Example #1
0
    def run(self):
        nominalTemp = int(
            self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,
                                    ConfigConst.NOMINAL_TEMP_KEY))
        #Takes the nominalTemp value from configfile
        while True:
            if self.enableEmulator:
                self.curTemp = uniform(float(self.lowVal), float(self.highVal))
                #Takes the random value of low and high temperatures
                sensorData.addValue(self.curTemp)
                print('\n--------------------')
                print('New sensor readings:')
                print('  ' + str(self.curTemp))
                a = sensorData.__str__()
                print(a)
                SensorData_Json = sensorData.fromSensortoJson(
                    sensorData)  #Convert Sensor data in JSON format
                ActuatorData_Json = actuatorData.fromActuatortoJson(
                    actuatorData)  #Convert Actuator data in JSON format

                #print (a)                                                          #Prints the current sensor data
                if self.isPrevTempSet == False:
                    self.prevTemp = self.curTemp  #Replace previous temperature with current
                    self.isPrevTempSet = True
                else:
                    if (abs(self.curTemp - sensorData.getAvgValue()) >=
                            self.alertDiff):
                        #Setting the alert condition
                        print('\n  Current temp exceeds average by > ' +
                              str(self.alertDiff) + '. Triggering alert...')
                        print(SensorData_Json
                              )  #Prints the Sesnsor Data in JSON format
                        smtpconnector.publishMessage(
                            'Exceptional sensor data [test]', SensorData_Json)
                        print('\n')
                        print("Actuator Data", ActuatorData_Json)
                        with open('SensorData.json', 'w') as f:
                            f.write(
                                SensorData_Json
                            )  #Writes the Sensor data in JSON format to a file
                        #Sending the email
                    if (abs(self.curTemp - nominalTemp) >
                            0):  #Checks the difference in temperature
                        val = self.curTemp - nominalTemp
                        actuatorData.setValue(
                            val
                        )  #Updates actuatorData with difference in temperature
                        if (val > 0):
                            actuatorData.setCommand(
                                1)  #Command set for temperature raise
                        else:
                            actuatorData.setCommand(
                                0)  #Command set for temperature low
                        #TempActuatorEmulator.processMessage(actuatorData)

                        TempActuatorEmulator.processMessage(
                            actuatorData
                        )  #LED Display message with new Actuator Data
                    sleep(self.rateInSec)  #Rest time for CPU
class TempSensorAdaptor(threading.Thread):
    '''
    classdocs
    '''
    actuatorData = None
    tempActuatorEmulator = None
    connector = SmtpClientConnector.SmtpClientConnector()
    sensorData = SensorData.SensorData() 
    alertDiff = 5
    def __init__(self, enableEmulator, lowVal, highVal, curTemp, isPrevTempSet):
        super(TempSensorAdaptor, self).__init__()
        self.enableEmulator = enableEmulator
        self.curTemp = curTemp
        self.lowVal = lowVal
        self.highVal = highVal
        self.isPrevTempSet = isPrevTempSet
        
        self.config = ConfigUtil.ConfigUtil('')
        self.config.loadConfig()
        self.actuatorData = ActuatorData()
        self.tempActuatorEmulator = TempActuatorEmulator()
    def run(self):
        nominalTemp = int(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.NOMINAL_TEMP_KEY))
        while True:
            if self.enableEmulator:
                self.curTemp = uniform(float(self.lowVal), float(self.highVal))
                #self.curTemp = 
                self.sensorData.addValue(self.curTemp)
                
                #print('the sensor readings:') 
                #print(' ' + str(self.sensorData))

                if self.isPrevTempSet == False:

                    self.prevTemp = self.curTemp
                    self.isPrevTempSet = True 
                else:

                    if (abs(self.curTemp - self.sensorData.getAvgValue()) >= self.alertDiff):

                        print('\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggeringalert...')

                        #self.connector.publishMessage('Exceptional sensor data [test]', str(self.sensorData))
                    
                    if (abs(self.curTemp - nominalTemp) > self.alertDiff):
                        
                        
                        val = self.curTemp - nominalTemp
                        self.actuatorData.setValue(val)
                        if (val > 0):
                            
                            self.actuatorData.setCommand(1)
                        else:
                            
                            self.actuatorData.setCommand(0)
                        self.tempActuatorEmulator.processMessage(self.actuatorData)

            sleep(1)    
Example #3
0
 def __init__(self):
     super(TempSensorAdaptor, self).__init__()
     self.config = ConfigUtil.ConfigUtil('')
     self.config.loadConfig()
     self.actuatorData = ActuatorData()
     self.tempActuatorEmulator = TempActuatorEmulator()
     self.senseHat = SenseHat()
     self.coapConnector = CoapSimpleClientConnector.CoapSimpleClientConnector(
     )
 def __init__(self, enableEmulator, lowVal, highVal, curTemp, isPrevTempSet):
     super(TempSensorAdaptor, self).__init__()
     self.enableEmulator = enableEmulator
     self.curTemp = curTemp
     self.lowVal = lowVal
     self.highVal = highVal
     self.isPrevTempSet = isPrevTempSet
     
     self.config = ConfigUtil.ConfigUtil('')
     self.config.loadConfig()
     self.actuatorData = ActuatorData()
     self.tempActuatorEmulator = TempActuatorEmulator()
    def __init__(self, a, r):
        '''
        Constructor
        '''
        self.sense = SenseHat()
        self.tempActuatorEmulator = TempActuatorEmulator()
        self.alertDiff = a
        self.rateInSec = r
        self.sensorData = SensorData
        self.connector = SmtpClientConnector()
        self.config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
        self.config.loadConfig()
        self.nominalTemp = self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE, 'nominalTemp')
#         self.nominalTemp = self.config.getProperty()
        _thread.start_new_thread(self.run())
    def run(self):
        while True:
            if self.enableEmulator:
                
                self.curTemp = self.sh.get_temperature()
                self.sensordata.addValue(self.curTemp, 'Sensor'+str(self.sensorid))
                self.sensorid += 1;

                print('\n--------------------')
                print('New sensor readings:')
                print('  ' + str(self.sensordata))
                print('  Current Temperature: '+ str(round(self.curTemp, 3)))
                print('  Alert interval: [' + str(round(self.nominalaveragetemp - self.threshold,3))+ \
                                            ',' + str(round(self.nominalaveragetemp + self.threshold,3)) + ']' )
                print('  NominalTemp: ' + str(round(self.nominalaveragetemp,3)))
            
                if self.isPrevTempSet == False:
                    self.prevTemp = self.curTemp
                    self.isPrevTempSet = True
                
                if (abs(self.curTemp - self.nominalaveragetemp) > self.threshold):
                        print('|Alert|  Current temperature exceeds safe range: ' 
                              +str(round(abs(self.curTemp-self.nominalaveragetemp), 3))) 
                        self.connector.publishMessage('Exceptional sensor data [test]', str(self.sensordata))
                        print('         Data has been sent to a remote system.')
                        
                if((self.curTemp - self.nominalaveragetemp > 0):
                    self.actuatordata.setCommand("Lower")
                if((self.curTemp - self.nominalaveragetemp < 0):
                    self.actuatordata.setCommand("Raise")
                actuatoremulator = TempActuatorEmulator()
                actuatoremulator.processMessage(self.actuatordata)
                                  

            sleep(self.sleepcycle)
            
            
            
            
            
Example #7
0
    def run(self):
        while True:
            TAE = TempActuatorEmulator()
            TAE.start()
            self.curTemp = self.senseHat.get_temperature()
            self.sensorData.addValue(self.curTemp)
            print('\n--------------------')
            print('New sensor readings: \n')
            print(' ' + str(self.sensorData))
            
            print('New actuator readings: \n')
            print(' ' + str(self.actuatorData))

            if (abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))) > self.alertDiff):
                print('\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggering alert...')
                try:
                    self.connector.publishMessage('Exceptional sensor data [test]', self.sensorData)
                except Exception as e:
                    print("Failed to send email\n" + str(e))
                    
                print('\n Actuator activating...')
                if (self.curTemp > float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))):
                    self.actuatorData.addValue(1, abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))))
                else:
                    self.actuatorData.addValue(2, abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))))
            
            
                
                # LED Display
                #self.senseHatLed.displayMsg(abs(self.curTemp - self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY)))
               
                
            else:
                self.actuatorData.addValue(0, 0)
            
        self.enableTempEmulator.updateData(self.actuatorData)    
        sleep(self.updateTime)
Example #8
0
 def run(self):
     sensordata = SensorData.SensorData()
 #    senseHatLedActivator = SenseHatLedActivator.SenseHatLedActivator()
     senseledThread = SenseHatLedActivator.SenseHatLedActivator()
     senseledThread.start()
     #senseHatLedActivator.run()
     
     while True:
         sense = SenseHat()
         temperature = sense.get_temperature()
         sensordata.addValue(temperature)
         
         #smtp module
         if(abs(sensordata.getValue()-sensordata.getAvgValue())>=self.threshold):
             logging.info('\n  Current temp exceeds average by > ' + str(self.threshold) + '. Triggering alert...')
             smtpClientConnector = SmtpClientConnector.SmtpClientConnector()
             smtpClientConnector.publishMessage("Excessive Temp", sensordata)
             
         nomialtemp = self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.NOMINAL_TEMP_KEY)
         
         #senseHat Led module
         actuatordata = ActuatorData()
         if(sensordata.getValue != nomialtemp):
             logging.info('\n temperature is different from nomialtemp')   
             actuatordata.command = 1
             actuatordata.statusCode = 1
             actuatordata.errCode = 0
             actuatordata.val = temperature
             actuatordata.stateData = temperature - float(nomialtemp)
             TempActuatorEmulator().processMessage(actuatordata, senseledThread)
         else:
             logging.info('\n temperature is equal to nomialtemp')   
             actuatordata.command = 1
             actuatordata.statusCode = 0
             actuatordata.errCode = 0
             actuatordata.val = temperature
         time.sleep(10)
import labs.common.ConfigUtil as ConfigUtil
from threading import Thread
from time import sleep
from random import uniform
from labs.common import SensorData
from labs.module02 import SmtpClientConnector
from labs.common import ConfigConst
from labs.common.ActuatorData import ActuatorData
from labs.module03.TempActuatorEmulator import TempActuatorEmulator

sensorData = SensorData.SensorData()  #Create an instance of SensorData class
smtpconnector = SmtpClientConnector.SmtpClientConnector(
)  #Create an instance of SmtpClientConnector
actuatorData = ActuatorData()  #Create an instance of ActuatorData
TempActuatorEmulator = TempActuatorEmulator(
)  #Create an instance of TempActuatorEmulator


class TempSensorAdaptor(Thread):
    '''
    Constructor
    '''
    def __init__(self):  # Overriding constructor __init__ here with parameters
        Thread.__init__(
            self)  # Calling __init__(self) from parent class Thread
        self.threadID = 1  # initializing Thread ID
        self.enable_Adaptor = False  # initializing enable_Adaptor
        self.name = "Thread"  # initializing name of the Thread
        self.counter = 1  # initializing counter for thread i.e how many threads we want to create
        self.sleep_cycle = 10  # Specifies suspend time for the next reading
        self.lowVal = 10  # Lower value of temperature from sensor simulator
Example #10
0
 def __init__(self):
     super(TempSensorAdaptor, self).__init__()
     self.config = ConfigUtil.ConfigUtil('')
     self.config.loadConfig()
     self.actuatorData = ActuatorData()
     self.tempActuatorEmulator = TempActuatorEmulator()
Example #11
0
class TempSensorAdaptor(threading.Thread):
    enableAdaptor = False
    actuatorData = None
    tempActuatorEmulator = None
    connector = SmtpClientConnector.SmtpClientConnector()
    sensorData = SensorData.SensorData()
    alertDiff = 5
    rateInSec = DEFAULT_FATE_IN_SEC
    enableEmulator = False
    lowVal = 0
    highVal = 30
    curTemp = 0
    isPrevTempSet = True

    #Constructor
    def __init__(self):
        super(TempSensorAdaptor, self).__init__()
        self.config = ConfigUtil.ConfigUtil('')
        self.config.loadConfig()
        self.actuatorData = ActuatorData()
        self.tempActuatorEmulator = TempActuatorEmulator()

    #set enableEmulator
    def setEnableAdaptorFlag(self, flag):
        self.enableAdaptor = flag

    def run(self):
        nominalTemp = int(
            self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,
                                    ConfigConst.NOMINAL_TEMP_KEY)
        )  #get the value of nominal temperature from ConfigConst class
        while True:
            if self.enableEmulator:
                self.curTemp = uniform(float(self.lowVal), float(
                    self.highVal))  #get a emulated temperature
                self.sensorData.addValue(
                    self.curTemp)  #add current temperature to SensorData class
                print('\n--------------------')
                print('New sensor readings:')
                #print(' ' + str(self.sensorData))
                if self.isPrevTempSet == False:  #skip if this is the first temperature
                    self.prevTemp = self.curTemp
                    self.isPrevTempSet = True
                else:
                    if (
                            abs(self.curTemp - self.sensorData.getAvgValue())
                            >= self.alertDiff
                    ):  #if the current temperature is larger or less than the average temperature more than the alert value, publish the message
                        print('\n Current temp exceeds average by > ' +
                              str(self.alertDiff) + '. Triggeringalert...')
                        #self.connector.publishMessage('Exceptional sensor data [test]', str(self.sensorData))
                    if (
                            abs(self.curTemp - nominalTemp) > self.alertDiff
                    ):  #if the current temperature is larger or less than the nominal temperature more than the alert level, run the actuator to adjust the temperature
                        print('\n+++++++++++++++++++')
                        print('to the actuator:')
                        val = self.curTemp - nominalTemp
                        self.actuatorData.setValue(val)
                        if (val > 0):
                            print('val > 0')
                            self.actuatorData.setCommand(1)
                        else:
                            print('val < 0')
                            self.actuatorData.setCommand(0)
                        self.tempActuatorEmulator.processMessage(
                            self.actuatorData)
            sleep(self.rateInSec)
class TempSensorAdaptor(object):
    '''
    classdocs
    '''
    rateInSec = 10.0
    alertDiff = 10.0
    curDegree = 0.0
    nominalTemp = 10.0
    sense=None

    '''
    Initial all the variable I need
    '''
    def __init__(self, a, r):
        '''
        Constructor
        '''
        self.sense = SenseHat()
        self.tempActuatorEmulator = TempActuatorEmulator()
        self.alertDiff = a
        self.rateInSec = r
        self.sensorData = SensorData
        self.connector = SmtpClientConnector()
        self.config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
        self.config.loadConfig()
        self.nominalTemp = self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE, 'nominalTemp')
#         self.nominalTemp = self.config.getProperty()
        _thread.start_new_thread(self.run())
    
    '''
    Connect to senseHat and obtain the environment temperature.
    '''
    def readTempFromSH(self):
        self.sense.clear()
        self.curDegree = self.sense.get_temperature()
    
    '''
    Store the temperature into SenseData.
    '''
    def addTempToSensorData(self):
        self.sensorData.addValue(self.sensorData, self.curDegree)
        now = datetime.datetime.now()
        print(str(now) + "\t" + str(self.curDegree))
        print(str(now) + "\t" + str(self.sensorData.getAvgValue(self.sensorData)))
        print("\n")
    
    '''
    Determine whether or not the particular temperature is higher or lower than the average temperature and then alert the user by sending email.
    '''
    def alert(self):
        if (abs(self.sensorData.getValue(self.sensorData) - self.sensorData.getAvgValue(self.sensorData)) >= self.alertDiff):
            # Start to send email
            logging.info('\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggering alert...')
            print("Starting sending email...")
            output = self.sensorData.__str__(self.sensorData)
            self.connector.publishMessage("Excessive Temp", output)
    
    '''
    Determine whether or not the new temperature value is higher or lower than the nominal temperature which is set in ConnectedDevicesConfig
    '''
    def adjust(self):
        if self.sensorData.getValue(self.sensorData) < float(self.nominalTemp) or self.sensorData.getValue(self.sensorData) > float(self.nominalTemp):
            self.actuatorData = ActuatorData()
            self.actuatorData.updateData(1, 1, 0, "adjust", self.sensorData.getValue(self.sensorData))
            self.tempActuatorEmulator.processMessage(self.actuatorData)
    
    '''
    Start a new thread to do the task.
    '''
    def run(self):
        while True:
            self.readTempFromSH()
            self.addTempToSensorData()
            self.alert()
            self.adjust()
            sleep(self.rateInSec)
Example #13
0
class TempSensorAdaptor(threading.Thread):
    enableAdaptor = False
    actuatorData = None
    tempActuatorEmulator = None
    connector = SmtpClientConnector.SmtpClientConnector()
    sensorData = SensorData.SensorData()
    alertDiff = 1
    rateInSec = DEFAULT_FATE_IN_SEC
    enableEmulator = False
    lowVal = 0
    highVal = 30
    curTemp = 0
    isPrevTempSet = True

    # Constructor
    def __init__(self):
        super(TempSensorAdaptor, self).__init__()
        self.config = ConfigUtil.ConfigUtil('')
        self.config.loadConfig()
        self.actuatorData = ActuatorData()
        self.tempActuatorEmulator = TempActuatorEmulator()
        self.senseHat = SenseHat()
        self.coapConnector = CoapSimpleClientConnector.CoapSimpleClientConnector(
        )

    # set enableEmulator
    def setEnableAdaptorFlag(self, flag):
        self.enableAdaptor = flag

    def run(self):
        self.nominalTemp = int(
            self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,
                                    ConfigConst.NOMINAL_TEMP_KEY)
        )  # get the value of nominal temperature from ConfigConst class
        while True:
            if self.enableAdaptor:
                self.curTemp = self.senseHat.get_temperature(
                )  # get a emulated temperature
                self.sensorData.addValue(
                    self.curTemp
                )  # add current temperature to SensorData class
                print('\n--------------------')
                print('New sensor readings:')
                self.coapConnector.initClient("")
                self.coapConnector.handleGetTest("myHomeTemperature")
                self.coapConnector.handlePostTest("myHomeTemperature",
                                                  str(self.curTemp))
                if self.isPrevTempSet == False:  # skip if this is the first temperature
                    self.prevTemp = self.curTemp
                    self.isPrevTempSet = True
                else:
                    self.sendEmail()
            sleep(self.rateInSec)

    # if the current temperature is larger or less than the average temperature more than the alert value, publish the message
    def sendEmail(self):
        if (abs(self.curTemp - self.sensorData.getAvgValue()) >=
                self.alertDiff):
            print('\n Current temp exceeds average by > ' +
                  str(self.alertDiff) + '. Triggeringalert...')
            self.connector.publishMessage('Exceptional sensor data [test]',
                                          str(self.sensorData))

    # if the current temperature is larger or less than the nominal temperature more than the alert level, run the actuator to adjust the temperature
    def tragerActuator(self, data):
        self.tempActuatorEmulator.processMessage(data)
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)