-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPiM25.py
More file actions
2145 lines (1556 loc) · 72.7 KB
/
PiM25.py
File metadata and controls
2145 lines (1556 loc) · 72.7 KB
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/env python
# -*- coding: utf-8 -*-
# SUGGESTED CONNECTIONS, but you can of course do it differenlty!
##############################################################
# Raspberry Pi 3 GPIO Pinout; Corner --> #
# (pin 1) | (pin 2) #
# OLED/GPS Vcc +3.3V | +5.0V GPS NEO6 Vcc #
# OLED SDA GPIO 2 | +5.0V PM25 G5 pin 1 Vcc b#
# OLED SCL GPIO 3 | GND PM25 G5 pin 2 GND o#
# GPIO 4 | UART TX #
# OLED/Gas GND GND | UART RX #
# GPIO 17 | GPIO 18 GPS NEO6 pin 5 TX #
# GPIO 27 | GND GPS NEO6 GND #
# GPIO 22 | GPIO 23 #
#r MCP3008 Vcc/Vref +3.3V | GPIO 24 PM25 G5 pin 5 TX g#
# GPIO 10 | GND DHT22 GND g#
# GPIO 9 | GPIO 25 DHT22 DATA b# #
# GPIO 11 | GPIO 8 DHT22 POWER p#
# GND | GPIO 7 #
# Reserved | Reserved #
# GPIO 5 | GND #
#b MCP3008 CLK GPIO 6 | GPIO 12 #
#g MCP3008 MISO GPIO 13 | GND (GPS GND) #
#y MCP3008 MOSI GPIO 19 | GPIO 16 (GPS TX) #
#o MCP3008 CSbar GPIO 26 | GPIO 20 #
#brMCP3008 GND/GND GND | GPIO 21 #
# (pin 39) | (pin 40) #
##############################################################
import pigpio, smbus
import atexit
import re, commands
import psutil # http://psutil.readthedocs.io/en/latest/
import yaml
import time, datetime
import numpy as np
import paho.mqtt.client as mqtt
import json
from binascii import hexlify
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import logging # heyhere
class BOX(object):
devkind = "BOX"
def __init__(self, name, use_WiFi=False, use_SMBus=False,
use_pigpio=False):
self.name = name
# Create and configure logger
LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename = "PiM25box_logging.log",
level = logging.DEBUG,
format = LOG_FORMAT,
filemode = 'w')
self.logger = logging.getLogger()
self.logger.info("box '{}' __init__".format(self.name))
self.instance_things = locals()
donts = ('self', 'name')
for dont in donts:
try:
self.instance_things.pop(dont)
except:
pass
self.name = name
self.use_WiFi = use_WiFi
self.use_SMBus = use_SMBus
self.use_pigpio = use_pigpio
self.devices = []
self.LOG_devices = []
self.LASS_devices = []
self.mac_address = None
self.get_mac_address()
if self.use_WiFi:
self._get_nWiFi()
self.WiFi_setstatus('on')
self.logger.info("WiFi_setstatus('on')")
else:
pass
print ' testing self.use_pigpio: ', self.use_pigpio
if self.use_pigpio:
print ' it was True'
self.make_a_pi()
self.logger.info("make_a_pi()")
else:
print ' it was False'
self.pi = None
self.pigpiod_process = None
if self.use_SMBus:
self.bus = smbus.SMBus(1)
self.logger.info("smbus.SMBus(1)")
else:
self.bus = None
def __repr__(self):
return ('{self.__class__.__name__}({self.name})'
.format(self=self))
def clear_all_device_datadicts(self):
for device in self.devices:
device.datadict = dict() # easiest way to clear!
def read_all_devices(self):
for device in self.devices:
device.read() # each device repopulates its datadict
def get_system_timedate_dict(self):
sysnow = datetime.datetime.now()
sysnow_str = sysnow.strftime("%Y-%m-%d %H:%M:%S")
sysdate_str = sysnow_str[:10]
systime_str = sysnow_str[11:]
sysmicroseconds_str = str(sysnow.microsecond)
systimedatedict = dict()
systimedatedict['sysnow_str'] = sysnow_str
systimedatedict['timestr'] = systime_str
systimedatedict['datestr'] = sysdate_str
systimedatedict['tickstr'] = sysmicroseconds_str
return systimedatedict
def make_a_pi(self):
status, process = commands.getstatusoutput('sudo pidof pigpiod') # check it
if status: # it wasn't running, so start it
print "pigpiod was not running"
self.logger.info("pigpiod was not running")
commands.getstatusoutput('sudo pigpiod') # start it
time.sleep(0.5)
status, process = commands.getstatusoutput('sudo pidof pigpiod') # check it again
if not status: # if it worked, i.e. if it's running...
self.pigpiod_process = process
print "pigpiod is running, process ID is: ", self.pigpiod_process
self.logger.info("pigpiod is running, process ID is: {}".format(self.pigpiod_process))
try:
self.pi = pigpio.pi() # local GPIO only
print "pi is instantiated successfully"
self.logger.info("pi is instantiated successfully")
except Exception, e:
str_e = str(e)
print "problem instantiating pi, the exception message is: ", str_e
self.logger.warning("problem instantiating pi: {}".format(str_e))
self.start_pigpiod_exception = str_e
# METHODS that involve WiFi
def WiFi_setstatus(self, on_or_off):
if type(on_or_off) is str:
if on_or_off.lower() == 'on':
self.WiFi_on()
elif on_or_off.lower() == 'off':
self.WiFi_off()
else:
print "WiFi_onoff unrecognized string"
self.logger.warning("WiFi_onoff unrecognized string: {}".format(on_or_off))
else:
if on_or_off:
self.WiFi_on()
else:
self.WiFi_off()
def get_WiFi_is_on(self):
WiFi_is_on = None
try:
stat, isblocked = commands.getstatusoutput("sudo rfkill list " +
str(self.nWiFi) +
" | grep Soft | awk '{print $3}'")
if isblocked == 'yes':
WiFi_is_on = False
print "WiFi is off"
self.logger.info("WiFi is off")
elif isblocked == 'no':
WiFi_is_on = True
print "WiFi is on"
self.logger.info("WiFi is on")
else:
print "can't tell if WiFi is on or off"
except:
print "problem checking WiFi status"
self.logger.warning("problem checking WiFi status")
return WiFi_is_on
def WiFi_on(self):
stat, out = commands.getstatusoutput("sudo rfkill unblock " + str(self.nWiFi))
if stat:
print "problem turning WiFi on" , stat, out
self.logger.warning("problem turning WiFi on")
def WiFi_off(self):
stat, out = commands.getstatusoutput("sudo rfkill block " + str(self.nWiFi))
if stat:
print "problem turning WiFi off"
self.logger.warning("problem turning WiFi off")
def _get_nWiFi(self):
stat, out = commands.getstatusoutput("sudo rfkill list | grep phy0 | awk '{print $1}'")
try:
self.nWiFi = int(out.replace(':', '')) # confirm by checking that it can be an integer
self.logger.info("nWiFi: {}".format(self.nWiFi)) # heyhere
except:
# print "there was an exception! "
self.logger.warning("there was a problem checking nWiFi!") # heyhere
self.nWiFi = None
# METHODS that involve ntpdate
def _do_ntpdate(self):
stat, out = commands.getstatusoutput("sudo ntpdate")
# needs work!
return stat, out
# METHODS that involve MAC address
def get_mac_address(self):
# https://stackoverflow.com/questions/159137/getting-mac-address
# Nice: https://forums.hak5.org/topic/20372-python-script-to-get-mac-address/
# Wow! https://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python
# also https://stackoverflow.com/questions/159137/getting-mac-address
ifconfig = commands.getoutput("ifconfig eth0 " +
" | grep HWaddr | " +
"awk '{print $5}'")
# print ' ifconfig: ', ifconfig
self.logger.info("ifconfig: {}".format(ifconfig))
if type(ifconfig) is str:
possible_mac = ifconfig.replace(':','') # alternate
if len(possible_mac) == 12:
self.mac_address = possible_mac
self.logger.info("self.mac_address: {}".format(possible_mac))
# METHODS that involve system status
def _get_some_system_info_lines(self):
info_lines = ['', '--------', '--------']
things = ('uname -a', 'lsb_release -a', 'df -h', 'free',
'vcgencmd measure_temp')
for thing in things:
err, msg = commands.getstatusoutput(thing)
if not err:
info_lines += ['COMMAND: ' + thing +
' returns: ' + msg, '--------']
else:
info_lines += ['COMMAND: ' + thing +
' returns: error', '--------']
info_lines += ['--------']
return info_lines
def print_some_system_info_lines(self):
info_lines = _get_some_system_info_lines()
for line in info_lines:
print line
def get_system_datetime(self):
sysnow = datetime.datetime.now()
sysnow_str = sysnow.strftime("%Y-%m-%d %H:%M:%S")
sysdate_str = sysnow_str[:10]
systime_str = sysnow_str[11:]
sysmicroseconds_str = str(sysnow.microsecond)
return sysnow_str
def show_CPU_temp(self):
temp = None
err, msg = commands.getstatusoutput('vcgencmd measure_temp')
#if not err:
#m = re.search(r'-?\d+\.?\d*', msg)
#try:
#temp = float(m.group())
#except:
#pass
# return temp
return msg
def add_device(self, device):
if type(device.name) is not str:
print "device not added, type(device.name) is not str: {}".format(device.name)
self.logger.error("device not added, type(device.name) is not str: {}".format(device.name)) # heyhere
elif len(device.name) == 0:
print "device not added, zero-length name not allowed"
self.logger.error("device not added, zero-length name not allowed") # heyhere
elif self.get_device(device.name) is not None:
print "device with name '{}' not added, that name is already present".format(device.name)
self.logger.error("device with name '{}' not added, that name is already present".format(device.name)) # heyhere
else:
self.devices.append(device)
print "device with unique name '{}' successfully added".format(device.name)
self.logger.info("device with unique name '{}' successfully added".format(device.name)) # heyhere
def new_G5bb(self, name, DATA=None, collect_time=None):
g5 = G5bb(box=self, name=name, DATA=DATA, collect_time=collect_time)
self.logger.info("new_G5bb: '{}'".format(g5.name))
return g5
def new_GPSbb(self, name, DATA=None, collect_time=None):
gps = GPSbb(box=self, name=name, DATA=DATA, collect_time=collect_time)
self.logger.info("new_GPSbb: '{}'".format(gps.name))
return gps
def new_DHT22bb(self, name, DATA=None, POWER=None):
dht = DHT22bb(box=self, name=name, DATA=DATA, POWER=POWER)
self.logger.info("new_DHT22bb: '{}'".format(dht.name))
return dht
def new_MCP3008bb(self, name, CSbar=None, MISO=None,
MOSI=None, SCLK=None, Vref=None):
mcp3008 = MCP3008bb(box=self, name=name, CSbar=CSbar,
MISO=MISO, MOSI=MOSI, SCLK=SCLK, Vref=Vref)
self.logger.info("new_MCP3008bb: '{}'".format(mcp3008.name))
return mcp3008
def new_MOS_gas_sensor(self, name, ADC=None, channel=None,
Rseries=None, Calibrationdata=None,
use_loglog=None, gasname=None,
atlimitsisokay=None):
gas_sensor = MOS_gas_sensor(box=self, name=name,
ADC=ADC, channel=channel, Rseries=Rseries,
Calibrationdata=Calibrationdata,
use_loglog=use_loglog, gasname=gasname,
atlimitsisokay=atlimitsisokay)
self.logger.info("new_MOS_gas_sensor: '{}'".format(gas_sensor.name))
return gas_sensor
def new_OLEDi2c(self, name):
oled = OLEDi2c(box=self, name=name)
self.logger.info("new_OLEDi2c: '{}'".format(oled.name))
return oled
def new_Dummy(self, name, dummydatadict=None):
dummy = Dummy(box=self, name=name, dummydatadict=dummydatadict)
self.logger.info("new_Dummy: '{}'".format(dummy.name))
return dummy
def get_device(self, devname):
try:
device = [d for d in self.devices if d.name == devname][0]
except:
device = None
return device
def new_LASS(self, name=None):
"""wrapper to make instantiation 'look nicer'"""
lass = LASS(self, name)
self.LASS_devices.append(lass)
self.logger.info("new_LASS: '{}'".format(lass.name))
return lass
def new_LOG(self, filename='deleteme.txt', name=None):
"""wrapper to make instantiation 'look nicer'"""
log = LOG(self, filename, name)
self.logger.info("new_LOG: '{}' filename: '{}'".format(log.name, log.filename))
return log
class LASS(object):
def __init__(self, box, name=None):
self.box = box
self.name = name
self.devkind = 'LASS'
self.box.logger.info("LASS '{}' __init__".format(self.name))
self.mac_address = box.mac_address
self.last_system_info = None # double check this should be here
self.devices = []
# six static box
self.app = 'PiM25'
self.ver_app = '0.1.0'
self.device = 'PiM25Box ' + name
self.device_id = None # replace with MAC yes mac YES mac yes!
self.ver_format = 3 # what does this mean? always 3
self.fmt_opt = 1 # (0) default (real GPS) (1) gps information invalid always 0 or 1
self.battery_level_static = 100.0
self.battery_mode_static = 1.0
self.motion_speed_static = 0.0
self.CPU_utilization_static = 0.0 # Hey link this up
self.sequence_number = 1
#self.static_lat = None
#self.static_lon = None
#self.static_alt = None
self.gps_lat = None
self.gps_lon = None
self.gps_alt = None
self.gps_fix = 0
self.gps_num = 0
# MQTT
self.client = mqtt.Client()
self.host = 'gpssensor.ddns.net'
self.topic = 'LASS/Test/PM25'
self.client.connect(self.host, 1883, 60)
def __repr__(self):
return ('{self.__class__.__name__}({self.name})'
.format(self=self))
def set_static_location(self, latlon=tuple, alt=None):
self.static_latlon = latlon
self.static_alt = alt
if type(latlon) == tuple and len(latlon) >= 2:
if all([type(x) in (float, int) for x in latlon[:2]]):
self.static_lat = latlon[0]
self.static_lon = latlon[1]
print "static latitude and longitude set."
self.box.logger.info("set static latitude: {} longitude: {}"
.format(self.static_lat, self.static_lon))
elif all([type(x) is str for x in latlon[:2]]):
try:
lat, lon = [float(x) for x in latlon[:2]]
self.static_lat = lat
self.static_lon = lon
print "static latitude and longitude set."
self.box.logger.info("set static latitude: {} longitude: {}"
.format(self.static_lat, self.static_lon))
except:
print "static latitude and longitude set has failed!"
self.box.logger.error("static latitude and longitude set has failed!")
pass
if type(alt) is float:
self.static_alt = alt
print "static altitude set."
self.box.logger.info("sstatic altitude set: {}".format(self.static_alt))
def set_sources(self, humsrc=None, tempsrc=None, pm25src=None,
pm1src=None, pm10src=None, timedatesrc=None,
GPSsrc=None, gassensors=None):
self.source_dict = dict()
self._lookup = {'humidity':{'DHT22':'s_h0', 'HTS221':'s_h1', 'SHT31':'s_h2',
'HTU21D':'s_h3', 'BME280':'s_h4', 'SHT25':'s_h5', 'G5':'s_h6',
'other':'s_h9'},
'temperature':{'DHT22':'s_t0', 'HTS221':'s_t1', 'SHT31':'s_t2',
'HTU21D':'s_t3', 'BME280':'s_t4', 'SHT25':'s_t5', 'G5':'s_t6',
'other':'s_t9'},
'PM25':{'G5':'s_d0', 'Panasonic':'s_d3', 'other':'s_d7'},
'PM1' :{'G5':'s_d1', 'other':'s_d8'},
'PM10':{'G5':'s_d2', 'other':'s_d9'}}
self._gaslookup = {'NH3':'s_g0', 'CO':'s_g1', 'NO2':'s_g2', 'C3H8':'s_g5',
'C4H10':'s_g4', 'CH4':'s_g5', 'H2':'s_g6',
'C2H5OH':'s_g7', 'CO2':'s_g8', 'TVOC':'s_gg'}
if humsrc:
param, source = 'humidity', humsrc
self.source_dict[self._lookup[param][source.devkind]] = (source, param)
self.box.logger.info("LASS {}: humsrc: {} param: {}"
.format(self.name, source, param))
if tempsrc:
param, source = 'temperature', tempsrc
self.source_dict[self._lookup[param][source.devkind]] = (source, param)
self.box.logger.info("LASS {}: tempsrc: {} param: {}"
.format(self.name, source, param))
if pm25src:
param, source = 'PM25', pm25src
self.source_dict[self._lookup[param][source.devkind]] = (source, param)
self.box.logger.info("LASS {}: pm25src: {} param: {}"
.format(self.name, source, param))
if pm1src:
param, source = 'PM1', pm1src
self.source_dict[self._lookup[param][source.devkind]] = (source, param)
self.box.logger.info("LASS {}: pm1src: {} param: {}"
.format(self.name, source, param))
if pm10src:
param, source = 'PM10', pm10src
self.source_dict[self._lookup[param][source.devkind]] = (source, param)
self.box.logger.info("LASS {}: pm10src: {} param: {}"
.format(self.name, source, param))
if not gassensors:
gassensors = []
for sensor in gassensors:
param, source, gasname = 'ppm', sensor, sensor.devkind
self.source_dict[self._gaslookup[gasname]] = (source, param)
self.box.logger.info("LASS {}: gas sensor: {} param: {}, gasname: {}"
.format(self.name, source, param, gasname))
if type(GPSsrc) is str and GPSsrc.lower() == 'static':
self.source_dict['gps_lat'] = ('static', 'static_lat')
self.source_dict['gps_lon'] = ('static', 'static_lon')
self.source_dict['gps_alt'] = ('static', 'static_alt')
self.source_dict['gps_fix'] = ('static', 'static_fix')
self.source_dict['gps_num'] = ('static', 'static_num')
self.fmt_opt = 1 # (0) default (real GPS) (1) gps information invalid always 0 or 1
self.box.logger.info("LASS {}: GPSsrc: {}:"
.format(self.name, 'static'))
else:
self.source_dict['gps_lat'] = (GPSsrc, 'latitude' )
self.source_dict['gps_lon'] = (GPSsrc, 'longitude')
self.source_dict['gps_alt'] = (GPSsrc, 'altitude' )
self.source_dict['gps_fix'] = (GPSsrc, 'fix' )
self.source_dict['gps_num'] = (GPSsrc, 'satnum' )
self.source_dict['gps_num'] = (GPSsrc, 'satnum' )
self.fmt_opt = 0 # (0) default (real GPS) (1) gps information invalid always 0 or 1
self.box.logger.info("LASS {}: GPSsrc: {}:"
.format(self.name, GPSsrc))
if type(timedatesrc) is str and timedatesrc.lower() == 'system':
self.source_dict['time'] = ('system', 'timestr')
self.source_dict['date'] = ('system', 'datestr')
self.source_dict['ticks'] = ('system', 'tickstr')
self.box.logger.info("LASS {}: timedatesrc: {}:"
.format(self.name, 'system'))
else:
self.source_dict['time'] = (timedatesrc, 'timestr')
self.source_dict['date'] = (timedatesrc, 'datestr')
self.source_dict['ticks'] = ('system', 'tickstr')
self.box.logger.info("LASS {}: timedatesrc: {}:"
.format(self.name, timedatesrc))
# 's_gx' g0, g1, g2, g3, g4, g5, g6 g7, g8, gg
# 's_gx' NH3, CO, NO2, C3H8, C4H10, CH4, H2, C2H5OH, SenseAir S8 CO2, TVOC
# 's_hx' h0, h1, h2, h3, h4, h5,
# 's_hx' DHT22, HTS221, SHT31, HTU21D, BME280, SHT25
# 's_tx' s_t0, s_t1, s_t2, s_t3, s_t4, s_t5
# 's_tx' DHT22, HTS221, SHT31, HTU21D, BME280, SHT25
# 's_dx' d0, d1, d2 d3
# 's_dx' PM2.5, PM10, PM1, Panasonic
def build_entry(self):
self.LASS_data = []
# static box information
self.LASS_data.append('ver_format=' + str(self.ver_format))
self.LASS_data.append('fmt_opt=' + str(self.fmt_opt))
self.LASS_data.append('app=' + str(self.app))
self.LASS_data.append('ver_app=' + str(self.ver_app))
self.LASS_data.append('device_id=' + str(self.device_id))
self.LASS_data.append('device=' + str(self.device))
systdd = self.box.get_system_timedate_dict()
for key, (source, param) in self.source_dict.items():
if (key in ('time', 'date', 'ticks') and source == 'system'):
thing = systdd[param]
if type(thing) is str and len(thing) >=8:
self.LASS_data.append(key + '=' + systdd[param])
elif ('gps' in key and source == 'static'):
thing = getattr(self, param)
if thing != None:
self.LASS_data.append(key + '=' + str(thing) )
else:
try:
thing = source.datadict[param]
if thing != None:
self.LASS_data.append(key + '=' + str(thing))
except:
pass
# https://www.saltycrane.com/blog/2008/11/python-datetime-time-conversions/
# sequence number
self.LASS_data.append('s_0=' + str(self.sequence_number))
self.sequence_number += 1
# battery level
self.LASS_data.append('s_1=' + str(self.battery_level_static))
# battery mode
self.LASS_data.append('s_2=' + str(self.battery_mode_static))
# motion speed
self.LASS_data.append('s_3=' + str(self.motion_speed_static))
# CPU utilization
# http://psutil.readthedocs.io/en/latest/
self.CPU_utilization = psutil.cpu_percent()
self.LASS_data.append('s_4=' + str(self.CPU_utilization))
self._generate_LASS_string()
self.send_to_LASS()
def _generate_LASS_string(self):
self.LASS_string = '|'.join([''] + self.LASS_data + [''])
self.box.logger.info("LASS_string '{}'".format(self.LASS_string))
return self.LASS_string
def send_to_LASS(self):
print "=============================="
print time.ctime(), self.LASS_string
self.box.logger.info("send_to_LASS: {}".format(self.LASS_string))
self.client.publish(self.topic, "%s" % ( self.LASS_string ))
print "=============================="
# return self.LASS_string
pass
def build_and_send_to_LASS(self):
self.build_entry()
self.send_to_LASS()
return self.LASS_string
# ['ver_format', 'fmt_opt', 'app', 'ver_app', 'device_id', 'tick',
# 'date', 'time', 'device', 's_0', 's_1', 's_2', 's_3', 's_d0',
# 's_t0', 's_h0', 'gps_lat', 'gps_lon', 'gps_fix', 'gps_num',
# 'gps_alt']
# time hh:mm:ss
# date yyyy-mm-dd
# 's_0' # sequence number
# 's_1' # battery level
# 's_2' # battery mode vs charging
# 's_3' # motion speed
# 's_4' # CPU utiliation
# 's_bx' # barometer b0, b1, b2 = Grove, BMP180, BME280
# 's_dx' # dust d0, d1, d2 is PM2.5, PM10, PM1, d3 Panasonic
# 's_gx' # gas g0, g1, g2, g3, g4, g5, g6 g7, g8, gg
# 's_gx' # gas NH3, CO, NO2, C3H8, C4H10, CH4, H2, C2H5OH, SenseAir S8 CO2, TVOC
# 's_hx' # h0, h1, h2, h3, h4, h5, DHT22, HTS221, SHT31, HTU21D, BME280, SHT25
# 's_Ix' # light
# 's_nx' # radiation
# 's_ox' # other, misc
# 's_px' # rain
# 's_sx' # sound
# 's_tx' # temperature, t0, t1, t2, t3, t4, t5 is DHT22, HTS221, SHT31, HTU21D, BME280, SHT25
# 's_wx' # winds w0, w1 speed, direction
# 's_rx' # rainfall r10, r60 is 10 and 60 minutes
class LOG(object):
def __init__(self, box, filename, name=None):
self.box = box
self.name = name
self.filename = filename
self.devices = []
self.box.logger.info("LOG '{}' __init__ logfilename: '{}'"
.format(self.name, self.filename))
self.t_previous_sysinfo = None
headerlines = []
headerlines.append('New log file, filename = ' + str(self.filename))
headerlines.append('New log file, log name = ' + str(self.name))
datetimedict = self.box.get_system_timedate_dict()
headerlines.append('Time = ' + datetimedict['timestr'])
headerlines.append('Date = ' + datetimedict['datestr'])
headerlines.append('box name = ' + str(self.box.name))
try:
headerlines.append('box MAC address = ' +
str(self.box.macaddress))
except:
pass
with open(filename, 'w') as outfile:
outfile.writelines([line + '\n' for line in headerlines])
def __repr__(self):
return ('{self.__class__.__name__}({self.name})'
.format(self=self))
def configure(self, logconfigure_dict):
for device, datakeys in logconfigure_dict.items():
if device in self.box.devices:
self.devices.append((device, datakeys))
# does not test if datakeys are there, device may be flexible.
else:
print "Not added. This is not in box.devices"
def build_entry(self, sysinfo_interval=None):
self.datadict = dict()
self.datadict['buildtime'] = self.box.get_system_datetime()
try:
time_since = time.time() - self.t_previous_sysinfo
except:
time_since = None
if ((time_since == None) or
(time_since > sysinfo_interval) or
(sysinfo_interval<=0)):
sysinfolines = self.box._get_some_system_info_lines()
self.datadict['sysinfolines'] = sysinfolines
self.t_previous_sysinfo = time.time()
for device, datakeys in self.devices:
devdict = dict()
self.datadict[device.name] = devdict
for dk in datakeys:
try:
devdict[dk] = device.datadict[dk]
except:
pass
def save_entry(self):
lines = []
try:
lines += self.datadict.pop('sysinfolines')
except:
pass
for key, info in self.datadict.items():
lines += [key]
if type(info) is list:
lines += info
elif type(info) is str:
lines += [info]
elif type(info) is dict:
for datakey, data in info.items():
lines += [' datakey: ' + datakey + ' = ' + str(data)]
with open(self.filename, 'a') as outfile: # note, append!!!
outfile.writelines([line + '\n' for line in lines])
self.log_entry_lines = lines # save for debugging
def build_and_save_entry(self, sysinfo_interval=None):
self.build_entry(sysinfo_interval=sysinfo_interval)
self.save_entry()
class GPIO_DEVICE(object):
def __init__(self, box, name=None):
self.box = box
self.pi = self.box.pi
self.bus = self.box.bus
self.name = name
self.datadict = dict()
self.statistics = {'nreads':0, 'ngoodreads':0,
'nbadreads':0} # minimal each may have more
self.last_twenty_stats = []
self.box.add_device(self)
donts = ('self', 'name', 'box')
for dont in donts:
try:
self.instance_things.pop(dont)
except:
pass
def __repr__(self):
return ('{self.__class__.__name__}({self.name})'
.format(self=self))
def get_my_current_instance_info(self):
current_info = dict()
for key in self.instance_things:
current_info[key] = getattr(self, key)
return current_info
def get_my_original_instance_info(self):
original_info = self.instance_things.copy()
return original_info
def _last_twenty_increment(self):
self.last_twenty_stats = ([self.last_read_is_good] +
self.last_twenty_stats[:19])
class Dummy(GPIO_DEVICE):
devkind = 'Dummy'
def __init__(self, box, name, dummydatadict=None):
self.instance_things = locals()
GPIO_DEVICE.__init__(self, box, name)
self.box.logger.info("Dummy '{}' __init__".format(self.name))
if type(dummydatadict) == dict:
self.datadict.update(dummydatadict)
def read(self): # doesn't really read anything
self.last_read_is_good = False
self.statistics['nreads'] += 1
self.datadict['read_time'] = time.time()
self.last_read_is_good = True # it's a dummy!
if self.last_read_is_good:
self.statistics['ngoodreads'] += 1
else:
self.statistics['nbadreads'] += 1
self._last_twenty_increment()
class G5bb(GPIO_DEVICE):
devkind = "G5"
def __init__(self, box, name, DATA, collect_time=None):
self.instance_things = locals()
GPIO_DEVICE.__init__(self, box, name)
self.box.logger.info("G5bb '{}' __init__".format(self.name))
if collect_time == None:
collect_time = 3.0
self.collect_time = collect_time
self.DATA = DATA
self.baud = 9600
self.key = '424d'
def read(self):
self.datadict = dict() # assures the old dict has been cleared.
self.last_read_is_good = False
self.statistics['nreads'] += 1
try:
self.pi.bb_serial_read_close(self.DATA)
except:
pass
self.pi.bb_serial_read_open(self.DATA, self.baud)
time.sleep(self.collect_time)
self.datadict['start_read_time'] = time.time()
size, data = self.pi.bb_serial_read(self.DATA)
#data_hexlified = hexlify(data)
try:
import struct
except ImportError:
import ustruct as struct
buffer = []
data = list(data)
buffer += data
while buffer and buffer[0] != 0x42:
buffer.pop(0)
if len(buffer) > 200:
buffer = [] # avoid an overrun if all bad data
if buffer[1] != 0x4d:
buffer.pop(0)
check = sum(buffer[0:30])
chksum = buffer[30]*256 + buffer[31]
if check == chksum:
PM1 = buffer[10]*256 + buffer[11]
PM25 = buffer[12]*256 + buffer[13]
PM10 = buffer[14]*256 + buffer[15]
try:
temperature = int(buffer[24]*256 + buffer[25])/10
humidity = int(buffer[26]*256 + buffer[27])/10
self.datadict['humidity'] = humidity
self.datadict['temperature'] = temperature
except:
pass
self.datadict['PM1'] = PM1
self.datadict['PM25'] = PM25
self.datadict['PM10'] = PM10
self.last_read_is_good = True
if self.last_read_is_good:
self.statistics['ngoodreads'] += 1
else:
self.statistics['nbadreads'] += 1
self._last_twenty_increment()
class GPSbb(GPIO_DEVICE):
devkind = "GPS" # "u-blox NEO 6, 7"
def __init__(self, box, name, DATA, collect_time=None):
self.instance_things = locals()
GPIO_DEVICE.__init__(self, box, name)
self.box.logger.info("GPSbb '{}' __init__".format(self.name))
if collect_time == None:
collect_time = 3.0
self.DATA = DATA
# okdict = {'GNGGA':15, 'GNRMC':13, 'GNGLL':8}
# latlonstartdict = {'GNGGA':2, ' GNRMC':3, 'GNGLL':1}
# timestartdict = {'GNGGA':1, ' GNRMC':1, 'GNGLL':5}
self.sentence_type = "$GNGGA"
self.ok_length = 15
self.speed_sentence_type = "$GNVTG" # speed
self.speed_ok_length = 10
self.satpos_sentence_type = "$GPGSV" # satellite positions
self.DATA = DATA
self.baud = 9600
if collect_time == None:
collect_time = 3.
self.collect_time = collect_time
def _read_chunk(self):
try:
self.status = self.pi.bb_serial_read_close(self.DATA)
except:
self.status = None
pass
self.status = self.pi.bb_serial_read_open(self.DATA, self.baud)
time.sleep(self.collect_time)
size, data = self.pi.bb_serial_read(self.DATA)
lines = ''.join(chr(x) for x in data)
self.status = self.pi.bb_serial_read_close(self.DATA)
return lines.splitlines()
def _get_degs(self, string, hemisphere):
A, B = string.split('.')
mins = float(A[-2:]) + float('0.' + B)
degs = float(A[:-2])