class I2CSenseHatAdaptor(threading.Thread): rateInSec = DEFAULT_RATE_IN_SEC humidity = 0.0 def __init__(self): super(I2CSenseHatAdaptor, self).__init__() self.config = ConfigUtil(ConfigConst.DEFAULT_CONFIG_FILE_NAME) self.config.loadConfig() print('Configuration data...\n' + str(self.config)) self.initI2CBus() def initI2CBus(self): logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) logging.info("Initializing I2C bus and enabling I2C addresses...") # i2cBus.write_byte_data(accelAddr, 0, 0) # i2cBus.write_byte_data(magAddr, 0, 0) # i2cBus.write_byte_data(pressAddr, 0, 0) # Select average configuration register i2cBus.write_byte_data(humidAddr, 0, 0) def displayHumidityData(self): # Humidity Calibration values #Read data back from 0x30(48), 1 byte val1 = i2cBus.read_byte_data(0x5f, 0x30) H0_rH = val1 /2 # Read data back from 0x31(49), 1 byte val2 = i2cBus.read_byte_data(0x5f, 0x31) H1_rH= val2 /2 # Read data back from 0x36(54), 2 bytes val3 = i2cBus.read_byte_data(0x5f, 0x36) val4 = i2cBus.read_byte_data(0x5f, 0x37) H0_T0_OUT = ((val4 & 0xFF) * 256) + (val3 & 0xFF) # Read data back from 0x3A(58), 2 bytes val5 = i2cBus.read_byte_data(0x5F, 0x3A) val6 = i2cBus.read_byte_data(0x5F, 0x3B) H1_T0_OUT = ((val6 & 0xFF) * 256) + (val5 & 0xFF) # Read data back from 0x28,0x29: humidity msb, humidity lsb val7 = i2cBus.read_byte_data(0x5F, 0x28) val8 = i2cBus.read_byte_data(0x5F, 0x29) H_OUT = ((val8 & 0xFF) * 256) + (val7 & 0xFF) # Read data back from 0x28(40) with command register 0x80(128), 6 bytes data = i2cBus.read_i2c_block_data(0x5f, 0x28 | 0x80, 6) #Convert to human-readable data self.humidity = ((1.0 * H1_rH) - (1.0 * H0_rH)) * ((1.0 * H_OUT) - (1.0 * H0_T0_OUT)) / ((1.0 * H1_T0_OUT) - (1.0 * H0_T0_OUT)) + (1.0 * H0_rH) # logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) d1 = 'Relative Humidity: ' + str(self.humidity) d2 = 'Relative Humidity block data: ' + str(data) logging.info(d1) logging.info(d2) def run(self): while True: # NOTE: you must implement these methods # self.displayAccelerometerData() # self.displayMagnetometerData() # self.displayPressureData() self.displayHumidityData() sleep(self.rateInSec)
def __init__(self): ''' Constructor ''' self.config = ConfigUtil( '../../../config/ConnectedDevicesConfig.props') # self.config = ConfigUtil('/Users/apple/workspace/iot-device/config/ConnectedDevicesConfig.props') self.config.loadConfig() logging.info('Configuration data...\n' + str(self.config))
def __init__(self): self.path = "" self.config = ConfigUtil( '../../../config/ConnectedDevicesConfig.props') self.host = self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY) self.port = int( self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.PORT_KEY)) CoAP.__init__(self, (self.host, self.port))
def __init__(self): ''' configure the remote server to send alert email; whenever an email is sent, log out the success message ''' self.config = ConfigUtil( '../../../config/ConnectedDevicesConfig.props') # self.config = ConfigUtil('/Users/apple/workspace/iot-device/config/ConnectedDevicesConfig.props') self.config.loadConfig() logging.info('Configuration data...\n' + str(self.config))
def sendemailmethod(self, topic, data): config = ConfigUtil() print(config.loadconfig()) logging.info('Configuration data...\n') host = config.getSMTPhost() print(host) port = config.getSMTPport() print(port) fromAddr = config.getSMTPfromAddr() toAddr = config.getSMTPtoAddr() password = config.getpassword() msg = MIMEMultipart() msg['From'] = fromAddr msg['To'] = toAddr msg['Subject'] = str("\n" + topic + "\n") msgBody = str("\n" + data + "\n") msg.attach(MIMEText(msgBody)) #msgText = msg.as_string() #Return the entire message flattened as a string. # send e-mail notification """ start smtp server sending instance to send the message """ smtpServer = smtplib.SMTP(host, port) # smtpServer.set_debuglevel(True) #set true for debbuging process smtpServer.ehlo() smtpServer.starttls() smtpServer.login(fromAddr, password) smtpServer.ehlo() smtpServer.sendmail(fromAddr, toAddr, msgBody) smtpServer.close()
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 manager(self,sensorvalues): # print("entered manager") avg=sensorvalues.getterAvg() #print(avg) current_val= sensorvalues.gettercurrent() count= sensorvalues.getterCount() max= sensorvalues.getterMax() self.setteravg(avg) self.settercurrent(current_val) """ get nominal temp from confg file """ nominalTemp=int(ConfigUtil().getvalue("device", "nominalTemp")) min= sensorvalues.getterMin() formatstring="Temperature:\n\tTime: "+str(datetime.now().isoformat())+"\n\tCurrent: "+str(current_val)+"\n\tAverage: "+str(avg)+"\n\tSamples : 10\n\tMin: "+str(min)+"\n\tMAX :"+str(max) time.sleep(0.8) #print(formatstring) topic="ALert : Sudden Temperature increase above threshold" #print(topic) a=PersistenceUtil() id_var= uuid.UUID().hex() a.writeSensorDataToDB(sensorvalues, id_var) a.writeSensorToPubSub(id_var)
class SmtpClientConnector(object): ''' configure the remote server to send alert email; whenever an email is sent, log out the success message ''' def __init__(self): ''' Constructor ''' self.config = ConfigUtil( '../../../config/ConnectedDevicesConfig.props') # self.config = ConfigUtil('/Users/apple/workspace/iot-device/config/ConnectedDevicesConfig.props') self.config.loadConfig() logging.info('Configuration data...\n' + str(self.config)) def publishMessage(self, topic, data): host = self.config.getProperty(ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.HOST_KEY) port = self.config.getProperty(ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.PORT_KEY) fromAddr = self.config.getProperty(ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.FROM_ADDRESS_KEY) toAddr = self.config.getProperty(ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.TO_ADDRESS_KEY) authToken = self.config.getProperty(ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.USER_AUTH_TOKEN_KEY) # nominalTemp = self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE, 'nominalTemp') # if(SensorData.getValue()): # actuate = ActuatorData() msg = MIMEMultipart() msg['From'] = fromAddr msg['To'] = toAddr msg['Subject'] = topic msgBody = str(data) msg.attach(MIMEText(msgBody)) msgText = msg.as_string() smtpServer = smtplib.SMTP_SSL(host, port) smtpServer.ehlo() smtpServer.login(fromAddr, authToken) smtpServer.sendmail(fromAddr, toAddr, msgText) smtpServer.close() logging.info('Sending Successful!\n\n')
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)
def manager(self,sensorvalues): # print("entered manager") avg=sensorvalues.getterAvg() #print(avg) current_val= sensorvalues.gettercurrent() count= sensorvalues.getterCount() max= sensorvalues.getterMax() self.setteravg(avg) self.settercurrent(current_val) """ get nominal temp from confg file """ nominalTemp=int(ConfigUtil().getvalue("device", "nominalTemp")) min= sensorvalues.getterMin() formatstring="Temperature:\n\tTime: "+str(datetime.now().isoformat())+"\n\tCurrent: "+str(current_val)+"\n\tAverage: "+str(avg)+"\n\tSamples : 10\n\tMin: "+str(min)+"\n\tMAX :"+str(max) time.sleep(0.8) #print(formatstring) topic="ALert : Sudden Temperature increase above threshold" #print(topic) """ check if email is to be sent using avg values """ if(abs(avg-current_val)>3): email=SMTPemailclass() # print(sensorvalues.getterAvg()) data=formatstring #"The temperature has suddenly changed to high percent value from average "+str(avg)+"to a sudden change of "+str(current)+"This is an auto generated email" email.sendemailmethod(topic, data) """ check if actuator is needed incase temp decreases """ elif(current_val < nominalTemp): # print(sensorvalues.getterAvg()) """ actuation on sensehat set command """ latest_actuator= ActuatorData("increase", avg, "temperature") print("set increase command") recent_command=latest_actuator.getcommand() print("enter led") TempActuatorAdaptor.ledActuator(self, recent_command,avg) print("email sent") """ check if actuator is needed incase temp increases """ elif(current_val > nominalTemp): """ actuation on sensehat set command """ latest_actuator= ActuatorData("decrease", avg, "temperature") print("set decrease command") recent_command=latest_actuator.getcommand() print("enter led") TempActuatorAdaptor.ledActuator(self, recent_command,avg)
def __init__(self): super(I2CSenseHatAdaptor, self).__init__() self.config = ConfigUtil(ConfigConst.DEFAULT_CONFIG_FILE_NAME) self.config.loadConfig() print('Configuration data...\n' + str(self.config)) self.initI2CBus()
def setUp(self): self.configUtil = ConfigUtil() self.configUtil.loadConfig() pass
class ConfigUtilTest(unittest.TestCase): """ Placeholder function for setup process. Not needed for this test. """ def setUp(self): self.configUtil = ConfigUtil() self.configUtil.loadConfig() pass """ Placeholder function for tear down process. Not needed for this test. """ def tearDown(self): pass """ Tests retrieval of a boolean property. """ def testGetBooleanProperty(self): # TODO: implement this pass """ Tests retrieval of an integer property. """ def testGetIntegerProperty(self): # TODO: implement this pass """ Tests retrieval of a string property. """ def testGetProperty(self): # TODO: implement this pass """ Tests if a property exists. """ def testHasProperty(self): # TODO: implement this pass """ Tests if a section exists. """ def testHasSection(self): # TODO: implement this pass """ Tests if the configuration is loaded. """ def testIsConfigDataLoaded(self): if self.configUtil.isConfigDataLoaded(): pass else: self.fail("Configuration data not loaded.")
''' Created on 14-Mar-2020 @author:aman shah ''' from labs.module07.CoapClientConnector import CoapClientConnector from labbenchstudios.common.DataUtil import DataUtil from labbenchstudios.common.ConfigUtil import ConfigUtil from labbenchstudios.common.SensorData import SensorData '''initialize variable for ConfigUtil class''' config = ConfigUtil() '''initialise variable for DataUtil class''' data = DataUtil() #ip/ or hostname direct host = '127.0.0.1' #config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY) #port number initialized port = 5683 #int(config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.PORT_KEY)) #equivalent to channel in mqtt path = 'temperature' #instance variable for SensorData class sensorData = SensorData() #add new sensordata value sensorData.addvalue(20.00) #call the Coapclient connector coapClient_obj = CoapClientConnector(host, port, path) '''ping request''' coapClient_obj.ping() '''get request''' coapClient_obj.get()
''' Created on Mar 19, 2019 @author: GANESHRAM KANAKSABAI ''' from labs.module07.CoapServerConnector import CoapServerConnector # importing CoapServerConnector from labbenchstudios.common.ConfigUtil import ConfigUtil # importing ConfigUtil from labbenchstudios.common import ConfigConst # importing ConfigConst config = ConfigUtil('../data/ConnectedDevicesConfig.props') config.loadConfig() host = config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY) port = int( config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.PORT_KEY)) server = CoapServerConnector(host, port, config) server.start() # starting the action of the server