airpi.py 2.26 KB
Newer Older
1 2 3 4 5
#This file takes in inputs from a variety of sensor files, and outputs information to a variety of services

import ConfigParser
import time
import inspect
Tom Hartley's avatar
Tom Hartley committed
6
import os
7
from sys import exit
Tom Hartley's avatar
Tom Hartley committed
8
from sensors import sensor
9 10 11

def get_subclasses(mod,cls):
	for name, obj in inspect.getmembers(mod):
Tom Hartley's avatar
Tom Hartley committed
12
		if hasattr(obj, "__bases__") and cls in obj.__bases__:
13 14 15 16 17 18 19 20 21 22 23
			return obj


if not os.path.isfile('sensors.cfg'):
	print "Unable to access config file: sensors.cfg"
	exit(1)

sensorConfig = ConfigParser.SafeConfigParser()
sensorConfig.read('sensors.cfg')

sensorNames = sensorConfig.sections()
Tom Hartley's avatar
Tom Hartley committed
24 25 26


sensorPlugins = []
27
for i in sensorNames:
Tom Hartley's avatar
Tom Hartley committed
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
	try:	
		try:
			filename = sensorConfig.get(i,"filename")
		except:
			print("Error: no filename config option found for " + i)
			raise
		try:
			enabled = sensorConfig.getboolean(i,"enabled")
		except:
			enabled = True

		#if enabled, load the plugin
		if enabled:
			try:
				mod = __import__('sensors.'+filename,fromlist=['a']) #Why does this work?
			except:
				print("Error: could not import module " + filename)
				raise

			try:	
				sensorClass = get_subclasses(mod,sensor.Sensor)
				if sensorClass == None:
					raise AttributeError
			except:
				print("Error: could not find a subclass of sensor.Sensor in module " + filename)
				raise

			try:	
				reqd = sensorClass.requiredData
			except:
				reqd =  []
			try:
				opt = sensorClass.optionalData
			except:
				opt = []

			pluginData = {}

			class MissingField(Exception): pass
						
			for requiredField in reqd:
				if sensorConfig.has_option(i,requiredField):
					pluginData[requiredField]=sensorConfig.get(i,requiredField)
				else:
					print "Error: Missing required field '" + requiredField + "' for sensor plugin " + i
					raise MissingField
			for optionalField in opt:
				if sensorConfig.has_option(i,optionalField):
					pluginData[optionalField]=sensorConfig.get(i,optionalField)
			instClass = sensorClass(pluginData)
			sensorPlugins.append(instClass)
			print ("Success: Loaded sensor plugin " + i)
	except Exception as e: #add specific exception for missing module
		print("Error: Did not import sensor plugin " + i )
		raise e


if not os.path.isfile("outputs.cfg"):
	print "Unable to access config file: outputs.cfg"

outputConfig = ConfigParser.SafeConfigParser()
outputConfig.read("outputs.cfg")