-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPiM25.py
More file actions
4717 lines (3498 loc) · 164 KB
/
Copy pathPiM25.py
File metadata and controls
4717 lines (3498 loc) · 164 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) #
#br OLED/GPS Vcc +3.3V | +5.0V PM25 G3 pin 1 Vcc br#
#y OLED SDA GPIO 2 | +5.0V MOS Gas Sensor +5V p#
#o OLED SCL GPIO 3 | GND MCP3008 GND/GND br#
# GPIO 4 | UART TX #
#r OLED GND GND | UART RX #
#o MCP3008 CSbar GPIO 17 | GPIO 18 #
#y MCP3008 MOSI GPIO 27 | GND #
#g MCP3008 MISO GPIO 22 | GPIO 23 #
#r MCP3008 Vcc/Vref +3.3V | GPIO 24 PM25 G3 pin 5 TX g#
#bl MCP3008 CLK GPIO 10 | GND PM25 G3 pin 2 GND o#
# GPIO 9 | GPIO 25 #
# GPIO 11 | GPIO 8 #
# GND | GPIO 7 #
# Reserved | Reserved #
# GPIO 5 | GND #
# GPIO 6 | GPIO 12 GPS TX #
# GPIO 13 | GND GPS GND #
#b DHT22 POWER GPIO 19 | GPIO 16 #
#w DHT22 DATA GPIO 26 | GPIO 20 #
#gy DHT22 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
from binascii import hexlify
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import logging
import socket
import paho.mqtt.client as mqtt
import Queue
from threading import Thread, Lock, Event
# Currently available to future classes, consider moving inside OLED
OLED_screens_lock = Lock()
OLED_smbus_lock = Lock()
class BOX(object):
devkind = "BOX"
hints = """ You have to START HERE, all other classes instantiated from box.new_xxx()
box = BOX("name", use_WiFi=False, use_SMBus=True,
use_pigpio=True, use_LASS=False, use_MQTT=False)
use_WiFi=True turns on WiFi and ping the internet
use_MQTT=True will set up an MQTT client, connect, start looping...
subscribe, and test-publish."""
def __init__(self, name=None, use_WiFi=False, use_SMBus=True,
use_pigpio=True, use_LASS=False, use_MQTT=False):
self.hints = """box.ping_the_internet(pingable_url=None)
box.WiFi_onoff(set_WiFi=None)
start_MQTT()
disconnect_MQTT()
publish(payload, topic='test', qos=1)
subscribe(topic='test', qos=1)
unubscribe(topic='test')
mpu = box.new_MPU6050i2c(name=None, I2C_clockdiv=9, DLPF=2, divideby=100,
recordgyros=True, recordaccs=True, recordtemp=False,
n_gyro_scale=0, n_acc_scale=0, fifo_block_read=True,
chunkbytes=24, AD0=1)
step = box.new_STEPPER_MOTOR('my step", max_steprate=20, ramp_rate=10,
GPIO_A=GPIO, GPIO_B=GPIO, GPIO_C=GPIO, GPIO_D=GPIO)
G3 = box.new_G3bb("my g3", DATA=GPIO, collect_time=3)
gps = box.new_GPSbb("my gps", DATA=GPIO, collect_time=3)
dht = box.new_DHT22bb("my dht", DATA=None, POWER=None)
adc = box.new_MCP3008bb("my adc", CSbar=GPIO, MISO=GPIO,
MOSI=GPIO, SCLK=GPIO,
SPI_baud=10000, Vref=3.3)
CO2 = box.new_MOS_Gas_Sensor("my CO2", ADC="my adc", channel=1,
int_or_float=float, calibdatapairs=datapointlist,
divider_posn='bottom', R_series=5000, V_supply=5,
units_name='ppm', xlog = False, ylog = False,
xlimitsok=True)
oled = box.new_OLEDi2c("my oled", rotate180=False)
rtc = box.new_RTC_smbus("my rtc", baud=None)
dummy= box.new_Dummy("my dummy", dummydatadict=None)
lass = box.new_LASS_reporter("my lass"=None)
dlog = box.new_DATALOG(filename='deleteme.txt', name="my datalog",
configure_dict=None)
box.add_device(device)
box.get_device(device)
box.read_all_readables()
box.print_system_info()
box.stopall()"""
self.name = name
# atexit.register(self.stopall) # shutdown when exiting python
# internet and mqtt constants
self.ping_the_internet_default_url = "www.google.com"
self.mqtt_host_url = "gpssensor.ddns.net" # for LASS
self.mqtt_host_url_1 = "test.mosquitto.org" # other
self.mqtt_host_url_2 = "iot.eclipse.org" # other
self.mqtt_LASS_PM25_topic = "LASS/Test/PM25"
self.mqtt_test_topic = "LASS/Test/test"
self.mqtt_keepalive = 60
self.mqtt_port = 1883
mqtt.Client.connected_flag = False
self.internet_pingable = None
# Create and configure logger
self.logging_level = logging.DEBUG
self.logging_filename = "PiM25box_logging.log"
# self.logging_format = "%(levelname)s %(asctime)s - %(message)s"
self.logging_format = '%(levelname)s %(asctime)s %(funcName)s %(message)s '
self.logging_filemode = 'w'
logging.basicConfig(filename = self.logging_filename,
level = self.logging_level,
format = self.logging_format,
filemode = self.logging_filemode)
self.logger = logging.getLogger()
self.cname = self.__class__.__name__
self.logger = logging.getLogger()
console = logging.StreamHandler()
formatter = logging.Formatter(self.logging_format, "%Y-%m-%d %H:%M:%S")
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(console)
msg = (('{x.cname}("{x.name}") \n Instantiated new box ' +
'named "{x.name}"').format(x=self))
self.logger.info(msg)
msg = (('{x.cname}("{x.name}") \n Started Python logging, ' +
'level={x.logging_level}, filename="{x.logging_filename}"').format(x=self))
self.logger.info(msg)
# get locals for YAML saving in the future
self.instance_things = locals()
donts = ('self', 'name')
for dont in donts:
try:
self.instance_things.pop(dont)
except:
pass
# connections to the world
self.use_WiFi = use_WiFi
self.use_SMBus = use_SMBus
self.use_pigpio = use_pigpio
self.use_MQTT = use_MQTT
self.use_LASS = use_LASS # this is for extra safety
msg = (('{x.cname}("{x.name}") \n use_WiFi={x.use_WiFi}, use_SMBus={x.use_SMBus}, ' +
'use_pigpio={x.use_pigpio}').format(x=self))
self.logger.info(msg)
# lists of devices and objects
self.devices = []
self.readables = []
self.unreadables = []
self.dataloggers = []
self.LASS_reporters = []
# This Raspberry Pi's MAC address
self.mac_address = None
self.get_mac_address()
msg = ('{x.cname}("{x.name}") \n Found MAC address {x.mac_address}' +
'named "{x.name}"'.format(x=self))
self.logger.info(msg)
# This Raspberry Pi's WiFi
self._get_nWiFi()
if self.use_WiFi:
self.WiFi_onoff('on')
msg = (('{x.cname}("{x.name}") \n WiFi requested').format(x=self))
else:
msg = (('{x.cname}("{x.name}") \n WiFi NOT requested').format(x=self))
self.logger.info(msg)
WiFi_ison = self.WiFi_onoff() # double check
msg = (('{x.cname}("{x.name}") \n currently WiFi_ison={}').format(WiFi_ison, x=self))
self.logger.info(msg)
# This Raspberry Pi's internet connection
self.internet_pingable = self.ping_the_internet()
if self.internet_pingable:
msg = (('{x.cname}("{x.name}") \n Internet is pingable, yay!').format(x=self))
else:
msg = (('{x.cname}("{x.name}") \n ping_the_internet failed.').format(x=self))
self.logger.info(msg)
if True and self.use_WiFi: # Give some time for the WiFi connection to work
if not self.internet_pingable:
print " no ping, try again in 5 seconds"
time.sleep(5)
self.internet_pingable = self.ping_the_internet()
if not self.internet_pingable:
print " no ping, try again in 5 seconds"
time.sleep(5)
self.internet_pingable = self.ping_the_internet()
if not self.internet_pingable:
print " no ping, try again in 10 seconds"
time.sleep(10)
self.internet_pingable = self.ping_the_internet()
if not self.internet_pingable:
print " no ping, try again in 10 seconds"
time.sleep(10)
self.internet_pingable = self.ping_the_internet()
if not self.internet_pingable:
print "still no internet connection, BUT NOT setting use_MQTT to False."
self.use_MQTT = False
# This Raspberry Pi's MQTT
if self.use_MQTT:
status = self.start_MQTT()
if status==0:
msg = (('{x.cname}("{x.name}") \n start_MQTT okay ### status={}').format(status, x=self))
self.logger.info(msg)
else:
msg = (('{x.cname}("{x.name}") \n start_MQTT problem ### status={}').format(status, x=self))
self.logger.warning(msg)
# This Raspberry Pi's pigpio
self.pi = None
self.pigpiod_process = None
if self.use_pigpio:
msg = (('{x.cname}("{x.name}") \n make_a_pi() called').format(x=self))
self.make_a_pi()
else:
msg = (('{x.cname}("{x.name}") \n use pigpio not requested').format(x=self))
self.logger.info(msg)
# This Raspberry Pi's SMBus
self.bus = None
if self.use_SMBus:
self.bus = smbus.SMBus(1)
msg = (('{x.cname}("{x.name}") \n SMBus instantiated').format(x=self))
else:
msg = (('{x.cname}("{x.name}") \n SMBus NOT instantiated').format(x=self))
self.logger.info(msg)
def __repr__(self):
return ('{self.__class__.__name__}("{self.name}")'
.format(self=self))
def start_MQTT(self):
self.use_MQTT = True
print "trying to connect with MQTT: "
self.mqtt_client = mqtt.Client(client_id="Luke, I am your client",
clean_session=True, userdata=None,
transport="tcp") # protocol=MQTTv311 or MQTTv31
self.mqtt_client.reconnect_delay_set(min_delay=5, max_delay=120)
self.mqtt_client.on_connect = self._on_connect
self.mqtt_client.on_disconnect = self._on_disconnect
self.mqtt_client.on_log = self._on_log # or _on_log_verbose
self.mqtt_client.on_message = self._on_message
self.internet_pingable = self.ping_the_internet()
print "pingable is: ", self.internet_pingable
status_con = self.mqtt_client.connect(host=self.mqtt_host_url,
keepalive=self.mqtt_keepalive,
port=self.mqtt_port) # 5 https://stackoverflow.com/a/35581280/3904031
print "connect status: ", status_con
time.sleep(1)
status_loop = self.mqtt_client.loop_start()
print "loop_start status: ", status_loop
time.sleep(1)
# test message
status_pub1 = self.mqtt_client.publish(topic="test", payload="hello!", qos=1, retain=True) # 7 publish
self.test_qos1_mqtt_status = status_pub1
print "self.test_qos1_mqtt_status: ", self.test_qos1_mqtt_status
time.sleep(1)
status_pub2 = self.mqtt_client.publish(topic="test", payload="hello!", qos=2, retain=True) # 7 publish
self.test_qos2_mqtt_status = status_pub2
print "self.test_qos2_mqtt_status: ", self.test_qos2_mqtt_status
time.sleep(1)
return status_con
def _on_log(self, client, userdata, level, buf):
print("On Log: ", buf)
def _on_log_verbose(self, client, userdata, level, buf):
print ("On Log")
print " buf:", buf
print " level:", level
print " userdata:", userdata
print " client:", client
def _on_connect(self, client, userdata, flags, rc):
print ("Connect code: ", rc)
if rc == 0:
client.connected_flag = True
print ("Connect OK")
else:
print ("Connect failed, looping stopped")
client.loop.stop()
def _on_disconnect(self, client, userdata, flags, rc=0):
print ("Disconnect code: ", rc)
def _on_message(self, client, userdata, msg):
print "Message received: "
print " Topic: ", msg.topic
print " Message: ", str(msg.payload.decode("utf-8", "ignore"))
def publish(self, payload, topic='test', qos=1):
status = -1
if not ((type(payload) is str) and (len(payload)>0)):
print "bad payload"
print "type(payload): ", type(payload)
print "len(payload): ", len(payload)
return status
if not ((type(qos) is int) and (qos in (0, 1, 2))):
print "bad qos"
return status
if not ((type(topic) is str) and len(topic)>0):
print "bad topic"
return status
if topic.lower() == 'test':
topic = self.mqtt_test_topic
status = self.mqtt_client.publish(topic=topic,
payload=payload,
qos=qos, retain=True)
print "published!, status: ", status
return status
def subscribe(self, topic='test', qos=1):
status = -1
if not ((type(qos) is int) and (qos in (0, 1, 2))):
print "bad qos"
return status
if not ((type(topic) is str) and len(topic)>0):
print "bad topic"
return status
if topic.lower() == 'test':
topic = self.mqtt_test_topic[:]
status = self.mqtt_client.subscribe(topic=topic, qos=qos)
print "subscribed to topic={}, status={} ".format(status, topic)
return status
def unubscribe(self, topic='test'):
status = -1
if not ((type(topic) is str) and len(topic)>0):
print "bad topic"
return status
if topic.lower() == 'test':
topic = self.mqtt_test_topic
status = self.mqtt_client.unsubscribe(topic=topic)
print "unubscribed to topic={}, status={} ".format(status, topic)
return status
def disconnect_MQTT(self, ):
status = self.mqtt_client.loop_stop()
print "loop_stop status: ", status
time.sleep(1)
status = self.mqtt_client.disconnect()
print "disconnect status: ", status
return status
def ping_the_internet(self, pingable_url=None):
pingable = False
try:
if pingable_url == None:
pingable_url = self.ping_the_internet_default_url
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
status = s.connect_ex((pingable_url, 443))
pingable = status == 0
except:
pass
return pingable
def self_check(self):
msg = (('{x.cname}("{x.name}") \n box "{x.name}" self_check started').format(x=self))
self.logger.info(msg)
# check WiFi situation
wifi_is_on = self.WiFi_onoff() # check anyway
msg = (('{x.cname}("{x.name}") \n box "{x.name}" use_WiFi={x.use_WiFi}, '
+ 'WiFi is on={}').format(wifi_is_on, x=self))
self.logger.info(msg)
if self.use_WiFi and not wifi_is_on:
msg = (('{x.cname}("{x.name}") \n ...and that is a problem.').format(x=self))
self.logger.info(msg)
# check internet connectivity
self.internet_pingable = self.ping_the_internet()
msg = (('{x.cname}("{x.name}") \n box "{x.name}" use_WiFi={x.use_WiFi}, ' +
'internet pingable={}').format(self.internet_pingable, x=self))
self.logger.info(msg)
if self.use_WiFi and not self.internet_pingable:
msg = (('{x.cname}("{x.name}") \n ...and that is a problem.').format(x=self))
print (msg)
self.logger.info(msg)
if use_pigpio:
stat, procid = commands.getstatusoutput('sudo pidof pigpiod')
if not stat:
msg = (('{x.cname}("{x.name}") \n box "{x.name}" use_pigpio={x.use_pigpio}, ' +
'pigpio process ID={}').format(procid, x=self))
else:
msg = (('{x.cname}("{x.name}") \n box "{x.name}" use_pigpio={x.use_pigpio}, ' +
'but pigpio not running and that is a problem').format(x=self))
self.logger.info(msg)
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')
if status: # it wasn't running, so try to start it
msg = (('{x.cname}("{x.name}") \n pigpiod was not running, try to start').format(x=self))
self.logger.info(msg)
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 or if it's running...
self.pigpiod_process = process
msg = (('{x.cname}("{x.name}") \n pigpiod is running; ' +
'process ID={x.pigpiod_process}').format(x=self))
self.logger.info(msg)
try:
self.pi = pigpio.pi() # local GPIO only
msg = (('{x.cname}("{x.name}") \n Instantiated pi from pigpio').format(x=self))
self.logger.info(msg)
except Exception, e:
str_e = str(e)
msg = (('{x.cname}("{x.name}") \n problem instantiating pi: {}').format(str_e, x=self))
self.logger.warning(msg)
self.start_pigpiod_exception = str_e
def stop_pigpiod(self):
command = 'sudo kill {}'.format(self.pigpiod_process)
status_kill = commands.getstatusoutput(command)
time.sleep(1)
status_check, process = commands.getstatusoutput('sudo pidof pigpiod') # check it again
if status_check:
msg = (('{x.cname}("{x.name}") \n killed pigpiod.').format(x=self))
else:
msg = (('{x.cname}("{x.name}") \n tried to kill pigpiod but it is still running ' +
'with process ID: {}').format(process, x=self))
self.logger.info(msg)
def WiFi_onoff(self, set_WiFi=None):
if set_WiFi == None:
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
msg = (('{x.cname}("{x.name}") \n WiFi is off').format(x=self))
self.logger.info(msg)
elif isblocked == 'no':
WiFi_is_on = True
msg = (('{x.cname}("{x.name}") \n WiFi is on').format(x=self))
self.logger.info(msg)
else:
msg = (('{x.cname}("{x.name}") \n I cant tell if WiFi is on or off: ' +
'{}, {}').format(stat, out, x=self))
self.logger.warning(msg)
except:
msg = (('{x.cname}("{x.name}") \n problem checking WiFi status: ' +
'{}, {}').format(stat, out, x=self))
self.logger.warning(msg)
elif ((type(set_WiFi)==str and set_WiFi.lower() == 'on') or
(type(set_WiFi)==bool and set_WiFi)):
try:
stat, out = commands.getstatusoutput("sudo rfkill unblock " +
str(self.nWiFi))
if stat:
msg = (('{x.cname}("{x.name}") \n problem turning WiFi on: ' +
'{}, {}').format(stat, out, x=self))
self.logger.warning(msg)
else:
WiFi_is_on = True
except:
msg = (('{x.cname}("{x.name}") \n problem turning on WiFi: ' +
'{}, {}').format(stat, out, x=self))
self.logger.warning(msg)
elif ((type(set_WiFi)==str and set_WiFi.lower() == 'off') or
(type(set_WiFi)==bool and not set_WiFi)):
try:
stat, out = commands.getstatusoutput("sudo rfkill block " +
str(self.nWiFi))
if stat:
msg = (('{x.cname}("{x.name}") \n problem turning WiFi off: ' +
'{}, {}').format(stat, out, x=self))
self.logger.warning(msg)
else:
WiFi_is_on = False
except:
msg = (('{x.cname}("{x.name}") \n problem turning off WiFi: ' +
'{}, {}').format(stat, out, x=self))
self.logger.warning(msg)
else:
msg = (('{x.cname}("{x.name}") \n set WiFi status command not recognized: '+
'{}, {}').format(stat, out, x=self))
self.logger.warning(msg)
return WiFi_is_on
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
msg = (('{x.cname}("{x.name}") \n nWiFi={x.nWiFi}').format(x=self))
self.logger.info(msg)
except:
msg = (('{x.cname}("{x.name}") \n there was a problem checking nWiFi!').format(x=self))
self.logger.warning(msg)
self.nWiFi = None
# METHODS that involve MAC address
def get_mac_address(self):
ifconfig = commands.getoutput("ifconfig eth0 " +
" | grep HWaddr | " +
"awk '{print $5}'")
msg = ("this Raspberry Pi's ifconfig: {}".format(ifconfig))
self.logger.info(msg)
if type(ifconfig) is str:
possible_mac = ifconfig.replace(':','') # alternate
msg = (('{x.cname}("{x.name}") \n this Raspberry Pi possible MAC address={}')
.format(possible_mac, x=self))
self.logger.info(msg)
if len(possible_mac) == 12:
self.mac_address = possible_mac
msg = (('{x.cname}("{x.name}") \n this Raspberry Pi ' +
'MAC address={x.mac_address}').format(x=self))
self.logger.info(msg)
# METHODS that involve system status
def _get_system_info(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_system_info(self):
info_lines = self._get_system_info()
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:
msg = (('{x.cname}("{x.name}") \n device not added, device name is not str: {}')
.format(device.name, x=self))
self.logger.error(msg)
elif len(device.name) == 0:
msg = (('{x.cname}("{x.name}") \n device not added, zero-length string ' +
'name not allowed').format(x=self))
self.logger.error(msg)
elif self.get_device(device.name) is not None:
msg = (('{x.cname}("{x.name}") \n device with name "{}" not added, ' +
'that name is already present').format(device.name, x=self))
self.logger.error(msg)
else:
self.devices.append(device)
msg = (('{x.cname}("{x.name}") \n device with unique name "{}" successfully added')
.format(device.name, x=self))
self.logger.info(msg)
def new_LASS_reporter(self, name=None):
lass = LASS_reporter(box=self, name=name)
self.LASS_reporters.append(lass)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}"')
.format(x=self, y=lass))
self.logger.info(msg)
return lass
def new_DATALOG(self, filename='deleteme.txt', name=None,
configure_dict=None):
dlog = DATALOG(self, filename, name, configure_dict)
self.dataloggers.append(dlog)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" ' +
'filename={y.filename} configure_dict={y.configure_dict}').format(x=self, y=dlog))
self.logger.info(msg)
return dlog
def new_OLEDi2c(self, name, rotate180=False):
oled = OLEDi2c(box=self, name=name, rotate180=rotate180)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" ' +
'rotate180={y.rotate180}').format(x=self, y=oled))
self.logger.info(msg)
return oled
def new_G3bb(self, name, DATA=None, collect_time=None):
g3 = G3bb(box=self, name=name, DATA=DATA, collect_time=collect_time)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" DATA={y.DATA} '+
'collect_time={y.collect_time} ').format(x=self, y=g3))
self.logger.info(msg)
return g3
def new_GPSbb(self, name, DATA=None, collect_time=None):
gps = GPSbb(box=self, name=name, DATA=DATA, collect_time=collect_time)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" DATA={y.DATA} '+
'collect_time={y.collect_time} ').format(x=self, y=gps))
self.logger.info(msg)
return gps
def new_DHT22bb(self, name, DATA=None, POWER=None):
dht = DHT22bb(box=self, name=name, DATA=DATA, POWER=POWER)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" ' +
'DATA={y.DATA} POWER={y.POWER} ').format(x=self, y=dht))
self.logger.info(msg)
return dht
def new_MCP3008bb(self, name, CSbar=None, MISO=None,
MOSI=None, SCLK=None,
SPI_baud=None, Vref=None):
mcp3008 = MCP3008bb(box=self, name=name, CSbar=CSbar,
MISO=MISO, MOSI=MOSI, SCLK=SCLK,
SPI_baud=SPI_baud, Vref=Vref)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" CSbar={y.CSbar} '+
'MISO={y.MISO} MOSI={y.MOSI} SCLK={y.SCLK} SPI_baud={y.SPI_baud} Vref={y.Vref}')
.format(x=self, y=mcp3008))
self.logger.info(msg)
return mcp3008
def new_Analog_Device(self, name, ADC=None, channel=None,
int_or_float=float, calibdatapairs=None,
units_name=None, xlog = False, ylog = False,
xlimitsok=True):
device = Analog_Device(box=self, name=name,
ADC=ADC, channel=channel,
int_or_float=int_or_float,
calibdatapairs=calibdatapairs, units_name=units_name,
xlog = xlog, ylog = ylog, xlimitsok=xlimitsok)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" ADC={y.ADC} '+
'channel={y.channel} int_or_float={y.int_or_float} units_name={y.units_name} ' +
'xlog={y.xlog} ylog={y.ylog} xlimitsok = {y.xlimitsok}' +
'calibdatapairs={y.rawcalibdatapairs} ').format(x=self, y=device))
self.logger.info(msg)
return device
def new_MOS_Gas_Sensor(self, name, ADC=None, channel=None,
int_or_float=float, calibdatapairs=None,
divider_posn=None, R_series=None, V_supply=None,
units_name=None, gasname=None, xlog = False, ylog = False,
xlimitsok=True):
device = MOS_Gas_Sensor(box=self, name=name,
ADC=ADC, channel=channel, int_or_float=int_or_float,
calibdatapairs=calibdatapairs, divider_posn=divider_posn,
R_series=R_series, V_supply=V_supply, units_name=units_name, gasname=gasname,
xlog = xlog, ylog = ylog, xlimitsok=xlimitsok)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}" ADC={y.ADC} '+
'channel={y.channel} int_or_float={y.int_or_float} divider_posn={y.divider_posn} '+
'R_series={y.R_series} V_supply={y.V_supply} units_name={y.units_name} '+
'gasname={y.gasname} xlog={y.xlog} ylog={y.ylog} xlimitsok = {y.xlimitsok}' +
'sortedcalibdatapairs={y.sortedcalibdatapairs} ').format(x=self, y=device))
self.logger.info(msg)
return device
def new_RTC_smbus(self, name=None, baud=None):
rtc = RTC_smbus(box=self, name=name, baud=baud)
msg = (('{x.cname}("{x.name}") \n Adding new instance, ' +
'name="{y.name}" ').format(x=self, y=rtc))
self.logger.info(msg)
return rtc
def new_Dummy(self, name, dummydatadict=None):
dummy = Dummy(box=self, name=name, dummydatadict=dummydatadict)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{x.name}" ' +
'dummydatadict={y.dummydatadict}').format(x=self, y=dummy))
self.logger.info(msg)
return dummy
def new_STEPPER_MOTOR(self, name, max_steprate=None, ramp_rate=None,
GPIO_A=None, GPIO_B=None, GPIO_C=None, GPIO_D=None):
stepper = STEPPER_MOTOR(box=self, name=name, max_steprate=max_steprate,
ramp_rate=ramp_rate, GPIO_A=GPIO_A,
GPIO_B=GPIO_B, GPIO_C=GPIO_C, GPIO_D=GPIO_D)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}"'+
'max_steprate={y.max_steprate}, ramp_rate={y.ramp_rate}, ' +
'four_GPIOS = {y.four_GPIOS}').format(x=self, y=stepper))
self.logger.info(msg)
return stepper
def new_MPU6050i2c(self, name=None, I2C_clockdiv=None, DLPF=None,
divideby=None, recordgyros=None, recordaccs=None,
recordtemp=None, n_gyro_scale=None, n_acc_scale=None,
fifo_block_read=None, chunkbytes=None, AD0=None):
mpu = MPU6050i2c(box=self, name=name, I2C_clockdiv=I2C_clockdiv,
DLPF=DLPF, divideby=divideby, recordgyros=recordgyros,
recordaccs=recordaccs, recordtemp=recordtemp,
n_gyro_scale=n_gyro_scale, n_acc_scale=n_acc_scale,
fifo_block_read=fifo_block_read, chunkbytes=chunkbytes,
AD0=AD0)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}"').format(x=self, y=mpu))
self.logger.info(msg)
return mpu
def new_HMC5883i2c(self, name):
mag = HMC5883i2c(box=self, name=name)
msg = (('{x.cname}("{x.name}") \n Adding new instance, name="{y.name}"').format(x=self, y=mag))
self.logger.info(msg)
return mag
def clear_all_readables(self):
for device in self.readables:
device.datadict = dict() # easiest way to clear!
def read_all_readables(self):
results = []
for device in self.readables:
device.read()
results.append((str(device), device.ierr))
return results
def get_device(self, dev):
device = None
if dev in self.devices:
device = dev
else:
try:
device = [d for d in self.devices if d.name == dev][0]
except:
pass
return device
def stopall(self):
oleds = [dev for dev in self.devices if 'oled' in dev.devkind.lower()]
print " OLEDS: ", len(oleds)
for o in oleds:
print o
try:
o.stop_thread()
print ' successfully stoppped'
except:
print ' UNsuccessfully stoppped'
pass
# o.Turn_Off_Display() # hey try NOT DOING this
try:
self.disconnect_MQTT()
print ' MQTT successfully disconnected'
except:
print ' MQTT UNsuccessfully disconnected'
pass
print " all stop!"
class LASS_reporter(object):
devkind = "LASS"
def __init__(self, box, name=None):
self.hints = """set_static_location(latlon=tuple, alt=None)
set_sources(humsrc=None, tempsrc=None, pm25src=None,
pm1src=None, pm10src=None, timedatesrc=None,
GPSsrc=None, gassensors=None)
build_entry()
_generate_LASS_string()"""
self.box = box
self.name = name
self.cname = self.__class__.__name__
self.mac_address = box.mac_address
self.last_system_info = None # double check this should be here
self.devices = []
# six static box parameters for LASS
self.app = 'PiM25'
self.ver_app = '0.1.0'
self.device = 'PiM25Box ' + name
self.device_id = self.box.mac_address
self.ver_format = 3 # now version 3 see https://lass.hackpad.tw/LASS-data-format-9OcSHfWwyUx
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.static_fix = 0
self.static_num = 0