Exemple #1
0
 def __init__(self):
     self.actuator = ActuatorData()
     self.sensorAdaptor = MultiSensorAdaptor()
     self.config = ConfigUtil()
     self.config.loadConfig("../../../config/ConnectedDevicesConfig.props")
     self.threshold = float(self.config.getValue("device", "nominalTemp"))
     self.actuatorOP = MultiActuatorAdaptor.getInstance()
 def __init__(self):
     '''
     Constructor
     '''
     self.config = ConfigUtil()
     self.connector = SmtpClientConnector()
     self.tempActuator = TempActuatorAdaptor()
Exemple #3
0
 def __init__(self):
     self.config = ConfigUtil(
         r"/home/pi/workspace/iot-device/apps/labs/common/ConnectedDevicesConfig.props"
     )
     logging.info('Configuration data...\n' + '\n' +
                  str(self.config.config.sections())
                  )  # Constructor loading config properties from the file
class CoapServerConnector(CoAP):
    '''
    This is the implementation of the CoAP server.
    '''
    def __init__(self):
        '''
        This is the default constructor.
        It takes the host and port values and set them as CoAP server
        It adds the resources to server
        '''

        self.config = ConfigUtil()
        self.config.loadConfig()
        self.coapHost = self.config.getProperty(
            ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY)
        self.coapPort = int(
            self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                    ConfigConst.PORT_KEY))
        CoAP.__init__(self, (self.coapHost, self.coapPort))
        print(self.coapHost)
        print(self.coapPort)
        self.add_resource('temperature/', TempResourceHandler())

    def start(self):
        '''
        This function starts the server and opens the port to listen mode for
        clients to connect.
        On keyboard interrupt it would close the connection.
        '''

        try:
            self.listen(10)
        except KeyboardInterrupt:
            print("Server is being shutdown.")
            self.close()
 def __init__(self):
     """
     Class constructor which initializes all required parameters for connecting ubidots cloud service
     """
     logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
                         level=logging.INFO,
                         datefmt='%Y-%m-%d %H:%M:%S')
     threading.Thread.__init__(self)
     self.load_prop = ConfigUtil(
         r"/home/pi/workspace/iot-device/apps/labs/common/ConnectedDevicesConfig.props"
     )
     self.BROKER_ENDPOINT = self.load_prop.getValues(
         'ubidots.cloud', 'host')
     self.TLS_PORT = int(self.load_prop.getValues('ubidots.cloud', 'port'))
     self.MQTT_USERNAME = self.load_prop.getValues('ubidots.cloud',
                                                   'authToken')
     self.MQTT_PASSWORD = ""
     self.TOPIC = '/v1.6/devices/'
     self.DEVICE_LABEL = 'substation-gateway'
     self.TLS_CERT_PATH = self.load_prop.getValues('ubidots.cloud',
                                                   'certFile')
     logging.info("Configuring & Setting Up Cloud Connection Properties")
     mqtt_client.on_connect = on_connect
     self.connect(mqtt_client, self.MQTT_USERNAME, self.MQTT_PASSWORD,
                  self.BROKER_ENDPOINT, self.TLS_PORT)
Exemple #6
0
    def __init__(self, rateInSec=10):
        super(HI2CSensorAdaptorTask, self).__init__()

        self.rateInSec = rateInSec
        self.config = ConfigUtil()
        self.config.loadConfig(ConfigConst.DEFAULT_CONFIG_FILE_NAME)

        print('Configuration data...\n' +
              str(ConfigConst.DEFAULT_CONFIG_FILE_NAME))
Exemple #7
0
 def setUp(self):
     self.config = ConfigUtil()
     self.config.loadConfig('../../../config/ConnectedDevicesConfig.props')
     self.tempsensor = TempSensorEmulatorTask()
     self.sensordata = SensorData()
     self.sensordata.addValue(10)
     self.sensordata.addValue(15)
     self.sensordata.addValue(20)
     self.sensordata.setName('Temperature')
Exemple #8
0
 def __init__(self):  # Constructor
     threading.Thread.__init__(self)
     SensorDataManager.setDaemon(self, True)
     self.nominal_temp = ConfigUtil(
         r"/home/pi/workspace/iot-device/apps/labs/common/ConnectedDevicesConfig.props"
     )
     self.temp_set_point = self.nominal_temp.getValues(
         "device", "nominalTemp"
     )  # loading nominal temperature value from config file9
     self.message = ''
class SensorDataManager:
    #Default Constructor
    def __init__(self):
        self.actuator = ActuatorData()
        self.sensorAdaptor = MultiSensorAdaptor()
        self.config = ConfigUtil()
        self.config.loadConfig("../../../config/ConnectedDevicesConfig.props")
        self.threshold = float(self.config.getValue("device", "nominalTemp"))
        self.actuatorOP = MultiActuatorAdaptor.getInstance()

    def run(self):

        self.sensorAdaptor.getSensorData()

    #Method for evaluating the sensor values and create decision for actation
    def hadleSensorData(self, SensorData):
        self.actuator.max_value = SensorData.max_value
        self.actuator.min_value = SensorData.min_value
        self.actuator.readings_number = SensorData.readings_number
        self.actuator.value = SensorData.getCurrentValue()
        self.actuator.avgTemp = (SensorData.total_value /
                                 SensorData.readings_number)
        self.actuator.total_value = SensorData.total_value
        self.actuator.setName(SensorData.getName())
        self.actuatorOP.updateActuator(self.actuator)
        #print("Value check - " + str(self.actuator.value))
        self.sendNotification()
        return True

    #Triggering mail based on the command value. The mail contains the relevant information.
    def sendNotification(self):

        try:
            logging.info(self.actuator.getName() + "Temperature: \nTime: " +
                         str(self.actuator.timestamp) + " Value :" +
                         str(self.actuator.getValue()))
            mail = SmtpClientConnector()
            #Creating mail body text
            data = "Reading from:" + self.actuator.getName(
            ) + "\nTime: " + str(
                self.actuator.timestamp) + "\ncurrent : " + str(
                    self.actuator.getValue()) + "\nAverage :" + str(
                        self.actuator.getAverageValue()) + "\nSamples :" + str(
                            self.actuator.readings_number) + "\nMin: " + str(
                                self.actuator.min_value) + "\nMax :" + str(
                                    self.actuator.max_value)
            mail.publishMessage(
                "Humidity Alert Python -" + self.actuator.getName(), data)
            logging.info('\nMail sent')
            return True
        except Exception as e:
            logging.info(e)
            print(e)
            #If the mailing fails, the method returns false
            return False
    def __init__(self):
        '''
        Constructor
        '''
        self.config = ConfigUtil()
        self.config.loadConfig(
            'C:/Users/sk199/git/connected-devices-python/iot-device/config/ConnectedDevicesConfig.props'
        )

        logging.info('Configuration data...\n' +
                     str(ConfigConst.DEFAULT_CONFIG_FILE_NAME))
 def __init__(self):
     """
     Constructor function which loads all the essential propertied from disk for setting up SMTP Client using
     ConfigUtil Class Function
     """
     self.config = ConfigUtil(
         r"/home/pi/workspace/iot-device/apps/labs/common/ConnectedDevicesConfig.props"
     )
     logging.info('Configuration data...\n' + '\n' +
                  str(self.config.config.sections())
                  )  # Constructor loading config properties from the file
Exemple #12
0
 def setUp(self):
     self.config = ConfigUtil()
     self.config.loadConfig('../../../config/ConnectedDevicesConfig.props')
     self.tempsensor = TempSensorAdaptorTask()
     self.sensordata = SensorData()
     self.actuatordata = ActuatorData()
     self.sensordata.addValue(10)
     self.sensordata.addValue(15)
     self.sensordata.addValue(20)
     self.sensordata.addValue(25)
     self.sensordata.setName('Temperature')
     self.actuatordata.setCommand('Increasing')
     self.actuatordata.setName('SenseHat')
     self.sdmanager = SensorDataManager()
Exemple #13
0
class smtpconnect():
    msgBody = ''
    fromAddr = ''
    toAddr = ''
    host = ''

    def __init__(self):
        self.config = ConfigUtil(
            r"/home/pi/workspace/iot-device/apps/labs/common/ConnectedDevicesConfig.props"
        )
        logging.info('Configuration data...\n' + '\n' +
                     str(self.config.config.sections())
                     )  # Constructor loading config properties from the file

    def publishMessage(self, topic, data):  # Publishing Mail Via SMTP
        self.host = self.config.getValues("smtp.cloud", "host")
        port = self.config.getValues("smtp.cloud", "port")
        self.fromAddr = self.config.getValues("smtp.cloud", "fromAddr")
        self.toAddr = self.config.getValues("smtp.cloud", "toAddr")
        authToken = self.config.getValues("smtp.cloud", "authToken")

        msg = MIMEMultipart()
        msg['From'] = self.fromAddr
        msg['To'] = self.toAddr
        msg['Subject'] = topic
        self.msgBody = " Present Status!!! " + str(data)
        msg.attach(MIMEText(self.msgBody, "plain"))

        # send e-mail notification
        smtpServer = smtplib.SMTP_SSL(self.host, port)  # Creating SMTP server
        smtpServer.ehlo()
        smtpServer.login(self.fromAddr, authToken)  # Authentication
        msgText = msg.as_string()  # Converting to String
        smtpServer.sendmail(self.fromAddr, self.toAddr, msgText)  # Send Mail
        logging.info("\n Successfully mailed alert from address " +
                     self.fromAddr)
        smtpServer.close()

    def getfromAddr(self):
        return self.fromAddr

    def gettoAddr(self):
        return self.toAddr

    def getmsgBody(self):
        return self.msgBody

    def getHost(self):
        return self.host
    def setUp(self):

        #getting the host data
        host = ConfigUtil().getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                        ConfigConst.HOST_KEY)

        #port number to connect
        port = int(ConfigUtil().getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                            ConfigConst.PORT_KEY))

        #resource uri
        path = 'Temperature Resource'

        #connecting to my CoAp client connector
        self.coap_client = CoapClientConnector(host, port, path)
Exemple #15
0
 def __init__(self):
     Thread.__init__(self)
     self.highVal = 30
     self.lowVal = 0
     self.updateTime = 2
     self.senseHat = SenseHat()
     self.sensorData = SensorData()
     self.actuatorData = ActuatorData()
     self.connector = Connector()
     self.alertDiff = 10
     
     
     self.config = ConfigUtil('D:/git/repository/iot-device/apps/data/ConnectedDevicesConfig.props')
     self.config.loadConfig()
     print('Configuration data...\n' + str(self.config))
Exemple #16
0
class SensorDataManager():
    actData = ActuatorData()
    nomTemp = 0
    confP = ConfigUtil()
    '''
    this function takes sensorData as an argument and updates the ActuatorData object with the values and 
    returns the ActuatorData object.
    '''
    def handleSensorData(self, sensorData):
        self.actData.setName(sensorData.getName())
        self.actData.setValue(sensorData.getCurrentValue())
        self.nomTemp = float(self.confP.getValue("device", "nominalTemp"))
        if ((self.nomTemp - 5.0) < sensorData.getCurrentValue() <
            (self.nomTemp + 5.0)):
            self.actData.setCommand("NEUTRAL")
        elif (sensorData.getCurrentValue() < (self.nomTemp + 10.0)):
            self.actData.setCommand("TEMP DEC")
        elif (sensorData.getCurrentValue() > (self.nomTemp + 10.0)):
            self.actData.setCommand("TEMP INC")
    # print(self.actData.getCommand())
        return self.actData

    #return None

    def humidity(self, sensorData):
        self.actData.setName(sensorData.getName())
        self.actData.setValue(sensorData.getCurrentValue())
        self.actData.setCommand(str(round(sensorData.getCurrentValue(), 2)))
        return self.actData

    def pressure(self, sensorData):
        self.actData.setName(sensorData.getName())
        self.actData.setValue(sensorData.getCurrentValue())
        self.actData.setCommand(str(round(sensorData.getCurrentValue(), 2)))
        return self.actData
Exemple #17
0
class Module03Test(unittest.TestCase):
	confU=ConfigUtil();
	sensorD=SensorData()
	hasConf=confU.hasConfig()
	curVal=sensorD.getCurrentValue()
	avgVal=sensorD.getAverageValue()
	actD=ActuatorData()
	senDM=SensorDataManager()
	
	"""
	it checks for the datatype of hasConf to be boolean, If true test case is passed.
	"""

	def testConfigUtil(self):
		self.assertTrue(isinstance(self.hasConf,bool),"Boolean Value")
		
	"""
	it checks for the datatype of curVal to be float, If true test case is passed. 
	Second checks for the avgVal to be within the specified range.If true test case is passed. 
	"""	
	def testSensorData(self):
		self.assertTrue(isinstance(self.curVal,float),"Float Value")
		self.assertTrue(self.avgVal>=0.0 and self.avgVal<=30.0,"Average Temperature within the range")
	'''
	It checks for the datatype of the getCommand function to be String.
	'''	
	def testActuatorData(self):
		self.assertTrue(isinstance(self.actD.getCommand(),str), "String")
		
	'''
	It checks for the returntype of the function handleSensorData of class SensorDataManager to be of type actuator data. 
	'''	
	def testSensorDataManager(self):
		self.assertTrue(isinstance(self.senDM.handleSensorData(self.sensorD),ActuatorData), "Type Actuator Data")		
class SensorDataManager(object):
    '''
    classdocs
    '''   
    actuatorData = ActuatorData()
    

    def __init__(self):
        '''
        Constructor
        '''
        self.config = ConfigUtil()
        self.connector = SmtpClientConnector()
        self.tempActuator = TempActuatorAdaptor()
        
    '''
    If current temperature exceeds or falls below the 'nominalTemp', the new SensorData instance will trigger an actuation
    It will return the new ActualatorData instance with the appropriate data value and command embedded;
    Otherwise, it returns None
    Also,if an actuation is triggered, the SmtpClientConnector instance will be created to send the e-mail 
    message to the appropriate destination    
    '''
        
    def handleSensorData(self,sensorData):
        self.nominalTemp = float(self.config.getValue(ConfigConst.DEVICE, ConfigConst.NOMINAL_TEMP))
        self.time       = sensorData.timeStamp                                     
        self.average    = sensorData.avgValue
        self.samples    = sensorData.getCount()
        self.min        = sensorData.minValue
        self.max        = sensorData.maxValue 
        self.message    = 'Temperature\n' + '\tTime: ' +str(self.time) + '\n\tCurrent: ' + str(sensorData.curValue) + '\n\tAverage: ' +str(self.average) + '\n\tSamples: ' + str(self.samples) + '\n\tMin: ' + str(self.min) + '\n\tMax: ' + str(self.max)
        
        if(sensorData.curValue>self.nominalTemp):
            
            logging.info('\nCurrent temperature exceeds nonminalTemp by > ' +str(self.nominalTemp) + '. Triggering alert...')
            #print('\nCurrent temperature exceeds nonminalTemp by > ' +str(self.nominalTemp) + '. Triggering alert...')      
            
            self.connector.publishMessage('Excessive Temperature', self.message)
            self.actuatorData.setCommand('Increasing')
            self.actuatorData.getValue(sensorData.curValue)
            self.tempActuator.updateActuator(self.actuatorData)
            print(self.message)
            return(self.actuatorData)
            
            
        elif(sensorData.curValue<self.nominalTemp):
            
            logging.info('\nCurrent temperature falls below nonminalTemp by < ' +str(self.nominalTemp) + '. Triggering alert...')                                     
             
            self.connector.publishMessage('Decreasing Temperature', self.message)
            self.actuatorData.setCommand('Decreasing')
            self.actuatorData.getValue(sensorData.curValue)
            self.tempActuator.updateActuator(self.actuatorData)
            print(self.message)
            return(self.actuatorData)
        
        else:
            return(None)
            
Exemple #19
0
class SmtpClientConnector():
    def __init__(self):
        self.config = ConfigUtil()

    def publishMessage(self, topic, data):

        self.config.loadConfig()
        ''' getting data from ConfigConst '''
        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)
        '''to give data in message'''
        msg = MIMEMultipart()
        msg['From'] = fromAddr
        msg['To'] = toAddr
        msg['subject'] = topic
        msgBody = str(data)
        msg.attach(MIMEText(msgBody))

        msgText = msg.as_string()
        '''send e-mail notification'''
        server = smtplib.SMTP_SSL(host, port)
        server.ehlo()
        server.login(fromAddr, authToken)
        server.sendmail(fromAddr, toAddr, msgText)

        server.close()
    def __init__(self):
        '''
        This is the default constructor.
        It takes the host and port values and set them as CoAP server
        It adds the resources to server
        '''

        self.config = ConfigUtil()
        self.config.loadConfig()
        self.coapHost = self.config.getProperty(
            ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY)
        self.coapPort = int(
            self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                    ConfigConst.PORT_KEY))
        CoAP.__init__(self, (self.coapHost, self.coapPort))
        print(self.coapHost)
        print(self.coapPort)
        self.add_resource('temperature/', TempResourceHandler())
Exemple #21
0
class Module02Test(unittest.TestCase):
    """
	class scoped variables and objects are created
	"""
    confU = ConfigUtil()
    sensorD = SensorData()
    tempSensor = TempSensorEmulatorTask()
    curVal = 0.0
    avgVal = 0.0
    hasConf = ""
    data = None
    '''
	values are setup into the variables
	 '''
    def setUp(self):
        self.data = self.tempSensor.getSensorData()
        self.hasConf = self.confU.hasConfig()
        self.curVal = self.sensorD.getCurrentValue()
        self.avgVal = self.sensorD.getAverageValue()

    """
	All the resources are tear down here.
	"""

    def tearDown(self):
        del self.data
        del self.hasConf
        del self.curVal
        del self.avgVal

    """
	it checks for the datatype of hasConf to be boolean, If true test case is passed.
	"""

    def testConfigUtil(self):
        self.assertTrue(isinstance(self.hasConf, bool), "Boolean Value")

    """
	it checks for the datatype of curVal to be float, If true test case is passed. 
	Second checks for the avgVal to be within the specified range.If true test case is passed. 
	"""

    def testSensorData(self):
        self.assertTrue(isinstance(self.curVal, float), "Float Value")
        self.assertTrue(self.avgVal >= 0.0 and self.avgVal <= 30.0,
                        "Average Temperature within the range")

    '''
	It checks for the datatype of data to be of class type SensorData, If true test case is passed.
	'''

    def testTemperatureSensorEmulatorTask(self):
        self.assertTrue(isinstance(self.data, SensorData),
                        "Sensor Data Type Value")
class SmtpClientConnector:
    
    def __init__(self):
        self.config = ConfigUtil()
        self.config.loadConfig("../../../config/ConnectedDevicesConfig.props")
    #method to create and send a mail
    def publishMessage(self, topic, data):
        host = self.config.getValue("smtp.cloud", "host")
        port = self.config.getValue("smtp.cloud", "port")
        fromAddr = self.config.getValue("smtp.cloud", "fromAddr")
        toAddr = self.config.getValue("smtp.cloud", "toAddr")
        authToken = self.config.getValue("smtp.cloud", "authToken")
        #Generating mail body
        msg =MIMEMultipart()
        msg['From'] = fromAddr
        msg['To'] = toAddr
        msg['Subject'] = topic
        body = str(data)
        msg.attach(MIMEText(body, 'plain'))
        msgText = msg.as_string()

        # send e-mail notification
        smtpServer = SMTP_SSL(host, port)
        smtpServer.ehlo()
        smtpServer.login(fromAddr, authToken)
        smtpServer.sendmail(fromAddr, toAddr, msgText)
        smtpServer.close()
        return True
Exemple #23
0
 def __init__(self):
     config = ConfigUtil()
     config.loadConfig("../../../config/ConnectedDevicesConfig.props")
     self.host = config.getValue("coap.device", "host")
     self.port = int(config.getValue("coap.device", "port"))
     self.path = "Temp"
     self.client = HelperClient(server=(self.host, self.port))
Exemple #24
0
    def __init__(self):
        self.config = ConfigUtil(
            '../../../config/ConnectedDevicesConfig.props')
        self.config.loadConfig()
        print('Configuration data...\n' + str(self.config))

        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))
        print('\tHost: ' + self.host)
        print('\tPort: ' + str(self.port))

        if not self.host or self.host.isspace():
            print("Using default host: " + self.host)

        self.serverAddr = (self.host, self.port)
        print('Server Address: ' + str(self.serverAddr))

        self.url = "coap://" + self.host + ":" + str(
            self.port) + "/Temperature"
    def connector(self, command):
        confUtil = ConfigUtil()
        if (command == "TEMP INC"):

            msg = "Current temperature value exceeds the nominal temperature value."
        elif (command == "TEMP DEC"):
            msg = "Current temperature value deceeds the nominal temperature value."
        else:
            msg = "Current temperature value neutral to the nominal temperature value."
        sub = "Temperature Alert"
        message = 'Subject: {}\n\n{}'.format(sub, msg)
        dictS = confUtil.dictSmtp()
        senderAddr = dictS['senderAddr']
        receiverAddr = dictS['receiverAddr']
        hostName = dictS['hostName']
        portNumber = dictS['portNumber']
        token = dictS['token']
        server = smtplib.SMTP(hostName, portNumber)
        server.starttls()
        server.login(senderAddr, token)
        server.ehlo()
        server.sendmail(senderAddr, receiverAddr, message)
Exemple #26
0
class SmtpClientConnector():
    def __init__(self):
        self.config = ConfigUtil(
            'D:/git/repository/iot-device/data/ConnectedDevicesConfig.props')
        self.config.loadConfig()
        print('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)
        msg = MIMEMultipart()
        msg['From'] = fromAddr
        msg['To'] = toAddr
        msg['Subject'] = topic
        msgBody = str(data)
        msg.attach(MIMEText(msgBody))
        msgText = msg.as_string()
        # send e-mail notification
        smtpServer = smtplib.SMTP_SSL(host, port)
        smtpServer.ehlo()
        smtpServer.login(fromAddr, authToken)
        smtpServer.sendmail(fromAddr, toAddr, msgText)
        smtpServer.close()

    def sendEmailMessage(self, topic, message):
        for destinAddr in self.destinAddr:

            msg = MIMEText(str(message))
            msg["From"] = self.sourceAddr
            msg["to"] = destinAddr
            msg["Subject"] = topic

            try:
                mailServer = smtplib.SMTP_SSL(self.host, self.port)
                mailServer.ehlo()
                mailServer.login(self.sourceAddr, self.passphrase)
                mailServer.send_message(msg, self.sourceAddr, destinAddr)
                mailServer.close()
                print("Sent successfully to " + destinAddr)
            except Exception as e:
                print("Failed to send email\n" + e)

    def printInfo(self):
        print("host:" + self.host + "\nport:" + str(self.port) +
              "\nFromAddr:" + self.sourceAddr + "\ntoAddr:" + self.destinAddr +
              "\n" + "authToken:" + self.passphrase)
Exemple #27
0
class DeviceDataManager:
    #Default Constructor
    def __init__(self):
        self.actuator = ActuatorData()
        self.sensorAdaptor = MultiSensorAdaptor()
        self.config = ConfigUtil()
        self.config.loadConfig("../../../config/ConnectedDevicesConfig.props")
        self.threshold = float(self.config.getValue("device", "nominalTemp"))
        self.actuatorOP = MultiActuatorAdaptor.getInstance()
#Creating multiThreaded environment

    def run(self):
        t1 = Thread(target=self.sensorAdaptor.getSensorData)
        #logging.info("Running t1")
        t2 = Thread(target=self.actuatorOP.runListener)
        t1.start()
        t2.start()

        #self.sensorAdaptor.getSensorData()

    #Method for evaluating the sensor values and create decision for actation
    def handleActuatorData(self, SensorData):
        self.actuator.max_value = SensorData.max_value
        self.actuator.min_value = SensorData.min_value
        self.actuator.readings_number = SensorData.readings_number
        self.actuator.value = SensorData.getCurrentValue()
        self.actuator.avgTemp = (SensorData.total_value /
                                 SensorData.readings_number)
        self.actuator.total_value = SensorData.total_value
        self.actuator.setName(SensorData.getName())
        self.actuatorOP.updateActuator(self.actuator)
        #print("Value check - " + str(self.actuator.value))
        #self.sendNotification()
        return True

    def handleSensorData(self, SensorData):
        pu = PersistenceUtil()
        pu.writeSensorToDataDbms(SensorData)
class SmtpClientConnector(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.config = ConfigUtil()
        self.config.loadConfig(
            'C:/Users/sk199/git/connected-devices-python/iot-device/config/ConnectedDevicesConfig.props'
        )

        logging.info('Configuration data...\n' +
                     str(ConfigConst.DEFAULT_CONFIG_FILE_NAME))

    '''   
    configured via the data stored in ConfigUtil    
    implement an SMTP, sending sensor data to a remote email account
    '''

    def publishMessage(self, topic, data):
        host = self.config.getValue(ConfigConst.SMTP_CLOUD_SECTION,
                                    ConfigConst.HOST_KEY)
        port = self.config.getValue(ConfigConst.SMTP_CLOUD_SECTION,
                                    ConfigConst.PORT_KEY)
        fromAddr = self.config.getValue(ConfigConst.SMTP_CLOUD_SECTION,
                                        ConfigConst.FROM_ADDRESS_KEY)
        toAddr = self.config.getValue(ConfigConst.SMTP_CLOUD_SECTION,
                                      ConfigConst.TO_ADDRESS_KEY)
        authToken = self.config.getValue(ConfigConst.SMTP_CLOUD_SECTION,
                                         ConfigConst.USER_AUTH_TOKEN_KEY)

        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()
Exemple #29
0
 def __init__(self):
     self.mqttc = mqtt.Client()
     self.config = ConfigUtil()
     self.config.loadConfig("../../config/ConnectedDevicesConfig.props")
Exemple #30
0
class MqttClientConnector:
    mqttc = None  # MQTT client Property

    def __init__(self):
        self.mqttc = mqtt.Client()
        self.config = ConfigUtil()
        self.config.loadConfig("../../config/ConnectedDevicesConfig.props")

    # Callback function for connect
    def on_connect(self, mqttc, obj, flags, rc):
        logging.info("Connected to broker")
        return True

    # Callback function for disconnect
    def on_disconnect(self, mqttc, obj, flags, rc):
        logging.info("disconnected to broker")
        return True

    # Callback function for message arrival
    def on_message(self, mqttc, obj, msg):
        logging.info(msg.topic + " Actuator Value changed to " +
                     msg.payload.decode("utf-8"))
        self.ard = ArduinoManager.getInstance()
        self.ard.servoCommand()

    # Callback function for publish
    def on_publish(self, mqttc, obj, mid):
        logging.info("mid: " + str(mid))

    # Callback function for  subscribe
    def on_subscribe(self, mqttc, obj, mid, granted_qos):
        logging.info("Subscribed: ActuatorData/change ")

    # Callback function for logging
    def on_log(self, mqttc, obj, level, string):
        logging.info(string)

    # Method for establishing subscribe MQTT connection
    def subscribeMqtt(self):
        host = self.config.getValue("mqtt.gateway", "host")
        port = 1883  #self.config.getValue("mqtt.gateway", "port")
        self.mqttc.on_message = self.on_message
        self.mqttc.on_connect = self.on_connect
        self.mqttc.on_publish = self.on_publish
        self.mqttc.on_subscribe = self.on_subscribe
        self.mqttc.connect(host, port, 60)
        self.mqttc.subscribe("project/constraint/actuator", 1)
        self.mqttc.loop_forever()

    # Method for publishing mqtt client
    def publishMqtt(self, message):
        host = self.config.getValue("mqtt.gateway", "host")
        port = 1883
        self.mqttc.on_message = self.on_message
        self.mqttc.on_connect = self.on_connect
        self.mqttc.on_publish = self.on_publish
        self.mqttc.on_subscribe = self.on_subscribe
        self.mqttc.connect(host, port, 60)
        self.mqttc.publish("project/constraint/sensor", message, 1)
        # Method for disconnecting the client
    def clientConnect(self):
        host = self.config.getValue("mqtt.gateway", "host")
        port = 1883
        self.mqttc.on_message = self.on_message
        self.mqttc.on_connect = self.on_connect
        self.mqttc.on_publish = self.on_publish
        self.mqttc.on_subscribe = self.on_subscribe
        self.mqttc.connect(host, port, 60)
        return True

    # Method for disconnecting the client
    def clientDisconnect(self):
        self.mqttc.disconnect(None, None)
        return True