示例#1
0
 def setUp(self):
     #self.adaptor= TempSensorAdaptorTask.getteravg()
     self.datamanager_avg = SensorDataManager().getteravg()
     self.datamanager_current = SensorDataManager().gettercurrent()
     self.datamanager_count = SensorDataManager().gettercount()
     self.adaptorTask_sensor = TempSensorAdaptorTask()
     self.sensorAdaptor = TempSensorAdaptor()
示例#2
0
    def setUp(self):

        #instantiate the classes required
        self.sensorDataManager = SensorDataManager()
        self.tempActuatorAdaptor = TempActuatorAdaptor()
        self.tempSensorAdaptor = TempSensorAdaptor()
        self.tempSensorAdaptorTask = TempSensorAdaptorTask()

        pass
def main():

    temp_sensor_object = TempSensorAdaptor()  # Thread 1 - Temperature Sensing
    alarm_trigger = SensorDataManager(
    )  # Thread 2 - Notification generator & actuation function class
    alarm_trigger.start()

    while True:
        pass
    def setUp(self):
        self.sd = SensorData()
        self.sd.addValue(11)
        self.sdm = SensorDataManager()
        self.actuator = ActuatorData()
        self.actuator.setCommand("Raise Temp")
        self.sdm.threshold = 20
        self.tsa = TempSensorAdaptor()
        self.taa = TempActuatorAdaptor()
        self.tat = TempSensorAdaptorTask()
        self.shla = SenseHatLedActivator()

        pass
示例#5
0
 def setUp(self):
     self.config = ConfigUtil()
     self.config.loadConfig('../../../config/ConnectedDevicesConfig.props')
     self.tempsensor = TempSensorAdaptorTask()
     self.sensordata = SensorData()
     self.actuatordata = ActuatorData()
     self.sensordata.addValue(10)
     self.sensordata.addValue(15)
     self.sensordata.addValue(20)
     self.sensordata.addValue(25)
     self.sensordata.setName('Temperature')
     self.actuatordata.setCommand('Increasing')
     self.actuatordata.setName('SenseHat')
     self.sdmanager = SensorDataManager()
示例#6
0
class Module03Test(unittest.TestCase):
	confU=ConfigUtil();
	sensorD=SensorData()
	hasConf=confU.hasConfig()
	curVal=sensorD.getCurrentValue()
	avgVal=sensorD.getAverageValue()
	actD=ActuatorData()
	senDM=SensorDataManager()
	
	"""
	it checks for the datatype of hasConf to be boolean, If true test case is passed.
	"""

	def testConfigUtil(self):
		self.assertTrue(isinstance(self.hasConf,bool),"Boolean Value")
		
	"""
	it checks for the datatype of curVal to be float, If true test case is passed. 
	Second checks for the avgVal to be within the specified range.If true test case is passed. 
	"""	
	def testSensorData(self):
		self.assertTrue(isinstance(self.curVal,float),"Float Value")
		self.assertTrue(self.avgVal>=0.0 and self.avgVal<=30.0,"Average Temperature within the range")
	'''
	It checks for the datatype of the getCommand function to be String.
	'''	
	def testActuatorData(self):
		self.assertTrue(isinstance(self.actD.getCommand(),str), "String")
		
	'''
	It checks for the returntype of the function handleSensorData of class SensorDataManager to be of type actuator data. 
	'''	
	def testSensorDataManager(self):
		self.assertTrue(isinstance(self.senDM.handleSensorData(self.sensorD),ActuatorData), "Type Actuator Data")		
class TempSensorAdaptorTask(threading.Thread):
    rateInSec = 10
    curTemp = 0
    sensorData = SensorData()
    sense = SenseHat()
    manager = SensorDataManager()
    dataUtil = DataUtil()
    '''
    Read the Temperature from the SenseHAT
    '''
    def __init__(self, rateInSec=10):
        threading.Thread.__init__(self)
        self.rateInSec = rateInSec
        self.time = self.sensorData.timeStamp

    def getTemperature(self):
        self.curTemp = self.sense.get_temperature()
        return self.curTemp

    def run(self):
        while True:
            self.sensorData.setName('Temp')
            self.sensorData.addValue(self.getTemperature())
            #print(self.sensorData.curValue)
            self.manager.handleSensorData(self.sensorData)

            self.dataUtil.toJsonFromSensorData(self.sensorData)

            sleep(self.rateInSec)
示例#8
0
class HumiditySensorAdaptorTask(Thread):
    '''
    Variables are defined and objects of required classes are created with the class scope.
    '''
    sensorData = SensorData()  #constructor of sensorData is created.
    multiAct = MultiActuatorAdaptor(
    )  #constructor of TempActuatorAdaptor is created.
    sensorDataM = SensorDataManager(
    )  #constructor of SensorDataManager is created.
    avgValue = 0.0
    count = 0.0
    total = 0.0
    currentValue = 0.0
    maxValue = 0.0
    minValue = 0.0
    timestamp = None
    sh = SenseHat()

    def __init__(self, name):  #constructor is initialized
        Thread.__init__(self)
        self.name = name

    '''
    this run function overrides the run function of Thread and calls the sense hat function to generate the Humidity values,addValue fnctn of sensorData is called
    humidity of class sensorDataManager is called and sensorData object is passed as a parameter.
    This function will return the actuator data.
    '''

    def run(self):  #run method of thread is overriden
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s:%(levelname)s:%(message)s')
        sh = SenseHat()
        res = sh.get_humidity()
        self.sensorData.addValue(res)
        self.act_data = self.sensorDataM.humidity(self.sensorData)
        self.getSensorData()
        if (self.act_data != None):
            self.multiAct.updateActuator(
                self.act_data)  #calling of updateActuator

        logging.basicConfig(level=logging.INFO)
        data = "Humidity Sensor:\nTime:    " + str(
            self.timestamp) + "\nCurrent:    " + str(
                self.currentValue) + "\nAverage:    " + str(
                    self.avgValue) + "\nSamples:    " + str(
                        self.count) + "\nMin:    " + str(
                            self.minValue) + "\nMax:    " + str(self.maxValue)
        logging.info(data)
        print("\n")

    '''
    This function fetches the values from sensorData and store it to the local variables of this class.
    '''

    def getSensorData(self):
        self.avgValue = self.sensorData.getAverageValue()
        self.count = self.sensorData.getCount()
        self.total = self.sensorData.getTotal()
        self.currentValue = self.sensorData.getCurrentValue()
        self.maxValue = self.sensorData.getMaxValue()
        self.minValue = self.sensorData.getMinValue()
        self.timestamp = self.sensorData.getTimestamp()
示例#9
0
class Module03Test(unittest.TestCase):
    """
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
    #initialize the rgb values for the led colors

    #no color
    e = [0, 0, 0]

    #red
    r = [255, 0, 0]

    #blue
    b = [0, 0, 255]

    #initialize the red arrow when increasing the temperature on sense hat led matrix
    arrowRedInc = [
        e, e, e, r, r, e, e, e, e, e, r, r, r, r, e, e, e, r, e, r, r, e, r, e,
        r, e, e, r, r, e, e, r, e, e, e, r, r, e, e, e, e, e, e, r, r, e, e, e,
        e, e, e, r, r, e, e, e, e, e, e, r, r, e, e, e
    ]

    #initialize the blue arrow when decreasing the temperature on sense hat led matrix
    arrowBlueDec = [
        e, e, e, b, b, e, e, e, e, e, e, b, b, e, e, e, e, e, e, b, b, e, e, e,
        e, e, e, b, b, e, e, e, b, e, e, b, b, e, e, b, e, b, e, b, b, e, b, e,
        e, e, b, b, b, b, e, e, e, e, e, b, b, e, e, e
    ]

    def setUp(self):

        #instantiate the classes required
        self.sensorDataManager = SensorDataManager()
        self.tempActuatorAdaptor = TempActuatorAdaptor()
        self.tempSensorAdaptor = TempSensorAdaptor()
        self.tempSensorAdaptorTask = TempSensorAdaptorTask()

        pass

    """
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""

    def tearDown(self):

        #set the reference to the variables as none to release the resources they're holding
        self.sensorDataManager = None
        self.tempActuatorAdaptor = None
        self.tempSensorAdaptor = None
        self.tempSensorAdaptorTask = None
        pass

    """
	This method tests the handleSensorData() of SensorDataManager module. It tests whether the sensor data passed to the method triggers the correct
	actuator command.
	"""

    def testGetHandleSensorData(self):

        #initialize sensor data
        sensorData = SensorData()

        #when current value is greater than nominal temp
        sensorData.addValue(90)

        #get the actuatorData returned from the sensor data manager
        actuatorData = self.sensorDataManager.handleSensorData(sensorData)

        #check if actuatorData is of type ActuatorData
        self.assertIsInstance(actuatorData, ActuatorData)

        #test the value, which should be "arrowBlueDec"
        self.assertEqual(self.arrowBlueDec, actuatorData.getValue())

        #actuatorData command should be decrease temp
        self.assertEqual(actuatorData.getCommand(), "DECREASE TEMP")

        #when current value is less than nominal temp
        sensorData.addValue(10)

        #get the actuatorData returned from the sensor data manager
        actuatorData = self.sensorDataManager.handleSensorData(sensorData)

        #check if actuatorData is of type ActuatorData
        self.assertIsInstance(actuatorData, ActuatorData)

        #actuatorData command should be increase temp
        self.assertEqual(actuatorData.getCommand(), "INCREASE TEMP")

        #when current value is equal to the nominal temp
        sensorData.addValue(20)

        #get the actuatorData returned from the sensor data manager
        actuatorData = self.sensorDataManager.handleSensorData(sensorData)

        #actuatorData is none sensor data equal to nominal temp
        self.assertEqual(actuatorData, None)

        pass

    """
	This tests the sendNotification() method of the SensorDataManager, it simply whether
	 the notification is being sent or not. This has been shown in documentation using screenshot of the
	 email
	"""

    def testSendNotification(self):

        #if the config file is loaded: while testing on system
        if self.sensorDataManager.smtpClientConnector.config.configFileLoaded == True:

            #returns true, notification is being sent
            self.assertEqual(
                True,
                self.sensorDataManager.sendNotification(
                    "Hello", "This is a test"))

        pass

    """
	This tests the updateActuator() method of the TempActuatorAdaptor, it checks whether the actuator is updated 
	(by returning an actuatorData reference) when the trigger is valid (INCREASE TEMP) and when the trigger is invalid 
	(NOT A VALID TRIGGER)
	"""

    def testUpdateActuator(self):

        #create an invalid actuator trigger
        actuatorData = ActuatorData()
        actuatorData.setCommand("NOT A VALID TRIGGER")

        #add a valid value
        actuatorData.setValue(self.arrowBlueDec)

        #updateActuator should return a false
        self.assertEqual(False,
                         self.tempActuatorAdaptor.updateActuator(actuatorData))

        #create a valid actuator trigger
        actuatorData = ActuatorData()
        actuatorData.setCommand("INCREASE TEMP")
        actuatorData.setValue(self.arrowRedInc)

        #updateActuator should return a True
        self.assertEqual(True,
                         self.tempActuatorAdaptor.updateActuator(actuatorData))

        #sending a none should throw an exception, where when caught, returns a false
        self.assertEqual(False, self.tempActuatorAdaptor.updateActuator(None))

        pass

    """
	This tests the getTemperature() method of the TempSensorAdaptorTask, it checks whether the fetcher runs when enabled,
	disabled, number of readings to get has been set to 0.
	"""

    def testGetTemperature(self):

        #enable the fetcher
        self.tempSensorAdaptorTask.enableFetcher = True

        #change numReadings to a small finite value to check
        self.tempSensorAdaptorTask.numReadings = 1

        #change sleep time (rateInSec) to a small amount
        self.tempSensorAdaptorTask.rateInSec = 1

        #run when numReadings > 0 and adaptor is enabled
        self.assertEqual(True, self.tempSensorAdaptorTask.getTemperature())

        #change numReadings to 0
        self.tempSensorAdaptorTask.numReadings = 0

        #run when numReadings = 0 and emulator is enabled, should return false because generator didn't run
        self.assertEqual(False, self.tempSensorAdaptorTask.getTemperature())

        #disable the emulator
        self.tempSensorAdaptorTask.enableFetcher = False

        #change readings to > 0
        self.tempSensorAdaptorTask.numReadings = 1

        #run when numReadings > 0 and emulator is disabled, should return false because generator didn't run
        self.assertEqual(False, self.tempSensorAdaptorTask.getTemperature())

    """
	This tests the run() method of the TempSensorAdaptor, it checks whether it runs successfully.
	"""

    def testTempSensorAdaptor(self):

        #get the reference to the tempSensorEmulatorTask
        tempSensTask = self.tempSensorAdaptor.tempSensorAdaptorTask

        #change numReadings to a small finite value to check
        tempSensTask.numReadings = 1

        #change sleep time (rateInSec) to a small amount
        tempSensTask.rateInSec = 1

        #enable the tempEmulatorTask's emulator
        tempSensTask.enableFetcher = True

        #run the run function of tempEmulatorAdaptor and get the value of success of the adaptor
        self.assertEqual(True, self.tempSensorAdaptor.run())
示例#10
0
class Module03Test(unittest.TestCase):
    """
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
    def setUp(self):
        self.config = ConfigUtil()
        self.config.loadConfig('../../../config/ConnectedDevicesConfig.props')
        self.tempsensor = TempSensorAdaptorTask()
        self.sensordata = SensorData()
        self.actuatordata = ActuatorData()
        self.sensordata.addValue(10)
        self.sensordata.addValue(15)
        self.sensordata.addValue(20)
        self.sensordata.addValue(25)
        self.sensordata.setName('Temperature')
        self.actuatordata.setCommand('Increasing')
        self.actuatordata.setName('SenseHat')
        self.sdmanager = SensorDataManager()

    """
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""

    def tearDown(self):
        pass

    """
	Place your comments describing the test here.
	"""

    def testloadConfig(self):
        self.assertTrue(
            self.config.loadConfig(
                '../../../config/ConnectedDevicesConfig.props'))

    def testhasConfigData(self):
        self.assertTrue(self.config.hasConfigData())

    def testgetValue(self):
        self.assertEqual(self.config.getValue("smtp.cloud", "port"), '465')

    def testgetSensorData(self):
        assert self.tempsensor.getTemperature(
        ) > 0 and self.tempsensor.getTemperature() < 30

    def testgetAverageValue(self):
        assert self.sensordata.getAverageValue(
        ) > 0 and self.sensordata.getAverageValue() < 30

    def testgetCount(self):
        self.assertEqual(self.sensordata.getCount(), 4)

    def testgetCurrentValue(self):
        assert self.sensordata.getCurrentValue(
        ) > 0 and self.sensordata.getCurrentValue() < 30

    def testMinValue(self):
        assert self.sensordata.getMinValue(
        ) >= 0 and self.sensordata.getMinValue() < 30

    def testMaxValue(self):
        assert self.sensordata.getMaxValue(
        ) > 0 and self.sensordata.getMaxValue() < 30

    def testName(self):
        self.assertEqual(self.sensordata.getName(), 'Temperature')

    def testgetCommand(self):
        self.assertEqual(self.actuatordata.getCommand(), 'Increasing')

    def testName2(self):
        self.assertEqual(self.actuatordata.getName(), 'SenseHat')

    def testhandleSenseData(self):
        assert self.sdmanager.handleSensorData(self.sensordata) is not None
示例#11
0
 def setUp(self):
     adaptor_object = TempSensorAdaptor()  # Thread object 1
     self.temp_sensor_object = adaptor_object.getSensorobj()
     manager_object = SensorDataManager()  # Thread object 2
     manager_object.start()  # Starting thread
     self.message_object = smtpconnect()  # SMTP class object
class TempSensorAdaptorTask(Thread):
    '''
    Variables are defined and objects of required classes are created with the class scope.
    '''
    
    sensorData=SensorData()         #constructor of sensorData is created.
    tempAct=TempActuatorAdaptor()   #constructor of TempActuatorAdaptor is created.
    sensorDataM=SensorDataManager() #constructor of SensorDataManager is created.
    smtpCCObject=SmtpClientConnector.SmtpClientConnector()  ##constructor of SmtpClientConnector is created.
    confP=ConfigUtil()  #constructor of ConfigUtil is created.
    avgValue=0.0
    count=0.0
    total=0.0
    currentValue=0.0
    maxValue=0.0
    minValue=0.0
    timestamp=None
    sh=SenseHat()       #constructor of SenseHat is created.
    '''
    nominal temperature is fetched from configuration file using object of ConfigParser.
    '''
    nominal=confP.getValue("device", "nominalTemp")
    print("im nominal",nominal)
    '''
    constructor of class TempSensorAdaptorTask
    '''
    def __init__(self,name):
       # self.generateTemp()
        Thread.__init__(self);
        self.name=name
    '''
    this run function overrides the run function of Thread and calls the sense hat function to generate the temperature values,addValue fnctn of sensorData is called
    handleSensorData of class sensorDataManager is called and sensorData object is passed as a parameter.
    This function will return the actuator data. notification fucn will be called to check the condition of sending the email
    '''
    
    def run(self):
        #for i in range(0,10):
       # while True:
        
        mqtt_client = mqttClient.Client()
        while True:
            self.val=self.sh.get_temperature()      #calling get_temperature function
            
            self.sensorData.addValue(self.val)  #calling addValue function of sensorData
            self.act_data=self.sensorDataM.handleSensorData(self.sensorData)
            self.getSensorData()
            
           #commented out for mod8# self.sendNotification(self.act_data.getCommand(), self.act_data.getValue(),self.nominal)
            
            ubidots(mqtt_client,self.avgValue,self.currentValue)
            time.sleep(2)
          #mod8#  if(self.act_data!=None):
            #mod8#    self.tempAct.updateActuator(self.act_data)      #calling of updateActuator
            #mod8# time.sleep(2)    
     #   return None    
    '''
    values of sensor data is fetched to store in local variables.
    '''        
    def getSensorData(self):
        self.avgValue= self.sensorData.getAverageValue();
        self.count=self.sensorData.getCount();
        self.total=self.sensorData.getTotal();
        self.currentValue=self.sensorData.getCurrentValue();
        self.maxValue=self.sensorData.getMaxValue();
        self.minValue=self.sensorData.getMinValue();
        self.timestamp=self.sensorData.getTimestamp();
                
    '''
    notification regarding email alert and logging information is handled by sendNotification function, it takes 3 arguments
    namely command which is set to actuator data, current Temperature value and the nominal value
    '''            
    def sendNotification(self,command,current,nominal): 
        logging.basicConfig(level=logging.INFO,format='%(asctime)s:%(levelname)s:%(message)s')
        nominal=float(nominal)     
        if(command=="TEMP INC"):
            logging.info('\n Current temperature exceeds Nominal Temperature by ' + str(round(abs(current-nominal),2)) + '. Triggering alert...')
        elif(command=="TEMP DEC"):
            logging.info('\n Current temperature deceeds Nominal Temperature by ' + str(round(abs(current-nominal),2)) + '. Triggering alert...')    
        else:
            logging.info('\n Current temperature is neutral to Nominal Temperature')    
        
      #  self.smtpCCObject.connector(command)
        logging.basicConfig(level=logging.INFO)
        data="Temperature:\nTime:    "+str(self.timestamp)+"\nCurrent:    "+str(self.currentValue)+"\nAverage:    "+str(self.avgValue)+"\nSamples:    "+str(self.count)+"\nMin:    "+str(self.minValue)+"\nMax:    "+str(self.maxValue)    
        logging.info(data)
        print("\n")
'''
Created on Jan 30, 2020

@author: Siddhartha
'''
from labs.module03.SensorDataManager import SensorDataManager
from labs.common.ConfigUtil import ConfigUtil
import logging

#Entry level script

logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
                    level=logging.DEBUG)
tempAdapter = SensorDataManager()
#setting the thread and executing
tempAdapter.run()
class Module03Test(unittest.TestCase):
    """
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
    def setUp(self):
        self.sd = SensorData()
        self.sd.addValue(11)
        self.sdm = SensorDataManager()
        self.actuator = ActuatorData()
        self.actuator.setCommand("Raise Temp")
        self.sdm.threshold = 20
        self.tsa = TempSensorAdaptor()
        self.taa = TempActuatorAdaptor()
        self.tat = TempSensorAdaptorTask()
        self.shla = SenseHatLedActivator()

        pass

    """
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""

    def tearDown(self):
        pass

    """
	Place your comments describing the test here.
	"""
    '@Test'

    def testSendNotification(self):
        self.assertTrue(self.sdm.sendNotification(),
                        "Notification Unsucessful")
        pass

    '@Test'

    def testhadleSensorData(self):
        self.assertTrue(self.sdm.hadleSensorData(self.sd),
                        "Sensor handle data method not working")

    '@Test'

    def testgetSensorData(self):
        self.assertTrue(self.tsa.getSensorData(),
                        "Issue in temperature adaptor")

    '@Test'

    def testreadSensorValueMin(self):
        self.assertGreaterEqual(self.tat.readSensorValue(), 0.0,
                                'sensor value coming less than 0')

    '@Test'

    def testreadSensorValueMax(self):
        self.assertGreaterEqual(100, self.tat.readSensorValue(),
                                'sensor value coming more than 100')

    '@Test'

    def testupdateActuator(self):
        self.assertTrue(self.taa.updateActuator(self.actuator),
                        "Actuator update failed")

    '@Test'

    def testupdateLed(self):
        self.assertTrue(self.shla.updateLed("Test Message"),
                        "Led update failed")
示例#15
0
'''
Created on Feb 9, 2020

@author: amanshah
# '''
# from labs.module04.TempSensorAdaptor import TempSensorAdaptor
from labs.module03.SensorDataManager import SensorDataManager
if __name__ == '__main__':
    #     x=TempSensorAdaptor()
    #     x.adaptor()
    while True:

        x = SensorDataManager()
        x.runapplication()
class HI2CSensorAdaptorTask(Thread):
    '''
    Variables are defined and objects of required classes are created with the class scope.
    '''
    sensorData = SensorData()  #constructor of sensorData is created.
    multiAct = MultiActuatorAdaptor(
    )  #constructor of TempActuatorAdaptor is created.
    sensorDataM = SensorDataManager(
    )  #constructor of SensorDataManager is created.
    avgValue = 0.0
    count = 0.0
    total = 0.0
    currentValue = 0.0
    maxValue = 0.0
    minValue = 0.0
    timestamp = None
    sh = SenseHat()

    def __init__(self, name):  #constructor is called
        Thread.__init__(self)
        self.name = name

    '''
    this run function overrides the run function of Thread and calculates the Humidity values from the I2C bus,addValue fnctn of sensorData is called
    humidityI2C of class sensorDataManager is called and sensorData object is passed as a parameter.
    This function will return the actuator data.
     
    '''

    def run(self):
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s:%(levelname)s:%(message)s')

        while True:

            lsb1 = i2cBus.read_byte_data(0x5f, 0x36)
            msb1 = i2cBus.read_byte_data(0x5f, 0x37)
            H0 = numpy.int16((msb1 << 8) | lsb1)

            lsb2 = i2cBus.read_byte_data(0x5f, 0x3A)
            msb2 = i2cBus.read_byte_data(0x5f, 0x3B)
            H1 = numpy.int16((msb2 << 8) | lsb2)

            lsb3 = i2cBus.read_byte_data(0x5f, 0x28)
            msb3 = i2cBus.read_byte_data(0x5f, 0x29)
            H = numpy.int16((msb3 << 8) | lsb3)

            h1 = numpy.uint16(i2cBus.read_byte_data(0x5f, 0x31) >> 1)
            h0 = numpy.uint16(i2cBus.read_byte_data(0x5f, 0x30) >> 1)

            per = ((h1 - h0) * (H - H0) / (H1 - H0)) + h0
            self.sensorData.addValue(per)
            self.act_data = self.sensorDataM.humidityI2C(self.sensorData)
            self.getSensorData()
            if (self.act_data != None):
                self.multiAct.updateActuator(self.act_data)
        # logger.info("I2C: " +str(per)+"%" )
            logging.basicConfig(level=logging.INFO)
            data = "HI2C Sensor:\nTime:    " + str(
                self.timestamp) + "\nCurrent:    " + str(
                    self.currentValue) + "\nAverage:    " + str(
                        self.avgValue) + "\nSamples:    " + str(
                            self.count) + "\nMin:    " + str(
                                self.minValue) + "\nMax:    " + str(
                                    self.maxValue)
            logging.info(data)
            print("\n")
        return None

    '''
     This function fetches the values from sensorData and store it to the local variables of this class.
    '''

    def getSensorData(self):
        self.avgValue = self.sensorData.getAverageValue()
        self.count = self.sensorData.getCount()
        self.total = self.sensorData.getTotal()
        self.currentValue = self.sensorData.getCurrentValue()
        self.maxValue = self.sensorData.getMaxValue()
        self.minValue = self.sensorData.getMinValue()
        self.timestamp = self.sensorData.getTimestamp()
示例#17
0
class TempSensorAdaptorTask(object):
    '''
    classdocs
    '''

    #instantiate the SenseHat class
    sense = SenseHat()

    #disable the emulator initially
    enableFetcher = False

    #instantiate the SensorData class
    sensorData = SensorData()

    #instantiate the SensorDataManager
    sensorDataManager = SensorDataManager()

    #this method is used to set the readings and the frequency of readings if provided, else defaults to 10 and 5 respectively
    def __init__(self, numReadings=10, rateInSec=5):
        '''
        Constructor
        '''

        #set the number of readings you want to get
        self.numReadings = numReadings

        #set the rate at which you want to get the readings
        self.rateInSec = rateInSec

    #get the temperature from SenseHAT
    def getTemperature(self):

        #data is not f doesn't run if 0 readings set:
        if self.numReadings == 0:
            return False

        #run the loop as many times as indicated in the numReadings variable
        while self.numReadings > 0:

            #if the fetcher is enabled
            if self.enableFetcher:

                #clear the sense hat
                self.sense.clear()

                #get the temperature from the sense hat
                temp = self.sense.get_temperature()

                #add it to the sensorData
                self.sensorData.addValue(temp)

                #store the updated values from sensorData object
                time = '            Time: ' + self.sensorData.timeStamp
                current = '            Current: ' + str(
                    self.sensorData.getCurrentValue())
                average = '            Average: ' + str(
                    self.sensorData.getAverageValue())
                samples = '            Samples: ' + str(
                    self.sensorData.getCount())
                min_temp = '            Min: ' + str(
                    self.sensorData.getMinValue())
                max_temp = '            Max: ' + str(
                    self.sensorData.getMaxValue())
                data = 'Temperature' + '\n' + time + '\n' + current + '\n' + average + '\n' + samples + '\n' + min_temp + '\n' + max_temp

                #log the current sensorData values
                logging.info(data)

                self.sensorData.loggingData = data

                #send it to the SensorDataManager who will check if it needs actuation
                self.sensorDataManager.handleSensorData(self.sensorData)

                #decrement as the number of readings by 1 to keep count of how many readings left
                self.numReadings -= 1

                #sleep for time indicated in rateInSec
                sleep(self.rateInSec)

            #if fetcher is not enabled
            else:

                #fetch didn't run
                return False

        #the fetcher is done running
        return True