def sendNotification(self):

        try:
            logging.info(self.actuator.getName() + "Temperature: \nTime: " +
                         str(self.actuator.timestamp) + " Value :" +
                         str(self.actuator.getValue()))
            mail = SmtpClientConnector()
            #Creating mail body text
            data = "Reading from:" + self.actuator.getName(
            ) + "\nTime: " + str(
                self.actuator.timestamp) + "\ncurrent : " + str(
                    self.actuator.getValue()) + "\nAverage :" + str(
                        self.actuator.getAverageValue()) + "\nSamples :" + str(
                            self.actuator.readings_number) + "\nMin: " + str(
                                self.actuator.min_value) + "\nMax :" + str(
                                    self.actuator.max_value)
            mail.publishMessage(
                "Humidity Alert Python -" + self.actuator.getName(), data)
            logging.info('\nMail sent')
            return True
        except Exception as e:
            logging.info(e)
            print(e)
            #If the mailing fails, the method returns false
            return False
 def __init__(self):
     '''
     Constructor
     '''
     self.config = ConfigUtil()
     self.connector = SmtpClientConnector()
     self.tempActuator = TempActuatorAdaptor()
class SensorDataManager(object):
    '''
    classdocs
    '''   
    actuatorData = ActuatorData()
    

    def __init__(self):
        '''
        Constructor
        '''
        self.config = ConfigUtil()
        self.connector = SmtpClientConnector()
        self.tempActuator = TempActuatorAdaptor()
        
    '''
    If current temperature exceeds or falls below the 'nominalTemp', the new SensorData instance will trigger an actuation
    It will return the new ActualatorData instance with the appropriate data value and command embedded;
    Otherwise, it returns None
    Also,if an actuation is triggered, the SmtpClientConnector instance will be created to send the e-mail 
    message to the appropriate destination    
    '''
        
    def handleSensorData(self,sensorData):
        self.nominalTemp = float(self.config.getValue(ConfigConst.DEVICE, ConfigConst.NOMINAL_TEMP))
        self.time       = sensorData.timeStamp                                     
        self.average    = sensorData.avgValue
        self.samples    = sensorData.getCount()
        self.min        = sensorData.minValue
        self.max        = sensorData.maxValue 
        self.message    = 'Temperature\n' + '\tTime: ' +str(self.time) + '\n\tCurrent: ' + str(sensorData.curValue) + '\n\tAverage: ' +str(self.average) + '\n\tSamples: ' + str(self.samples) + '\n\tMin: ' + str(self.min) + '\n\tMax: ' + str(self.max)
        
        if(sensorData.curValue>self.nominalTemp):
            
            logging.info('\nCurrent temperature exceeds nonminalTemp by > ' +str(self.nominalTemp) + '. Triggering alert...')
            #print('\nCurrent temperature exceeds nonminalTemp by > ' +str(self.nominalTemp) + '. Triggering alert...')      
            
            self.connector.publishMessage('Excessive Temperature', self.message)
            self.actuatorData.setCommand('Increasing')
            self.actuatorData.getValue(sensorData.curValue)
            self.tempActuator.updateActuator(self.actuatorData)
            print(self.message)
            return(self.actuatorData)
            
            
        elif(sensorData.curValue<self.nominalTemp):
            
            logging.info('\nCurrent temperature falls below nonminalTemp by < ' +str(self.nominalTemp) + '. Triggering alert...')                                     
             
            self.connector.publishMessage('Decreasing Temperature', self.message)
            self.actuatorData.setCommand('Decreasing')
            self.actuatorData.getValue(sensorData.curValue)
            self.tempActuator.updateActuator(self.actuatorData)
            print(self.message)
            return(self.actuatorData)
        
        else:
            return(None)
            
Esempio n. 4
0
 def __init__(self, rateInSec=5, alertDiff=5):
     '''
     Constructor
     '''
     threading.Thread.__init__(self)
     self.connector = SmtpClientConnector()
     self.rateInSec = rateInSec
     self.alertDiff = alertDiff
     self.time = self.sensorData.timeStamp
 def sendNotification(self):
     if (abs(SensorData.getValue() - SensorData.getAvgValue()) >=
             self.alertDiff):
         #             print(SensorData.curValue)
         #             print(SensorData.sampleCount)
         logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
                             level=logging.DEBUG)
         logging.info('\n Current temp exceeds average by > ' +
                      str(self.alertDiff) + '.Triggering alert...')
         data = SensorData.__str__()
         connector = SmtpClientConnector()
         connector.publishMessage('Excessive Temp', data)
 def sendNotification(self):
     if(abs(self.currentValue-self.avgValue)>self.threshold):
         smtpCCObject=SmtpClientConnector()
         smtpCCObject.connector()
         logging.basicConfig(level=logging.INFO,format='%(asctime)s:%(levelname)s:%(message)s')
         logging.info('\n Current temperature exceeds average by ' + str(round(abs(self.currentValue-self.avgValue),2)) + '. Triggering alert...')
         
     
     
     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")
Esempio n. 7
0
 def sendNotification(self):
     try:
         self.getSensorData()
         if(abs(self.currentTemp - self.avgTemp) > self.threshold):
             logging.info('Current temp exceeds average beyond ' + str(self.threshold) + '. Triggering alert...')
             mail = SmtpClientConnector()
             #Creating mail body text
             data = "Temperature Exceeded Warning!\n \nTemperature: \nTime: "+str(self.sensor.timestamp)+"\ncurrent : "+str(self.currentTemp) +"\nAverage :"+str(self.avgTemp)+"\nSamples :"+str(self.readings)+"\nMin: "+str(self.minTemp)+"\nMax :"+str(self.maxTemp)
             mail.publishMessage("Temperature Alert Python", data)
             logging.info('\nMail sent')
         return True
     except:
         #If the mailing fails, the method returns false
         return False
    def sendNotification(self):

        try:
            if (self.actuator.getCommand() == "Raise Temp"):
                #logging.info('Current Temperature lower than threshold: ' + str(self.threshold) + ' Lowering Temp')
                logging.info(
                    "Current Temperature lower than threshold: \n \nTemperature: \nTime: "
                    + str(self.actuator.timestamp) + "\ncurrent : " +
                    str(self.actuator.getValue()) + "\nAverage :" +
                    str(self.actuator.getAverageValue()) + "\nSamples :" +
                    str(self.actuator.readings_number) + "\nMin: " +
                    str(self.actuator.min_value) + "\nMax :" +
                    str(self.actuator.max_value))
                mail = SmtpClientConnector()
                #Creating mail body text
                data = "Current Temperature lower than threshold: \n \nTemperature: \nTime: " + str(
                    self.actuator.timestamp) + "\ncurrent : " + str(
                        self.actuator.getValue()) + "\nAverage :" + str(
                            self.actuator.getAverageValue()
                        ) + "\nSamples :" + str(
                            self.actuator.readings_number) + "\nMin: " + str(
                                self.actuator.min_value) + "\nMax :" + str(
                                    self.actuator.max_value)
                mail.publishMessage("Temperature Alert Python", data)
                logging.info('\nMail sent')

            elif (self.actuator.getCommand() == "Decrease Temp"):
                logging.info(
                    "Current Temperature higher than threshold: \n \nTemperature: \nTime: "
                    + str(self.actuator.timestamp) + "\ncurrent : " +
                    str(self.actuator.getValue()) + "\nAverage :" +
                    str(self.actuator.getAverageValue()) + "\nSamples :" +
                    str(self.actuator.readings_number) + "\nMin: " +
                    str(self.actuator.min_value) + "\nMax :" +
                    str(self.actuator.max_value))
                mail = SmtpClientConnector()
                #Creating mail body text
                data = "Current Temperature higher than threshold: \n \nTemperature: \nTime: " + str(
                    self.actuator.timestamp) + "\ncurrent : " + str(
                        self.actuator.getValue()) + "\nAverage :" + str(
                            self.actuator.getAverageValue()
                        ) + "\nSamples :" + str(
                            self.actuator.readings_number) + "\nMin: " + str(
                                self.actuator.min_value) + "\nMax :" + str(
                                    self.actuator.max_value)
                mail.publishMessage("Temperature Alert Python", data)
                logging.info('\nMail sent')
            return True
        except Exception as e:
            logging.info(e)
            #If the mailing fails, the method returns false
            return False
Esempio n. 9
0
class SensorDataManager(object):
    '''
    classdocs
    '''

    #instantiate TempActuatorAdaptor
    tempActuatorAdaptor = TempActuatorAdaptor()
    
    #instantiate ConfigUtil
    configUtil = ConfigUtil()
    
    #instantiate smtp client connector
    smtpClientConnector = SmtpClientConnector()
    
    #set the rgb values
    #no color
    e = [0, 0, 0]
    
    #red color
    r = [255, 0, 0]
    
    #blue color
    b = [0, 0, 255]
    
    #initialize upward red arrow to indicate actuator increasing my temperature
    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 downward blue arrow to indicate actuator increasing my temperature
    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 __init__(self):
        '''
        Constructor
        '''   
        #get the nominal temp from ConfigUtil
        self.nominalTemp = self.configUtil.getIntegerValue("device", "nominalTemp")
     
    #this method takes in sensorData as a parameter and checks it against the nominal temp and takes appropriate action   
    def handleSensorData(self, sensorData):
        
        #get the current sensor value
        sensorVal = sensorData.getCurrentValue()
        
        #check if temperature greater than the nominal temp
        if sensorVal > self.nominalTemp:
            
            #send email notification
            self.sendNotification(sensorData.loggingData, "High Temperature")
            
            #instantiate ActuatorData
            actuatorData = ActuatorData.ActuatorData()
            
            #the thermostat should decrease the temp as the temperature is too hot!
            actuatorData.setCommand("DECREASE TEMP")
            
            #set the name of the actuator 
            actuatorData.setName("Temperature")
            
            #set the value to pixel matrix
            actuatorData.setValue(self.arrowBlueDec)
            
            #send the reference to the Actuator Adaptor
            self.tempActuatorAdaptor.updateActuator(actuatorData)
            
            #return the actuator data reference
            return actuatorData
            
        #check if temperature less than the nominal temp
        elif sensorVal < self.nominalTemp:
            
            #send email notification
            self.sendNotification(sensorData.loggingData, "Low Temperature")
            
            #instantiate ActuatorData
            actuatorData = ActuatorData.ActuatorData()
            
            #the thermostat should increase the temp as the temperature is too cold!
            actuatorData.setCommand("INCREASE TEMP")
            
            #set the name of the actuator 
            actuatorData.setName("Temperature")
            
            #set the value to pixel matrix
            actuatorData.setValue(self.arrowRedInc)
            
            #send the reference to the Actuator Adaptor
            self.tempActuatorAdaptor.updateActuator(actuatorData)
            
            #return the actuator data reference
            return actuatorData
        
        #if temperature is equal to nominal temperature, do nothing and simply return a none    
        else:
        
            #no actuation 
            return None
        
        
    #method for sending the notification via e-mail
    def sendNotification(self, data, topic):
        
        #if the currentValue is greater than or equal to the average by more than the threshold
        if topic == "High Temperature":
            
            #log the difference 
            logging.info('\n Current temperature exceeds the nominal temperature, decreasing the temperature')
            
            #send email with topic indicating excessive temperature
            self.smtpClientConnector.publishMessage(data, "High Temperature")
        
        #if current value is less than the average by more than the threshold
        elif topic == "Low Temperature": 
            
            #log the difference
            logging.info('\n Nominal temperature exceeds the current temperature, increasing the temperature')
            
            #send email with topic indicating excessive temperature
            self.smtpClientConnector.publishMessage(data, "Too low temperature")
        
        #return true for running successfully
        return True
Esempio n. 10
0
class SensorDataManager(object):
    '''
    classdocs
    '''

    #instantiate TempActuatorAdaptor
    multiActuatorAdaptor = MultiActuatorAdaptor()

    #instantiate ConfigUtil
    configUtil = ConfigUtil()

    #instantiate smtp client connector
    smtpClientConnector = SmtpClientConnector()

    def __init__(self):
        '''
        Constructor
        '''

    #this method takes in sensorData as a parameter and checks it against the type of readings and takes appropriate action
    def handleSensorData(self, sensorDatas):

        #initialize the list for actuatorData
        actuatorDataList = []

        #iterate through the sensorDatas list
        for sensorData in sensorDatas:

            #if the reading is directly from i2c bus
            if sensorData.getName() == "i2c humidity":

                #get the current sensor value
                sensorVal = sensorData.getCurrentValue()

                #instantiate ActuatorData
                actuatorData = ActuatorData()

                #the actuator should display the current humidity
                actuatorData.setCommand("DISPLAY I2C Humidity")

                #set the name of the actuator
                actuatorData.setName("I2C Humidity")

                #set the value to the current humidity value
                actuatorData.setValue(sensorVal)

                #send email notification consisting of the reading
                self.sendNotification(sensorData.loggingData,
                                      "Humidity Reading from I2C Bus")

                #append the actuator data to the list
                actuatorDataList.append(actuatorData)

            #if the reading is directly from sensehat api
            elif sensorData.getName() == "sense_hat API humidity":

                #get the current sensor value
                sensorVal = sensorData.getCurrentValue()

                #instantiate ActuatorData
                actuatorData = ActuatorData()

                #the actuator should display the current humidity
                actuatorData.setCommand("DISPLAY SENSE HAT API Humidity")

                #set the name of the actuator
                actuatorData.setName("SENSE HAT API Humidity")

                #set the value to the current humidity value
                actuatorData.setValue(sensorVal)

                #send email notification consisting of the reading
                self.sendNotification(sensorData.loggingData,
                                      "Humidity Reading from SenseHAT API")

                #append the actuator data to the list
                actuatorDataList.append(actuatorData)

        #if no valid sensor data reading
        if len(actuatorDataList) == 0:

            #return none
            return None

        #send the list to the updateActuator method of the multiActuatorAdaptor
        self.multiActuatorAdaptor.updateActuator(actuatorDataList)

        #return the list of actuatorData
        return actuatorDataList

    #method for sending the notification via e-mail
    def sendNotification(self, data, topic):

        #send email with topic indicating excessive temperature
        self.smtpClientConnector.publishMessage(data, topic)

        #create a delay for email to be sent
        sleep(2)

        #return true for running successfully
        return True
Esempio n. 11
0
class Module02Test(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-scopedsou
	instances of complex objects, initialize any requisite connections, etc.
	"""
    def setUp(self):

        #instantiate the variables required
        self.smtpClientConnector = SmtpClientConnector()
        self.tempSensorEmulatorTask = TempSensorEmulatorTask()
        self.tempEmulatorAdaptor = TempEmulatorAdaptor()

    """
	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.smtpClientConnector = None
        self.tempSensorEmulatorTask = None
        self.tempEmulatorAdaptor = None

    """
	 This method tests the publishMessage() of SmtpClientConnector module. It checks whether the SmtpClientConnector is able to successfully 
	 send an email or not by testing it in various scenarios like when the configurations are correct, wrong configurations, wrong values 
	 in configurations, connection failure
	"""

    def testPublishMessage(self):

        #when testing on the pipeline on cloud, the config file has been ignored. hence, load sample config file
        if self.smtpClientConnector.config.configFileLoaded == False:

            self.smtpClientConnector.config.loadConfig(
                '../sample/ConnectedDevicesConfig_NO_EDIT_TEMPLATE_ONLY.props')

        #when default config file is loaded properly (testing on the computer)
        if self.smtpClientConnector.config.configFileLoaded == '../../../config/ConnectedDevicesConfig.props':

            #when configurations are correct
            success = self.smtpClientConnector.publishMessage(
                "Testing Message", "This is a test")

            #test true on success of mail
            self.assertEqual(
                success, True,
                "Message was sent successfully, test case showing false")

            #load the sample config file where the fromAddr and toAddr, authToken are not valid
            self.smtpClientConnector.config.loadConfig(
                '../../../sample/ConnectedDevicesConfig_NO_EDIT_TEMPLATE_ONLY.props'
            )

            #test false on success of mail
            success = self.smtpClientConnector.publishMessage(
                "Testing Message", "This is a test")
            self.assertEqual(
                success, False,
                "Message was not sent successfully, test case showing true")

    """
	This method tests the generateRandomTemperature() method of the TempSensorEmulatorTask module. It checks whether the 
	generator runs in various scenarios such as disabling the emulator, setting the number of readings to 0
	"""

    def testGenerateRandomTemperature(self):

        #enable the emulator
        self.tempSensorEmulatorTask.enableEmulator = True

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

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

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

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

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

        #disable the emulator
        self.tempSensorEmulatorTask.enableEmulator = False

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

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

    """
	This method tests the getSensorData() method of the TempSensorEmulatorTask module. It simply checks
	whether the reference to the sensorData of tempSensorEmulatorTask is valid or not
	"""

    def testGetSensorData(self):

        #check type of the return of the method, should be of type SensorData
        self.assertEqual(type(self.tempSensorEmulatorTask.getSensorData()),
                         SensorData)

        #check if the returned sensorData reference belongs to the tempSensorEmulatorTask's sensorData
        sensorData = self.tempSensorEmulatorTask.getSensorData()
        sensorData.addValue(30)
        self.assertEqual(
            30,
            self.tempSensorEmulatorTask.getSensorData().getCurrentValue())

    """
	 This method tests the sendNotification method of the TempSensorEmulatorTask module. 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.tempSensorEmulatorTask.smtpConnector.config.fileName == '../sample/ConnectedDevicesConfig_NO_EDIT_TEMPLATE_ONLY.props':

            #returns true, notification is being sent
            self.assertEqual(
                True, self.tempSensorEmulatorTask.sendNotification("Hello"))

    """
	This method simply checks whether the adaptor is running successfully
	"""

    def testTempEmulatorAdaptor(self):

        #get the reference to the tempSensorEmulatorTask
        tempSensTask = self.tempEmulatorAdaptor.tempSensorEmulator

        #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.enableEmulator = True

        #run the run function of tempEmulatorAdaptor and get the value of success of the adaptor
        self.assertEqual(True, self.tempEmulatorAdaptor.run())
Esempio n. 12
0
    def setUp(self):

        #instantiate the variables required
        self.smtpClientConnector = SmtpClientConnector()
        self.tempSensorEmulatorTask = TempSensorEmulatorTask()
        self.tempEmulatorAdaptor = TempEmulatorAdaptor()
Esempio n. 13
0
class TempSensorEmulator(threading.Thread):
    '''
    classdocs
    '''
    enableEmulator = False
    prevTempSet = False
    isPrevTempSet = False
    curTemp = 0

    #random temperature limits
    lowVal = 0
    highVal = 30

    #probe rate
    rateInSec = 10

    #keep the alert threshold to +/- 10 degrees
    alertDiff = 10

    #Instantiate SensorData class
    sensorData = SensorData()

    #Instantiate SmtpClient class
    connector = SmtpClientConnector()

    def __init__(self, rateInSec=10):
        '''
        Constructor
        '''
        super(TempSensorEmulator, self).__init__()
        #make sure the rate is 5 seconds
        if rateInSec > 10:
            self.rateInSec = rateInSec

    def run(self):
        while True:
            #execute if the thread is enabled
            if self.enableEmulator:

                #randomly generate a temperature between 0 and 30- model the temperature sensor
                self.curTemp = uniform(float(self.lowVal), float(self.highVal))

                #save this measurement in sensorData instance
                self.sensorData.addValue(self.curTemp)

                print('\n-------------------------')
                print('New sensor Readings:')
                print(' ' + str(self.sensorData))

                #Check if the this is the first reading, if so just move on till the next reading
                if self.isPrevTempSet == False:

                    self.isPrevTempSet = True
                #If there have been already some readings, then go ahead and calculate average temperature
                else:
                    #If the current temperature is not in the range of avg_temp-10 < avg_temp < avg_temp+10
                    if ((abs(self.curTemp - self.sensorData.getAvgValue())) >=
                            self.alertDiff):

                        print('\n Current temp exceeds average by > ' +
                              str(self.alertDiff) + '. Triggering alert...')
                        #If the temperature is out of threshold call publishMessage() to send alert mail
                        #Send the sensorData elements as the body for the message
                        self.connector.publishMessage(
                            'Exceptional sensor Data  [test]', self.sensorData)
            #sleep for 5 seconds
            sleep(self.rateInSec)
class Module02Test(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.emu = TempSensorEmulatorTask()
        self.smtp = SmtpClientConnector()
        self.config = "../../../config/ConnectedDevicesConfig.props"
        self.tempSensor = TempSensorEmulatorTask()
        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.
	
	def testSomething(self):
		pass
	"""
    '@Test'

    #Testing Lower bound of sensor data
    def testgetData(self):
        self.assertGreaterEqual(self.emu.getSensorData(), 0,
                                "Sensor temp less than 0")
        pass

    # Testing SMTP connection and test mail
    def testSmtpData(self):
        self.assertTrue(
            self.smtp.publishMessage(
                "Python Unit Test check",
                "If you are receiving this mail then the python smtp test successful"
            ), "Issue in mail server")
        pass

    # Testing data generation from emulator task
    def testSensorEmulatorTask(self):
        self.assertIsNotNone(self.tempSensor.getSensorData(),
                             "Generated data from getSensordata()")
        pass

    # Testing send notification method
    def testSendNotification(self):
        self.assertIsNotNone(self.tempSensor.sendNotification(),
                             "Generated data from getdata()")
        pass

    # Testing sensor emulator upper bounds
    def testSensorEmulatorTaskUpperBound(self):
        self.assertGreaterEqual(
            30, self.tempSensor.getSensorData(),
            "Generated data from Sensor if greater than 30")
        pass
 def setUp(self):
     self.emu = TempSensorEmulatorTask()
     self.smtp = SmtpClientConnector()
     self.config = "../../../config/ConnectedDevicesConfig.props"
     self.tempSensor = TempSensorEmulatorTask()
     pass
Esempio n. 16
0
class TempSensorEmulatorTask(threading.Thread):
    '''
    classdocs
    '''
    rateInSec = 10
    alertDiff = 0
    sensorData = SensorData()
    enableEmulator = False
    message = ''

    def __init__(self, rateInSec=5, alertDiff=5):
        '''
        Constructor
        '''
        threading.Thread.__init__(self)
        self.connector = SmtpClientConnector()
        self.rateInSec = rateInSec
        self.alertDiff = alertDiff
        self.time = self.sensorData.timeStamp
#         self.average    = self.sensorData.avgValue
#         self.samples    = self.sensorData.getCount()
#         self.min        = self.sensorData.minValue
#         self.max        = self.sensorData.maxValue
#

    '''
    randomly generating a temperature value between 0 C and 30 C, return a reference to SensorData. 
    '''
    def getSensorData(self):
        self.curValue = round(random.uniform(0.0, 30.0), 2)
        #print(self.curValue)
        return self.curValue

    '''
    Check if the randomly generated value is different from the average stored measurement by a configurable threshold(5)
    If the threshold is reached or surpassed, the most recent SensorData (and any other information) 
    will be emailed to a remote service using the SmtpClientConnector module
    '''

    def sendNotification(self):
        if (abs(self.sensorData.curValue - self.sensorData.getAverageValue())
                >= self.alertDiff):
            logging.info('\nCurrent temperature exceeds average by > ' +
                         str(self.alertDiff) + '. Triggering alert...')
            self.average = self.sensorData.avgValue
            self.samples = self.sensorData.getCount()
            self.min = self.sensorData.minValue
            self.max = self.sensorData.maxValue
            self.message = 'Temperature\n' + '\tTime: ' + str(
                self.time) + '\n\tCurrent: ' + str(
                    self.curValue) + '\n\tAverage: ' + str(
                        self.average) + '\n\tSamples: ' + str(
                            self.samples) + '\n\tMin: ' + str(
                                self.min) + '\n\tMax: ' + str(self.max)
            self.connector.publishMessage('Excessive Temperature',
                                          self.message)
            print(self.message)
            #self.connector.publishMessage('Excessive Temperature', self.curValue)

    def run(self):
        while True:
            self.sensorData.addValue(self.getSensorData())
            #print(self.sensorData.curValue)
            #print(self.sensorData.getCurrentValue())
            #print(self.sensorData.getCount())
            #print(self.sensorData.getAverageValue())
            self.sendNotification()
            #print(self.message)
            sleep(self.rateInSec)
Esempio n. 17
0
class TempSensorAdaptor(threading.Thread):
    '''
    classdocs
    '''
    enableAdaptor = False
    prevTempSet = False
    isPrevTempSet = False
    curTemp = 0

    #random temperature limits
    lowVal = 0
    highVal = 30

    #probe rate
    rateInSec = 10

    #keep the alert threshold to +/- 10 degrees
    alertDiff = 3

    #Instantiate SensorData class
    sensorData = SensorData()

    #Instantiate ActuatorData class
    actuatorData = ActuatorData()

    #Instantiate snese_hat class
    sensehat = SenseHat()

    #Instantiate SmtpClientConnector class
    connector = SmtpClientConnector()

    tempActuatorEmulator = TempActuatorEmulator()

    config = ConfigUtil.ConfigUtil(
        '../../../data/ConnectedDevicesConfig.props')
    config.loadConfig()

    nominalTemp = float(
        config.getProperty(ConfigConst.CONSTRAINED_DEVICE,
                           ConfigConst.NOMINAL_TEMP))

    def __init__(self, rateInSec=10):
        '''
        Constructor
        '''
        super(TempSensorAdaptor, self).__init__()
        #make sure the rate is 5 seconds
        if rateInSec > 10:
            self.rateInSec = rateInSec

    def run(self):
        while True:
            #execute if the thread is enabled
            if self.enableAdaptor:

                #Get the temperature reading from sense_hat module
                self.curTemp = self.sensehat.get_temperature_from_humidity()

                #save and process this measurement in sensorData instance
                self.sensorData.addValue(self.curTemp)

                print('\n-------------------------')
                print('New sensor Readings:')
                print(' ' + str(self.sensorData))

                #Check if the this is the first reading, if so just move on till the next reading
                if self.isPrevTempSet == False:

                    self.isPrevTempSet = True
                #If there have been already some readings, then go ahead and calculate average temperature
                else:
                    #If the current temperature is not in the range of avg_temp-10 < avg_temp < avg_temp+10
                    if ((abs(self.curTemp - self.sensorData.getAvgValue())) >=
                            self.alertDiff):

                        temp_diff = abs(self.curTemp -
                                        self.sensorData.getAvgValue())

                        print('\n Current temp exceeds average by > ' +
                              str(temp_diff) + '. Triggering alert...')
                        #Send warning mail to the client
                        self.connector.publishMessage(
                            'Exceptional sensor Data  [test]', self.sensorData)

                        self.actuatorData.setValue(temp_diff)
                        if (self.curTemp > self.nominalTemp):
                            #If the temperature is out of threshold send the data to actuator
                            self.actuatorData.setCommand('DECREASE')

                        elif (self.curTemp < self.nominalTemp):
                            self.actuatorData.setCommand('INCREASE')

                        else:

                            print('\nIdeal temperature')
                            self.actuatorData.setCommand('IDEAL')

                        self.tempActuatorEmulator.processMessage(
                            self.actuatorData)

            #sleep for 5 seconds
            sleep(self.rateInSec)