def run(self):
     while True:
         if self.enableEmulator:
             
             # Generate random value of current temperature between max and min values from Sensor data file
             self.sensor.curValue = random.uniform(float(self.sensor.getMinValue()), float(self.sensor.getMaxValue()))
             
             # Add the generated temperature value in the sensor data file
             self.sensor.addValue(self.sensor.curValue)
             
             # Generate readable output
             print('\n--------------------')
             print('New temperature is generating:')
             print('  ' + str(self.sensor))
             
             k = abs(self.sensor.curValue - self.sensor.getAvgValue())
             
             # Condition for sending message
             if (k >= self.alertDiff):
                 
                 # Initialize object of SmtpClientConnector to publish the message 
                 sen = SmtpClientConnector.SmtpClientConnector()
                 print('\n  Oops...Current temperature exceeds average by > ' + str(k) + '. Sending notification...')
                 sen.publishMessage('This is the updated sensor information', self.sensor)
                 
         sleep(self.rateInSec)
class TempSensorAdaptor(Thread):

    #creating the sensor data object and initial values to use inside Adaptor
    sensorData = SensorData.SensorData()
    actuator = ActuatorData.ActuatorData()
    connector = SmtpClientConnector.SmtpClientConnector()
    actuatorEmulator = TempActuatorEmulator.TempActuatorEmulator()
    isPrevTempSet = False
    lowVal = 0
    highVal = 30
    nominalTemp = 20
    alertDiff = 5

    #initiating the thread for the Adaptor
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        while True:
            if self.enableAdaptor:
                #generate temperature information
                self.curTemp = uniform(float(self.lowVal), float(self.highVal))
                self.sensorData.addValue(self.curTemp)
                print('\n--------------------')
                print('New sensor readings:')
                print(' ' + str(self.sensorData))

                if self.isPrevTempSet == False:
                    self.prevTemp = self.curTemp
                    self.isPrevTempSet = True
                else:
                    #checking for alerting difference and sending the message through SMTP
                    if (abs(self.curTemp - self.sensorData.getAvgValue()) >=
                            self.alertDiff):
                        print('\n Current temp exceeds average by > ' +
                              str(self.alertDiff) + '. Triggering alert...')
                        self.connector.publishMessage(
                            'Exceptional sensor data [test]', self.sensorData)
                '''
                checking to see if the temperature exceeds nominal temperature to set status
                for actuator and send the message accordingly
                '''
                if (self.curTemp > self.nominalTemp):

                    self.actuator.setCommand(ActuatorData.COMMAND_ON)
                    self.actuator.setStatusCode(ActuatorData.STATUS_ACTIVE)
                    self.actuator.setErrorCode(ActuatorData.ERROR_OK)
                    self.actuator.setStateData('Decrease')
                    self.actuator.setValue(self.curTemp - self.nominalTemp)
                    self.actuatorEmulator.processMessage(self.actuator)

                elif (self.curTemp < self.nominalTemp):

                    self.actuator.setCommand(ActuatorData.COMMAND_OFF)
                    self.actuator.setStatusCode(ActuatorData.STATUS_ACTIVE)
                    self.actuator.setErrorCode(ActuatorData.ERROR_OK)
                    self.actuator.setStatusCode('Increase')
                    self.actuator.setValue(self.curTemp - self.nominalTemp)
                    self.actuatorEmulator.processMessage(self.actuator)
            sleep(5)
class TempSensorEmulator(Thread):

    #creating the sensor data object and initial values to use inside Emulator
    sensorData = SensorData.SensorData()
    connector = SmtpClientConnector.SmtpClientConnector()
    isPrevTempSet = False
    lowVal = 0
    highVal = 30
    alertDiff = 5

    #initiating the thread for the emulator
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        while True:
            if self.enableEmulator:
                self.curTemp = uniform(float(self.lowVal), float(self.highVal))
                self.sensorData.addValue(self.curTemp)
                print('\n--------------------')
                print('New 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) + '. Triggering alert...')
                        self.connector.publishMessage(
                            'Exceptional sensor data [test]', self.sensorData)
            sleep(5)
class TempSensorEmulator (threading.Thread):
    sensorData = SensorData.SensorData()
    connector = SmtpClientConnector.SmtpClientConnector()
    enableEmulator = False
    isPrevTempSet  = False
    rateInSec      = DEFAULT_RATE_IN_SEC
    sensorData.setName('Temperature')
    
    lowVal = 0
    highVal = 30
    alertDiff = 5
   
    def __init__(self, rateInSec = DEFAULT_RATE_IN_SEC):
        super(TempSensorEmulator, self).__init__()
        
        if rateInSec > 0:
            self.rateInSec = rateInSec

    def run(self):
            while True:
                if self.enableEmulator:
                    self.curTemp = uniform(float(self.lowVal), float(self.highVal))
                    self.sensorData.addValue(self.curTemp)
                    print('\n--------------------')
                    print('New 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]', self.sensorData)
                sleep(self.rateInSec)
Esempio n. 5
0
    def run(self):
        while True:
            '''
                Enabling the Emulator and generates the current value provided within the range
                and printing the sensor data.
                '''
            if self.enableEmulator:
                self.sensor.curVal = uniform(float(self.sensor.getMinValue()),
                                             float(self.sensor.getMaxValue()))
                self.sensor.addValue(self.sensor.curVal)
                print(self.sensor)
            '''
                Alert Notification will be sent if the current value exceeds the threshold value
                which is the addition of the average value and 10
                '''
            if self.sensor.curVal >= (self.sensor.getAvgValue() + 10):
                data = (self.sensor)
                print(data)
                print("Warning: Temperature has been surpassed")

                sensor_notification = SmtpClientConnector.SmtpClientConnector()
                sensor_notification.publishMessage(
                    "Temperature Alert Notification", data)
            '''
            providing a delay for every sensor readings
            '''
            delay = int(
                self.temp_delay.getProperty(
                    ConfigConst.ConfigConst.CONSTRAINED_DEVICE,
                    ConfigConst.ConfigConst.POLL_CYCLES_KEY))
            sleep(delay)
    def run(self):
        while True:
            '''
                Enabling the Emulator and generates the current value provided within the range
                and printing the sensor data.
                '''
            if self.enableAdaptor:
                self.sensor.curVal = uniform(float(self.sensor.getMinValue()),
                                             float(self.sensor.getMaxValue()))
                self.sensor.addValue(self.sensor.curVal)
                nominal_temp = self.temp.getProperty(
                    ConfigConst.ConfigConst.CONSTRAINED_DEVICE,
                    ConfigConst.ConfigConst.NOMINAL_TEMP)
                self.sensor.diffVal = self.sensor.curVal - self.sensor.avgVal
                print(self.sensor)
                '''
                Alert Notification will be sent if the current value exceeds or very lesser than the nomial temperature
                '''
                if self.sensor.curVal >= (self.sensor.getAvgValue() + 3):
                    data = (self.sensor)
                    self.sensor.timestamp = datetime.now()
                    SensorData.SensorData.surpassed_values.append(self.sensor)
                    print(SensorData.SensorData.surpassed_values)
                    print("Warning: Temperature has been surpassed")

                    sensor_notification = SmtpClientConnector.SmtpClientConnector(
                    )
                    sensor_notification.publishMessage(
                        "Temperature Alert Notification: ", data)
                '''
                Determining the difference between the nominal and the current temperature
                using actuator data
                '''
                if self.sensor.curVal != nominal_temp:
                    self.actuator_data = ActuatorData.ActuatorData()
                    self.diff = (self.sensor.curVal - float(nominal_temp))

                    if self.diff > 0:
                        self.actuator_data.setValue(self.sensor.curVal -
                                                    float(nominal_temp))
                        self.actuator_data.setCommand(ActuatorData.COMMAND_SET)
                    else:
                        self.actuator_data.setValue(
                            float(nominal_temp) - self.sensor.curVal)
                        self.actuator_data.setCommand(
                            ActuatorData.COMMAND_RESET)

                    print(
                        "The difference between the nominal temp and the current temp is: "
                        + str(self.actuator_data.getValue()) + chr(176) + 'C')
                    self.tempEmulator.publishMessage(self.actuator_data)
                '''
                providing a delay for every sensor readings
                '''
                delay = int(
                    self.temp.getProperty(
                        ConfigConst.ConfigConst.CONSTRAINED_DEVICE,
                        ConfigConst.ConfigConst.POLL_CYCLES_KEY))
                sleep(delay)
Esempio n. 7
0
 def __init__(self, name):
     Thread.__init__(self)
     self.enableAdaptor = True;
     self.sensorData = SensorData.SensorData(name, 0, 30);
     self.actuator = ActuatorData.ActuatorData()
     self.connector = SmtpClientConnector.SmtpClientConnector()
     self.tempConf = ConfigUtil.ConfigUtil('../../../config/ConnectedDevicesConfig.props'); 
     self.actuatorEmulator = TempActuatorEmulator.TempActuatorEmulator();
Esempio n. 8
0
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)    
 def on_message(self, client, userdata, msg):
     logging.info("the :\n" + str(msg.payload.decode("utf-8")))
     logging.info("message topic=" + str(msg.topic))
     logging.info("message qos=" + str(msg.qos))
     logging.info("message retain flag=" + str(msg.retain))
     smtpClientConnector = SmtpClientConnector.SmtpClientConnector()
     smtpClientConnector.publishMessage("autoset airconditioner",
                                        str(msg.payload.decode("utf-8")))
     senseHat = SenseHat()
     senseHat.show_message(str(msg.payload.decode("utf-8")))
     sleep(5)
     senseHat.clear()
Esempio n. 10
0
class TempSensorAdaptor():

    #Initialization of each parameters
    lowVal = 0
    highVal = 0
    cruTemp = 0
    alertDiff = 5
    enableAdaptor = False
    isPrevTempSet = False

    #Connecting to SMTP services
    connector = SmtpClientConnector.SmtpClientConnector()

    #Get the sensor data
    sensordata = sense_hat.SenseHat
    p = sensordata.get_temperature(1)

    #Get the value of parameters from the App
    def __init__(self, lowVal, highVal, curTemp, enableEmulator):
        self.lowVal = lowVal
        self.highVal = highVal
        self.curTemp = curTemp
        self.enableEmulator = enableEmulator

#Generate the Information that will be delivered

    def run(self):
        while True:
            if self.enableAdaptor:
                self.p = uniform(float(self.lowVal), float(self.highVal))
                self.addValue(self.p)
                print('\n-----------------------')
                print('This is your current condition:')
                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('Warning!!!',
                                                  self.sensordata)
            sleep(30)
 def run(self):
     count = 10
     sensordata = SensorData.SensorData()
     while count > 0:
         #generate a random temperature in [0,30]
         temperature = random.uniform(0.0, 30.0)
         sensordata.addValue(temperature)
         #    self.sendNotification()
         #check if the temperature is surpass the threshold
         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)
         count = count - 1
         time.sleep(30)
Esempio n. 12
0
 def run(self):
     while True:
         if self.enableEmulator:
             self.sensor.curVal = uniform(float(self.sensor.getMinValue()),
                                          float(self.sensor.getMaxValue()))
             self.sensor.addValue(self.sensor.curVal)
             print(self.sensor)
             if self.sensor.curVal >= (self.sensor.getAvgValue() + 7):
                 data = (self.sensor)
                 print(data)
                 print("Warning")
                 sen_not = SmtpClientConnector.SmtpClientConnector()
                 sen_not.publishMessage("Temperature Notification", data)
             delay = int(
                 self.temp_delay.getProperty(
                     ConfigConst.ConfigConst.CONSTRAINED_DEVICE,
                     ConfigConst.ConfigConst.POLL_CYCLES_KEY))
             sleep(delay)
 def run(
     self
 ):  #overriding run method is used to perform the desired functionality
     while True:
         if self.enableEmulator:
             #sense = SenseHat();
             #self.sensor.curVal = sense.get_temperature_from_pressure();
             self.sensor.curVal = uniform(float(self.sensor.getMinValue()),
                                          float(self.sensor.getMaxValue()))
             self.sensor.addValue(self.sensor.curVal)
             nominal_temp = self.temp.getProperty(
                 ConfigConst.ConfigConst.CONSTRAINED_DEVICE,
                 ConfigConst.ConfigConst.NOMINAL_TEMP)
             self.sensor.diffVal = self.sensor.curVal - self.sensor.avgVal
             print(self.sensor)
             if self.sensor.curVal >= (self.sensor.getAvgValue() + 2):
                 data = (self.sensor)
                 self.sensor.timestamp = datetime.now()
                 SensorData.SensorData.breach_values.append(self.sensor)
                 print(SensorData.SensorData.breach_values)
                 print(
                     "Warning!! value of temperature exceeded the average temperature by %.2f degrees"
                     % (self.sensor.diffVal))
                 sen_not = SmtpClientConnector.SmtpClientConnector()
                 sen_not.publishMessage("Temperature Notification", data)
             if self.sensor.curVal != nominal_temp:
                 self.actuator_data = ActuatorData.ActuatorData()
                 self.diff = (self.sensor.curVal - float(nominal_temp))
                 if self.diff > 0:
                     self.actuator_data.setValue(self.sensor.curVal -
                                                 float(nominal_temp))
                     self.actuator_data.setCommand(ActuatorData.COMMAND_SET)
                 else:
                     self.actuator_data.setValue(
                         float(nominal_temp) - self.sensor.curVal)
                     self.actuator_data.setCommand(
                         ActuatorData.COMMAND_RESET)
                 print("Actual Vale : ", str(self.actuator_data.getValue()))
                 self.temp_emul.publishMessage(self.actuator_data)
             delay = int(
                 self.temp.getProperty(
                     ConfigConst.ConfigConst.CONSTRAINED_DEVICE,
                     ConfigConst.ConfigConst.POLL_CYCLES_KEY))
             sleep(delay)
Esempio n. 14
0
class TempSensorEmulator(threading.Thread):
    rateInSec = DEFAULT_FATE_IN_SEC
    connector = SmtpClientConnector.SmtpClientConnector()
    sensorData = SensorData.SensorData()
    alertDiff = 5
    enableEmulator = False
    lowVal = 0
    highVal = 30
    curTemp = 0
    isPrevTempSet = True

    #Constructor
    def __init__(self):
        super(TempSensorEmulator, self).__init__()

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

    def run(self):
        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
                elif (
                        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))
            sleep(self.rateInSec)
 def __init__(self):
     '''
     Constructor
     '''
     self.mqttClient = mqttClient.Client()
     self.config = ConfigUtil.ConfigUtil()
     self.sensoData = SensorData.SensorData()
     self.config.loadConfig()
     self.brockerKeepAlive = 60
     self.connected_flag = False
     
     self.pemfile = "/home/raspberry/workspace/ubidots_cert.pem"
     self.authToken = 'A1E-nDuSgklKdOve42x5KXvi49lTs3pAi2'
     self.port = 8883
     self.brokerAddr = 'things.ubidots.com'
     self.password = ''
     
     self.smtp = SmtpClientConnector.SmtpClientConnector()
     self.timeStamp = str(datetime.now())
     self.senseled = SOSLed.SOSLed()
     self.sensehatled = SenseHatLedActivator.SenseHatLedActivator()
    def run(self):
        sensordata = SensorData.SensorData()

        while True:
            sense = SenseHat()
            #generate new temperature data
            temperature = sense.get_temperature()
            sensordata.addValue(temperature)
            #add into log
            logging.info(
                "\n---------------------------------\nNew sensor readings:\n" +
                "name=" + sensordata.name + ",timeStamp=" +
                sensordata.timeStamp + ",minValue=" +
                str(sensordata.minValue) + ",aveValue=" +
                str(sensordata.avgValue) + ",maxValue=" +
                str(sensordata.maxValue) + ",curValue=" +
                str(sensordata.curValue) + ",totValue=" +
                str(sensordata.totValue) + ",sampleCount=" +
                str(sensordata.sampleCount))

            #convert to json format from python object
            datautil = DataUtil()
            jsondata = datautil.toJsonFromSensorData(sensordata)
            if (abs(sensordata.curValue - sensordata.avgValue) > 2):
                logging.info(
                    "\nCurrent temp exceeds average by >2. Converting data...\n"
                    + "JSON data:\n" + jsondata)

            #smtp module
            smtpClientConnector = SmtpClientConnector.SmtpClientConnector()
            smtpClientConnector.publishMessage("Temperature", jsondata)
            # logging.info("send email successfully")

            #write json dta to filesystem
            of = open("tempData.json", "w+")
            of.write(jsondata)
            of.close()
            # logging.info("write data as JSON file to filesystem successfully")

            time.sleep(10)
Esempio n. 17
0
 def run(self):
     while True:
         if self.enableTempEmulator:
             if self.isPrevTempSet == False:
                 # corner code
                 self.prevTemp = self.curTemp
                 self.isPrevTempSet = True
             else:
                 self.curTemp = uniform(float(self.min_value), float(self.max_value))
                 self.tempSensorData.addNewValue(self.curTemp)
                 print('----------------------------')
                 print('New sensor readings:')
                 print(str(self.tempSensorData))
                 if abs(self.tempSensorData.avgTemp - self.tempSensorData.curTemp) > 5:
                     print("Current temp exceeds average by >" + str(abs(self.tempSensorData.avgTemp - self.curTemp)))
                     # config data path
                     path = "../../../data/ConnectedDevicesConfig.props"
                     # new SmtpClientConnector instance add path
                     emailSender = SmtpClientConnector.SmtpClientConnector(path)
                     emailSender.sendEmailMessage("TemperatureEmulator(Exceptional)", self.tempSensorData)
                     print("")
             sleep(self.rateInSec)
    def run(self):
        while True:
            if self.enableEmulator:
                self.sensor.curVal = uniform(float(self.sensor.getMinValue()),
                                             float(self.sensor.getMaxValue()))
                self.sensor.addValue(self.sensor.curVal)
                self.sensor.diffVal = self.sensor.curVal - self.sensor.avgVal
                print(self.sensor)
                if self.sensor.curVal >= (self.sensor.getAvgValue() + 2):
                    data = DataUtil()
                    self.sensor.timestamp = datetime.now()
                    json_data = data.toJsonfromSensor(self.sensor)
                    SensorData.SensorData.breach_values.append(self.sensor)
                    print(SensorData.SensorData.breach_values)
                    print(
                        "warning!!Temperature exceeded the average temperature by %.2f degrees"
                        % (self.sensor.diffVal))
                    sen_not = SmtpClientConnector.SmtpClientConnector()
                    sen_not.publishMessage("Temperature Notification",
                                           json_data)

                sleep(3)
Esempio n. 19
0
    def run(self):
        while True:
            '''
                Enabling the Emulator and generates the current value provided 
                within the range and printing the sensor data.
                '''
            if self.enableAdaptor:
                self.sensor.curVal = uniform(float(self.sensor.getMinValue()),
                                             float(self.sensor.getMaxValue()))
                self.sensor.addValue(self.sensor.curVal)
                self.sensor.diffVal = self.sensor.curVal - self.sensor.avgVal
                print(self.sensor)
                '''
                Alert Notification will be sent if the current value exceeds
                the average value by 3 then the mail will be sent, and
                printing the JSON string in the console output
                '''
                if self.sensor.curVal >= (self.sensor.getAvgValue() + 3):
                    data = DataUtil.DataUtil()
                    self.sensor.timestamp = datetime.now()
                    json_data = data.SensorDataToJson(self.sensor)
                    SensorData.SensorData.surpassed_values.append(self.sensor)
                    #print(SensorData.SensorData.surpassed_values)
                    print("Warning: Temperature has been surpassed")
                    print("\nJSON data: " + json_data + '\n')

                    sensor_notification = SmtpClientConnector.SmtpClientConnector(
                    )
                    sensor_notification.publishMessage(
                        "Temperature Alert Notification: ", json_data)
                '''
                providing a delay for every sensor readings
                '''
                delay = int(
                    self.temp.getProperty(
                        ConfigConst.ConfigConst.CONSTRAINED_DEVICE,
                        ConfigConst.ConfigConst.POLL_CYCLES_KEY))
                sleep(delay)
Esempio n. 20
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)
Esempio n. 21
0
class TempSensorEmulatorTask(object):
    '''
    classdocs
    '''
    
    #initialize sensor data to hold the aggregate and current temp values
    sensorData = SensorData.SensorData()
    
    #intialize smtp connector for sending notifications
    smtpConnector = SmtpClientConnector.SmtpClientConnector()
    
    #disable the emulator initially
    enableEmulator = False

    '''
    constructor takes in the lower and upper bound on temperature generator, 
    how often it should generate temp and the threshold for max difference between 
    average and current temp
    '''
    def __init__(self, minTemp = 0.0, maxTemp = 30.0, rateInSec = 3, threshold = 5.0, numReadings = 10):
        '''
        Constructor
        '''
        
        #set the values to the default values or the one sent while instantiating
        self.rateInSec = rateInSec
        self.minTemp = minTemp
        self.maxTemp = maxTemp
        self.threshold = float(threshold)
        self.numReadings = numReadings
    
    #method to generate a random temperature between the lower and upper bound
    def generateRandomTemperature(self):
        
        #generator 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 emulator is enabled
            if self.enableEmulator:

                #generate a random temperature 
                self.sensorData.addValue(random.uniform(float(self.minTemp), float(self.maxTemp)))
                
                #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)
                
                #check if the current value and the average value differ by more than the threshold
                if abs(self.sensorData.getCurrentValue() - self.sensorData.getAverageValue()) > self.threshold:
                    
                    #send notfication if so
                    self.sendNotification(data)
                
                #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 emulator is not enabled
            else:
                
                #generator didn't run
                return False
            
        #the generator is done running
        return True
                
                
            
    #method that returns the reference to the sensorData
    def getSensorData(self) -> SensorData.SensorData:   
        return self.sensorData
    
    #method for sending the notification via e-mail
    def sendNotification(self, data):
        
        #if the currentValue is greater than or equal to the average by more than the threshold
        if self.getSensorData().getCurrentValue() >= self.getSensorData().getAverageValue():
            
            #log the difference 
            logging.info('\n Current temperature exceeds average by > ' + str(self.threshold) + '. Triggering alert ')
            
            #send email with topic indicating excessive temperature
            self.smtpConnector.publishMessage("Excessive Temperature", data)
        
        #if current value is less than the average by more than the threshold
        elif self.getSensorData().getCurrentValue() < self.getSensorData().getAverageValue(): 
            
            #log the difference
            logging.info('\n Average temperature exceeds current value by >' + str(self.threshold) + '. Triggering alert ')
            
            #send email with topic indicating excessive temperature
            self.smtpConnector.publishMessage("Too low temperature", data)
        
        #return true for running successfully
        return True

            
            
        
class TempSensorAdaptorTask(Thread):
    '''
    Variables are defined and objects of required classes are created with the class scope.
    '''
    sensorData = SensorData()  #constructor of sensorData 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.
    du = DataUtil()
    '''
    nominal temperature is fetched from configuration file using object of ConfigParser.
    '''
    nominal = confP.getValue("device", "nominalTemp")
    '''
    constructor of class TempSensorAdaptorTask
    '''
    def __init__(self, name):
        # self.generateTemp()

        Thread.__init__(self)
        self.name = name
        self.temp = pu.getSensorDataFromDbms()

        self.act = pu.getActuatorDataFromDbms()
        # self.act=None
        if (self.temp == None):

            self.run()

    #  print(self.temp)
    '''
    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:
            self.val = self.sh.get_temperature(
            )  #calling get_temperature function
            j = {}
            #curVal=pu.getActuatorDataFromDbms()
            jj = pu.getActuatorDataFromDbms()
            if (len(self.act) < 20):
                pu.writeActuatorDataToDbms()
        #   print(jj)
            adl = ActuatorDataListener()
            c = adl.onActuatorMessage(self.temp)
            if (c != self.temp):
                self.temp = c
            self.sensorData.addValue(
                self.val)  #calling addValue function of sensorData
            # self.act_data=self.sensorDataM.handleSensorData(self.sensorData)
            self.getSensorData()
            sdj = self.du.toJsonFromSensorData(self.sensorData)
            print("**************")

            print(sdj)
            st = pu.writeSensorDataToDbms(self.sensorData)

            time.sleep(2)

    '''
    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='%(message)s')
        #    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. 23
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)
Esempio n. 24
0
'''
Created on 2018年9月15日

@author: howson
'''
import random
from time import sleep
import threading
from labs.common import SensorData
from labs.module02 import SmtpClientConnector

DEFAULT_RATE_IN_SEC = 10

Sens = SensorData.SensorData()
SmtpConnector = SmtpClientConnector.SmtpClientConnector()


class TempSensorEmulator(threading.Thread):
    enableEmulator = False
    isPrevTempSet = False
    rateInSec = DEFAULT_RATE_IN_SEC
    Sens.setName('Temperature')

    lowVal = 0
    highVal = 30
    alertDiff = 5

    def __init__(self, rateInSec=DEFAULT_RATE_IN_SEC):
        super(TempSensorEmulator, self).__init__()

        if rateInSec > 0:
                '/home/pi/workspace/iot-device/connected-devices-python/apps')
from labs.module02 import SmtpClientConnector
import time
import requests
import random
from sense_hat import SenseHat
import json

my_device = "raspberrypi"  # My Device label
my_temp_var = "temperature"  # My First variable label
my_humid_var = "humidity"  # My Second variable label
my_press_var = "pressure"  # My Third variable label
my_co_ordinates = "position"  # My Fourth Variable
my_auth_token = "YOUR PERSONAL AUTH TOKEN"  # My Auth TOKEN

conn = SmtpClientConnector.SmtpClientConnector()  # instance for SMTP client
"""Function to create the pay-load to send to cloud and returns the pay-load"""
"""@parameter: temp, humid, press and pos."""


def my_payload(temp, humid, press, pos):
    # Creates three variables for sending data
    instance = SenseHat()  # create a sense-hat instance
    result_temp = instance.get_temperature(
    )  # get temperature readings from sense-hat.
    result_humd = instance.get_humidity(
    )  # get humidity readings from sense-hat.
    result_press = instance.get_pressure(
    )  # get pressure readings from sense-hat.
    """Generate Random Co-Ordinates for Country - India"""
    lat = random.randrange(10, 26, 1) + random.randrange(1, 1000, 1) / 1000.0
Esempio n. 26
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)
Esempio n. 27
0
Created on Jan 21, 2019
@author: Suraj
'''

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
Esempio n. 28
0
import sys
sys.path.insert(0,
                '/home/pi/workspace/iot-device/connected-devices-python/apps')
import random
from sense_hat import SenseHat
from time import sleep
from threading import Thread
from labs.common import SensorData
from labs.module02 import SmtpClientConnector
from labs.module03 import TempActuatorEmulator
import labs.common.ConfigConst as configconst
from labs.common import ConfigUtil
from labs.common import ActuatorData
from awscli.customizations.emr.constants import TRUE

sen = SmtpClientConnector.SmtpClientConnector()

# red = (255, 0, 0)
blue = (255, 0, 0)


class allSensorAdaptor(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.flag = True
        self.rateInSec = 5

    def run(self):
        while True:
            if self.flag == True:
                sense = SenseHat()
class TempSensorAdaptor():
    sh          = None
    nominalaveragetemp = 0
    sensorid    = 1
    threshold   = 3 # NOTE: 2 or 3
    sleepcycle  = 0
    enableEmulator = False
    isPrevTempSet  = False
    

    
    connector = SmtpClientConnector.SmtpClientConnector()
    sensordata = SensorData.SensorData() 
    actuatordata = ActuatorData.ActuatorData()

    
    def __init__(self):
        self.sh = SenseHat()
        self.nominalaveragetemp = self.connector.nominalTemp
        self.sleepcycle = self.connector.pollCycleSecs
        self.enableEmulator = self.connector.enableEmulator
    
        
    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)
            
            
            
            
            
Esempio n. 30
0
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")
    
    '''
    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.currentValue,"temperature")
            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")