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 (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)
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)
def __init__(self): ''' Constructor which initializes the sensor object and the SMTPCLient object ''' self.sensor = SensorData.SensorData() self.SmtpClient = SmtpClientConnector.MyClass()
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)
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();
def setUp(self): #Get a SMTPclient instance self.SmtpTest = SmtpClientConnector.MyClass() #Get a TempSensorEmulator instance self.EmulatorTest = TempSensorEmulatorTask.TempSensorEmulator() #Get a TempEmulatorAdapter instance self.Emulation = TempEmulatorAdapter.TempEmulatorAdapter() pass
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()
def run(self): while True: if self.enableEmulator: self.curTemp = uniform(float(self.lowVal), float(self.highVal)) SenDat.addValue(self.curTemp) print('\n------------') print('Sensor reading:') print(' ' + str(self.curTemp)) if self.PrevTempSet == False: self.prevTempS = self.curTemp self.PrevTempS = True else: print(SenDat.__str__()) print('CurTemp - AvgValue =' + str(abs(self.curTemp - SenDat.getAvgValue()))) print('Threshold =' + str(self.alertDiff)) if (abs(self.curTemp - SenDat.getAvgValue()) >= self.alertDiff): print('The Current temperature exceeds average by >' + str(self.alertDiff) + 'TriggeringAlert...') self.sensorData = SenDat.__str__() SmtpClientConnector.publishMessage('Exceptional Sensor Data', self.sensorData) sleep(self.rateInSec)
def __init__(self): ''' Constructor ''' #Creating a configUtil instance and loading the configUtil file self.config = ConfigUtil.ConfigUtil() self.config.loadConfigData() #Creating an actuatorData instance to store Actuator state in, and setting it's name. self.actuator = ActuatorData.ActuatorData() self.actuator.setName("Temperature Actuator Data") #Creating an actuatorAdapter to actuate the actual actuator. self.actuatorAdapter = MultiActuatorAdapter.MultiActuatorAdapter() #SMTP-connector to send Emails self.smtpConnector = SmtpClientConnector.MyClass()
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)
def __init__(self): ''' Constructor ''' #Creating a configUtil instance and loading the configUtil file self.config = ConfigUtil.ConfigUtil() self.config.loadConfigData() #Reading the required nominal temperature from the config file and logging it self.nominal = self.config.getIntegerValue("device", "nominalTemp") logging.info( str("Read nominal temperature from config " + str(self.nominal))) #Creating an actuatorData instance to store Actuator state in, and setting it's name. self.actuator = ActuatorData.ActuatorData() self.actuator.setName("Temperature Actuator Data") #Creating an actuatorAdapter to actuate the actual actuator. self.actuatorAdapter = TempActuatorAdapter.TempActuatorAdapter() #SMTP-connector to send Emails self.smtpConnector = SmtpClientConnector.MyClass()
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)
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)
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)
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)
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)
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)
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
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)
''' 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:
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()