forked from haydnw/AirPi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
airpi.py
executable file
·1412 lines (1199 loc) · 50.2 KB
/
airpi.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/env python
"""Start sampling with an AirPi board.
This is the main script file for sampling air quality and / or weather
data with an AirPi board on a Raspberry Pi. It takes configuration
settings from a number of config files, and outputs data from the
specified sensors in one or more requested formats. Errors notifications
can be raised via several methods.
See: http://airpi.es
http://github.com/haydnw/airpi
"""
import sys
sys.dont_write_bytecode = True
# We don't import individual sensors classes etc.
# here because they are imported dynamically below.
import socket
import RPi.GPIO as GPIO
import ConfigParser
import datetime
import time
import inspect
import os
import signal
import urllib2
import logging
import subprocess
from logging import handlers
from math import isnan
from sensors import sensor
from outputs import output
from supports import support
from notifications import notification
class MissingField(Exception):
"""Exception to raise when an imported plugin is missing a required
field.
"""
pass
def format_msg(msg, msgtype):
"""Format messages for consistency.
Format messages in a consistent format for display to the user, or
for recording in the LOGGER.
Args:
msg: The message to be formatted.
msgtype: The type of message represented by msg.
Returns:
The formatted string.
"""
msgtypes = ['error', 'warning', 'info']
if msgtype in msgtypes:
return(msgtype.upper() + ":").ljust(8, ' ') + " " + msg
elif msgtype is 'sys':
return("[AirPi] " + msg)
else:
return(msgtype.title() + ":").ljust(8, ' ') + " " + msg
def logthis(kind, msg):
""" Add spaces to align debug output.
Add spaces to LOGGER messages, so that debug output is nicely
aligned and therefore more readable.
Args:
kind: The kind of message to be processed.
msg: The message to be processed.
"""
if kind == "debug" or kind == "error":
LOGGER.debug(" " + msg)
else:
LOGGER.info(" " + msg)
def get_subclasses(mod, cls):
"""Load subclasses for a module.
Load the named subclasses for a specified module. Keys are named
'dummy' because they are not used, and calling them this means that
Pylint doesn't throw a message about them not being used.
Args:
mod: Module from which subclass should be loaded.
cls: Subclass to load
Returns:
The subclass.
"""
for dummy, obj in inspect.getmembers(mod):
if hasattr(obj, "__bases__") and cls in obj.__bases__:
return obj
def check_conn():
"""Check internet connectivity.
Check for internet connectivity by trying to connect to a website.
Returns:
boolean True if successfully connects to the site within five
seconds.
boolean False if fails to connect to the site within five
seconds.
"""
try:
urllib2.urlopen("http://www.google.com", timeout=5)
return True
except urllib2.URLError:
pass
return False
def led_setup(redpin, greenpin):
"""Set up AirPi LEDs.
Carry out initial setup of AirPi LEDs, including setting them to
'off'.
Args:
redpin: GPIO pin number for red pin.
greenpin: GPIO pin number for green pin.
"""
if redpin:
GPIO.setup(redpin, GPIO.OUT, initial=GPIO.LOW)
if redpin:
GPIO.setup(greenpin, GPIO.OUT, initial=GPIO.LOW)
def led_on(pin):
"""Turn LED on.
Turn on an AirPi LED at a given GPIO pin number.
Args:
pin: Pin number of the LED to turn on.
"""
GPIO.output(pin, GPIO.HIGH)
def led_off(pin):
"""Turn LED off.
Turn off an AirPi LED at a given GPIO pin number.
Args:
pin: Pin number of the LED to turn off.
"""
GPIO.output(pin, GPIO.LOW)
def get_serial():
"""Get Raspberry Pi serial no.
Get the serial number of the Raspberry Pi.
See: http://raspberrypi.nxez.com/2014/01/19/
getting-your-raspberry-pi-serial-number-using-python.html
Returns:
string The serial number, or an error string.
"""
cpuserial = "0000000000000000"
try:
thefile = open('/proc/cpuinfo', 'r')
for line in thefile:
if line[0:6] == 'Serial':
cpuserial = line[10:26]
thefile.close()
except Exception:
cpuserial = "ERROR000000000"
return cpuserial
def get_hostname():
"""Get current hostname.
Get the current hostname of the Raspberry Pi.
Returns:
string The hostname.
"""
if socket.gethostname().find('.') >= 0:
return socket.gethostname()
else:
return socket.gethostbyaddr(socket.gethostname())[0]
def set_cfg_paths():
"""Set paths to cfg files.
Set the paths to config files. Assumes that they are in a
sub-directory called 'cfg', within the same directory as the current
script (airpi.py).
Returns:
dict The paths to the various config files.
"""
cfgpaths = {}
basedir = os.path.abspath('.')
if basedir == "/":
basedir = "/home/pi/AirPi"
cfgdir = os.path.join(basedir, 'cfg')
cfgpaths['settings'] = os.path.join(cfgdir, 'settings.cfg')
cfgpaths['sensors'] = os.path.join(cfgdir, 'sensors.cfg')
cfgpaths['outputs'] = os.path.join(cfgdir, 'outputs.cfg')
cfgpaths['notifications'] = os.path.join(cfgdir, 'notifications.cfg')
cfgpaths['supports'] = os.path.join(cfgdir, 'supports.cfg')
logdir = os.path.join(basedir, 'log')
cfgpaths['log'] = os.path.join(logdir, 'airpi.log')
return cfgpaths
def set_up_logger():
"""Set up a logger.
Set up a logger to be used for this main script.
"""
thislogger = logging.getLogger(__name__)
thislogger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(CFGPATHS['log'],
maxBytes=40960, backupCount=5)
thislogger.addHandler(handler)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
return thislogger
def check_cfg_file(filetocheck):
"""Check cfg file exists.
Check whether a specified cfg file exists. Print and log a warning
if not. Log the file name if it does exist.
Args:
filetocheck: The file to check the existence of.
Returns:
boolean True if the file exists.
"""
if not os.path.isfile(filetocheck):
msg = "Unable to access config file: " + filetocheck
print(msg)
logthis("error", msg)
exit(1)
else:
msg = "Config file: " + filetocheck
logthis("info", msg)
return True
def any_plugins_enabled(plugins, plugintype):
"""Warn user if no plugins in a list are enabled.
Print and log a message if the list of enabled plugins is empty,
i.e. there are no plugins enabled.
Args:
plugins: Array of plugins to check.
type: The type of plugin being checked.
Returns:
boolean True if there are any plugins enabled.
"""
if not plugins:
msg = "There are no " + plugintype + " plugins enabled!"
msg += " Please enable at least one and try again."
print(msg)
logthis("error", msg)
sys.exit(1)
else:
return True
def set_up_supports():
"""Set up AirPi support plugins.
Set up AirPi support plugins by reading supports.cfg to determine
which should be enabled.
Returns:
list A list containing the enabled 'support' objects.
"""
print("==========================================================")
msg = format_msg("SUPPORTS", 'loading')
print(msg)
check_cfg_file(CFGPATHS['supports'])
SUPPORTCONFIG = ConfigParser.SafeConfigParser()
SUPPORTCONFIG.read(CFGPATHS['supports'])
SUPPORTNAMES = SUPPORTCONFIG.sections()
supportplugins = {}
for plugin in SUPPORTNAMES:
try:
try:
filename = SUPPORTCONFIG.get(plugin, "filename")
except Exception:
msg = "No filename config option found for support plugin "
msg += str(plugin)
msg = format_msg(msg, 'error')
print(msg)
raise
try:
enabled = SUPPORTCONFIG.getboolean(plugin, "enabled")
except Exception:
enabled = True
#if enabled, load the plugin
if enabled:
try:
# 'a' means nothing below, but argument must be non-null
mod = __import__('supports.' + filename, fromlist=['a'])
msg = "Successfully imported support module: " + filename
msg = format_msg(msg, 'success')
logthis("info", msg)
except Exception:
msg = "Could not import support module " + filename
msg = format_msg(msg, 'error')
print(msg)
raise
try:
msg = "Trying to get subclass for " + filename
msg = format_msg(msg, 'info')
logthis('info', msg)
supportclass = get_subclasses(mod, support.Support)
msg = "Successfully got subclasses for " + filename
msg = format_msg(msg, 'success')
logthis("info", msg)
if supportclass == None:
raise AttributeError
except Exception:
msg = "Could not find a subclass of support.Support in"
msg += " module " + filename
msg = format_msg(msg, 'error')
print(msg)
raise
try:
logthis("info", "Starting to set instclass for " + filename)
instclass = supportclass(SUPPORTCONFIG)
logthis("info", "Support plugin params are: " + str(instclass.params))
msg = "Successfully set instclass for " + filename
msg = format_msg(msg, 'success')
logthis("info", msg)
supportplugins[instclass.name.lower()] = instclass
msg = "Loaded support plugin " + str(plugin)
msg = format_msg(msg, 'success')
print(msg)
LOGGER.info("*******************")
except Exception as excep:
msg = "Failed to import support plugin " + plugin
msg = format_msg(msg, 'error')
print(msg)
logthis("info", msg)
else:
# Plugin is not enabled
supportplugins[filename] = False
except Exception as excep: #add specific exception for missing module
msg = "Did not import support plugin " + str(plugin) + ": " + str(excep)
msg = format_msg(msg, 'error')
print(msg)
raise excep
return supportplugins
def set_up_sensors():
"""Set up AirPi sensors.
Set up AirPi sensors by reading sensors.cfg to determine which
should be enabled, then checking that all required fields are
present in sensors.cfg.
Returns:
list A list containing the enabled 'sensor' objects.
"""
print("==========================================================")
msg = format_msg("SENSORS", 'loading')
print(msg)
check_cfg_file(CFGPATHS['sensors'])
SENSORCONFIG = ConfigParser.SafeConfigParser()
SENSORCONFIG.read(CFGPATHS['sensors'])
SENSORNAMES = SENSORCONFIG.sections()
sensorplugins = []
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) #Use BCM GPIO numbers.
for i in SENSORNAMES:
try:
# See if the plugin is enabled
try:
enabled = SENSORCONFIG.getboolean(i, "enabled")
logthis("info", str(i) + " requested: " + str(enabled))
except Exception as excep:
enabled = True
# If enabled, load the plugin
if enabled:
try:
filename = SENSORCONFIG.get(i, "filename")
logthis("info", "Filename is: " + filename)
except Exception:
msg = "No filename config option found for sensor plugin "
msg += str(i)
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise
try:
# 'a' means nothing below, but argument must be non-null
logthis("info", "Trying to import sensors." + filename)
mod = __import__('sensors.' + filename, fromlist=['a'])
logthis("info", "Successfully imported sensors." + filename)
except Exception as excep:
msg = "Could not import sensor module " + filename
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise
try:
sensorclass = get_subclasses(mod, sensor.Sensor)
if sensorclass == None:
raise AttributeError
except Exception:
msg = "Could not find a subclass of sensor.Sensor in"
msg += " module " + filename
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise
try:
reqd = sensorclass.requiredData
except Exception:
reqd = []
msg = "Unable to determine required parameters for the sensor."
msg = format_msg(msg, 'error')
print(msg)
try:
opt = sensorclass.optionalData
except Exception:
msg = "Unable to determine optional parameters for the sensor."
msg = format_msg(msg, 'error')
print(msg)
opt = []
# Sensors don't have any common params, so this is empty
common = []
#TODO: Get rid of this when it's all activated in Output
plugindata = define_plugin_params(SENSORCONFIG,
i, reqd, opt, common)
try:
instclass = sensorclass(plugindata)
except Exception:
if "serial_gps" not in filename:
msg = "Unable to set instclass for sensor using plugindata."
else:
msg = " GPS instance not created - socket not set up?"
msg = format_msg(msg, 'error')
LOGGER.error(msg)
raise
# Check for a getval() method
if callable(getattr(instclass, "getval", None)):
sensorplugins.append(instclass)
# Store sensorplugins array length for GPS plugin
if "serial_gps" in filename:
global gpsplugininstance
gpsplugininstance = instclass
msg = "Loaded sensor plugin " + str(i)
msg = format_msg(msg, 'success')
print(msg)
else:
msg = "Loaded sensor support plugin " + str(i)
msg = format_msg(msg, 'success')
print(msg)
except Exception as excep:
# TODO: add specific exception for missing module
msg = "Did not import sensor plugin " + str(i) + ": " + str(excep)
msg = format_msg(msg, 'error')
print(msg)
continue
LOGGER.info("*******************")
if any_plugins_enabled(sensorplugins, 'sensor'):
return sensorplugins
def set_up_outputs():
"""Set up AirPi output plugins.
Set up AirPi output plugins by reading outputs.cfg to determine
which should be enabled, then checking that all required fields are
present in outputs.cfg.
Returns:
list A list containing the enabled 'output' objects.
"""
print("==========================================================")
msg = format_msg("OUTPUTS", 'loading')
print(msg)
check_cfg_file(CFGPATHS['outputs'])
OUTPUTCONFIG = ConfigParser.SafeConfigParser()
OUTPUTCONFIG.read(CFGPATHS['outputs'])
OUTPUTNAMES = OUTPUTCONFIG.sections()
if "Notes" in OUTPUTNAMES:
OUTPUTNAMES.remove("Notes")
outputplugins = []
for plugin in OUTPUTNAMES:
try:
try:
filename = OUTPUTCONFIG.get(plugin, "filename")
except Exception:
msg = "No filename config option found for output plugin "
msg += str(plugin)
msg = format_msg(msg, 'error')
print(msg)
raise
try:
enabled = OUTPUTCONFIG.getboolean(plugin, "enabled")
except Exception:
enabled = True
#if enabled, load the plugin
if enabled:
try:
# 'a' means nothing below, but argument must be non-null
mod = __import__('outputs.' + filename, fromlist=['a'])
msg = "Successfully imported output module: " + filename
msg = format_msg(msg, 'success')
logthis("info", msg)
except Exception:
msg = "Could not import output module " + filename
msg = format_msg(msg, 'error')
print(msg)
raise
try:
msg = "Trying to get subclass for " + filename
msg = format_msg(msg, 'info')
logthis('info', msg)
outputclass = get_subclasses(mod, output.Output)
msg = "Successfully got subclasses for " + filename
msg = format_msg(msg, 'success')
logthis("info", msg)
if outputclass == None:
raise AttributeError
except Exception:
msg = "Could not find a subclass of output.Output in"
msg += " module " + filename
msg = format_msg(msg, 'error')
print(msg)
raise
try:
logthis("info", "Starting to set instclass for " + filename)
instclass = outputclass(OUTPUTCONFIG)
logthis("info", "Output plugin params are: " + str(instclass.params))
msg = "Successfully set instclass for " + filename
msg = format_msg(msg, 'success')
logthis("info", msg)
outputplugins.append(instclass)
msg = "Loaded output plugin " + instclass.name
msg = format_msg(msg, 'success')
print(msg)
LOGGER.info("*******************")
except Exception as excep:
msg = "Failed to import plugin " + plugin + ": " + str(excep)
msg = format_msg(msg, 'error')
print(msg)
logthis("info", msg)
except Exception as excep: #add specific exception for missing module
msg = "Did not import output plugin " + str(plugin) + ": " + str(excep)
msg = format_msg(msg, 'error')
print(msg)
raise excep
if any_plugins_enabled(outputplugins, 'output'):
# TODO: Fix this to look at plugin.params["target"]
#return fix_duplicate_outputs(outputplugins)
return outputplugins
def fix_duplicate_outputs(plugins):
"""Ensure only one output plugin for stdout is enabled.
Check whether the list of enabled output plugins includes more than
one which prints to stdout. If it does, disable all except Print to
avoid mayhem on screen!
Args:
plugins: A list containing the enabled output plugin
objects.
Returns:
list A new list of enabled output plugin objects, containing
only one plugin which outputs to screen.
"""
enabled = []
for index, plugin in enumerate(plugins):
name = plugin.getname()
if plugin.target == "screen":
thisPlugin = {}
thisPlugin["name"] = name
thisPlugin["index"] = index
enabled.append(thisPlugin)
removed = 0 # pop() changes indices; this helps us keep track
if len(enabled) >= 2:
for plugin in enabled:
if plugin["name"] != "Print":
plugins.pop(plugin["index"] - removed)
removed += 1
msg = "Only one plugin can output to screen at at time."
msg += os.linesep
msg += " Print is enabled; others have been disabled."
msg = format_msg(msg, 'warning')
print(msg)
return plugins
def define_plugin_params(config, name, reqd, opt, common):
"""Define setup parameters for an plugin.
Take a list of parameters supplied by the user ('config'), and
compare to the separate lists of 'required', 'optional' and 'common'
parameters for the plugin. Check that 'required' ones are present
(raise a MissingField exception if not). Merge all three dicts into
one 'params' dict that holds all setup parameters for this plugin,
then tag metadata and async info on to the end.
Parameters supplied by the user usually come from the relevant cfg
file, while the lists of 'required', 'optional' and 'common'
parameters are normally defined in the plugin Class.
Args:
config: The configparser containing the parameters defined by
the user.
name: The name of the plugin defined in the config file.
reqd: List of parameters required by the plugin.
opt: List of parameters considered optional for the plugin.
common: List of parameters which are common across all plugins.
Returns:
dict A dict containing the various parameters.
"""
LOGGER.debug(" Defining plugin params for " + name)
LOGGER.debug(" - reqd: " + str(reqd))
LOGGER.debug(" - opt: " + str(opt))
LOGGER.debug(" - common: " + str(common))
params = {}
# Defaults:
params["metadata"] = False
#TODO: Can we delete this below?
#params["limits"] = False
params['async'] = False
# Read params which have been defined
if reqd:
for reqdfield in reqd:
if config.has_option(name, reqdfield):
params[reqdfield] = config.get(name, reqdfield)
else:
msg = "Missing required field '" + reqdfield
msg += "' for plugin " + name + "."
print(msg)
logthis("error", msg)
msg += "This should be found in file: " + CFGPATHS['outputs']
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise MissingField
if opt:
for optfield in opt:
if config.has_option(name, optfield):
params[optfield] = config.get(name, optfield)
if common:
for commonfield in common:
if config.has_option("Common", commonfield):
params[commonfield] = config.get("Common", commonfield)
LOGGER.debug(" Final combined params to be used to create " + name + " instance are:")
LOGGER.debug(" " + str(params))
return params
def set_up_notifications():
"""Set up AirPi notification plugins.
Set up AirPi notification plugins by reading notifications.cfg to
determine which should be enabled. For each plugin, check that all
required fields are present; if so, create an instance of the plugin
class and append it to the list of Notification plugins. Return the
list.
Returns:
list A list containing the enabled 'notification' objects.
"""
print("==========================================================")
msg = format_msg("NOTIFICATIONS", 'loading')
print(msg)
check_cfg_file(CFGPATHS['notifications'])
NOTIFICATIONCONFIG = ConfigParser.SafeConfigParser()
NOTIFICATIONCONFIG.read(CFGPATHS['notifications'])
NOTIFICATIONNAMES = NOTIFICATIONCONFIG.sections()
NOTIFICATIONNAMES.remove("Common")
notificationPlugins = []
for i in NOTIFICATIONNAMES:
try:
try:
filename = NOTIFICATIONCONFIG.get(i, "filename")
except Exception:
msg = "No filename config option found for notification plugin "
msg += str(i)
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise
try:
enabled = NOTIFICATIONCONFIG.getboolean(i, "enabled")
except Exception:
enabled = True
#if enabled, load the plugin
if enabled:
try:
# 'a' means nothing below, but argument must be non-null
mod = __import__('notifications.' + filename,
fromlist=['a'])
except Exception:
msg = "Could not import notification module " + filename
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise
try:
notificationclass = get_subclasses(mod,
notification.Notification)
if notificationclass == None:
raise AttributeError
except Exception:
msg = "Could not find a subclass of"
msg += " notification.Notification in module " + filename
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise
try:
reqd = notificationclass.requiredParams
except Exception:
reqd = []
try:
opt = notificationclass.optionalParams
except Exception:
opt = []
try:
common = notificationclass.commonParams
except Exception:
common = []
#TODO: Get rid of this when it's all activated in Output
plugindata = define_plugin_params(NOTIFICATIONCONFIG, i,
reqd, opt, common)
if NOTIFICATIONCONFIG.get(i, "target") == "internet" and not check_conn():
msg = "Skipping notification plugin " + i
msg += " because no internet connectivity."
msg = format_msg(msg, 'error')
print(msg)
logthis("info", msg)
else:
instclass = notificationclass(plugindata)
instclass.async = plugindata['async']
# check for a sendnotification function
if callable(getattr(instclass, "sendnotification", None)):
notificationPlugins.append(instclass)
msg = "Loaded notification plugin " + str(i)
msg = format_msg(msg, 'success')
print(msg)
logthis("info", msg)
else:
msg = "No callable sendnotification() function"
msg += " for notification plugin " + str(i)
msg = format_msg(msg, 'error')
print(msg)
logthis("info", msg)
except Exception as excep:
msg = "Did not import notification plugin " + str(i) + ": "
msg += str(excep)
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
raise excep
# Don't run any_plugins_enabled() here, because it's OK to NOT have any
# notifications enabled (unlike sensors and outputs).
if not notificationPlugins:
msg = "No Notifications enabled."
msg = format_msg(msg, 'info')
print(msg)
return notificationPlugins
def set_settings():
"""Set up settings.
Set up settings by reading from settings.cfg.
Returns:
list A list containing the various settings.
"""
print("==========================================================")
print(format_msg("SETTINGS", 'loading'))
check_cfg_file(CFGPATHS['settings'])
mainconfig = ConfigParser.SafeConfigParser()
mainconfig.read(CFGPATHS['settings'])
if mainconfig.has_option("Debug", "debug"):
if mainconfig.getboolean("Debug", "debug"):
logging.basicConfig(level=logging.DEBUG)
settingslist = {}
settingslist['SAMPLEFREQ'] = mainconfig.getfloat("Sampling", "sampleFreq")
if mainconfig.has_option("Sampling", "averageFreq"):
if mainconfig.getint("Sampling", "averageFreq") != 0:
settingslist['AVERAGEFREQ'] = mainconfig.getint("Sampling",
"averageFreq")
averagefreq = settingslist['AVERAGEFREQ']
if averagefreq > 0:
averagecount = averagefreq / settingslist['SAMPLEFREQ']
if averagecount < 2:
msg = "averageFreq must be a least twice sampleFreq."
msg = format_msg(msg, 'error')
print(msg)
logthis("error", msg)
sys.exit(1)
else:
settingslist['AVERAGECOUNT'] = averagecount
settingslist['PRINTUNAVERAGED'] = mainconfig.getboolean("Sampling", "printUnaveraged")
settingslist['STOPAFTER'] = 0 # Default
if mainconfig.has_option("Sampling", "stopafter"):
if mainconfig.getint("Sampling", "stopafter") != 0:
settingslist['STOPAFTER'] = mainconfig.getint("Sampling",
"stopafter")
settingslist['DUMMYDURATION'] = 0 # Default
if mainconfig.has_option("Sampling", "dummyduration"):
settingslist['DUMMYDURATION'] = mainconfig.getint("Sampling",
"dummyduration")
# LEDs
settingslist['REDPIN'] = mainconfig.getint("LEDs", "redPin")
settingslist['GREENPIN'] = mainconfig.getint("LEDs", "greenPin")
settingslist['SUCCESSLED'] = mainconfig.get("LEDs", "successLED")
settingslist['FAILLED'] = mainconfig.get("LEDs", "failLED")
settingslist['LIMITLED'] = mainconfig.get("LEDs", "limitLED")
# Misc
settingslist['OPERATOR'] = mainconfig.get("Misc", "operator")
settingslist['HELP'] = mainconfig.getboolean("Misc", "help")
settingslist['PRINTERRORS'] = mainconfig.getboolean("Misc", "printErrors")
# Debug
settingslist['WAITTOSTART'] = mainconfig.getboolean("Debug", "waittostart")
msg = "Loaded settings."
msg = format_msg(msg, 'success')
print(msg)
logthis("info", msg)
return settingslist
def set_metadata():
"""Set metadata.
Set up metadata for this run. Outputting of the metadata is handled
by each of the output plugins individually, so that you can - for
example - output metadata via Print and CSVOutput in the same run.
Returns:
dict All metadata elements.
"""
meta = {
"STARTTIME":time.strftime("%H:%M on %A %d %B %Y"),
"OPERATOR":SETTINGS['OPERATOR'],
"PIID":get_serial(),
"PINAME":get_hostname(),
"SAMPLEFREQ": str(int(SETTINGS['SAMPLEFREQ'])) + " seconds"
}
if 'AVERAGEFREQ' in SETTINGS:
meta['AVERAGEFREQ'] = str(SETTINGS['AVERAGEFREQ']) + " seconds"
if SETTINGS['DUMMYDURATION'] != 0:
meta["DUMMYDURATION"] = str(int(SETTINGS['DUMMYDURATION'])) + " seconds"
if SETTINGS['STOPAFTER'] != 0:
meta["STOPAFTER"] = str(int(SETTINGS['STOPAFTER'])) + " samples"
return meta
def output_metadata(plugins, meta):
"""Output metadata via enabled plugins.
Output metadata for the run via each of the enabled 'output'
plugins. Note that some output plugins will not output metadata as
it is not appropriate.
Args:
plugins: List of enabled 'output' plugins.
meta: Metadata for the run.
"""
if meta is None:
meta = set_metadata()
for plugin in plugins:
#for name, data in inspect.getmembers(plugins):
# if hasattr(name, "output_metadata"):
plugin.output_metadata(meta)
def delay_start():
"""Delay sampling for a set time.
Delay sampling for a predetermined amount of time, notifying the
user in 10-second chunks. This is primarily used to wait until the
'start' of a full minute (i.e. zero seconds on the clock) before
starting a run.
Args:
delay: How long the run should be delayed for (seconds).
"""
# First calculate the required delay length
now = datetime.datetime.now()
seconds = float(now.second + (now.microsecond / 1000000))
delay = (60 - seconds)
# Now account for any dummy runs (including if DUMMYRUN = 0)
dummyduration = SETTINGS['DUMMYDURATION']
if delay > dummyduration:
delay = delay - dummyduration
else:
delay = delay + (60 - dummyduration)
# OK, commence the delay
print("==========================================================")
msg = "Sampling will start in " + str(int(delay)) + " seconds."
msg = format_msg(msg, 'info')
print(msg)
remainder = delay % 10
remaining = delay - remainder
time.sleep(remainder)
while remaining >= 1:
msg = "Sampling will start in " + str(int(remaining)) + " seconds."
msg = format_msg(msg, 'info')
print(msg)
time.sleep(10)
remaining -= 10
def dummy_runs(dummyduration):
"""Do dummy runs to kick off sensors.