Пример #1
0
 def __init__(self):
     '''
     Constructor
     '''
     #start the Dbms listener from PersistenceUtil
     self.pUtil = PersistenceUtil()
     self.pUtil.registerActuatorDataDbmsListener()
 def run(self):    
     while TempSensorAdaptorTask.isDaemon(self):    
         time.sleep(6)
         environment_temperature = self.getSensorData()
         data_object.addValue(environment_temperature)  # Logging sensor data
         sensor_obj = PersistenceUtil(data_object)
         
         self.max_sample -= 1                    
         if self.max_sample == 0:
             return 0
Пример #3
0
class MultiSensorAdaptor():
    '''
    classdocs
    '''

    #initialize TempSensorAdaptorTask
    tempSensorAdaptorTask = TempSensorAdaptorTask()

    def __init__(self):
        '''
        Constructor
        '''
        #start the Dbms listener from PersistenceUtil
        self.pUtil = PersistenceUtil()
        self.pUtil.registerActuatorDataDbmsListener()

    #method for creating and running the thread
    def run(self):

        #log the initial message
        logging.info("Starting getTemperature thread()")

        #try the running thread
        try:

            #enable the temperature fetcher
            self.tempSensorAdaptorTask.enableFetcher = True

            #create the thread that calls the getTemperature() method of the tempSensorAdaptorTask
            threadTempSensorAdaptor = threading.Thread(
                target=self.tempSensorAdaptorTask.getTemperature())

            #set the temp sensor adaptor daemon to true (enable main thread to exit when done)
            threadTempSensorAdaptor.daemon = True

        #if found error
        except:

            #return false
            return False

        #return true for running successfully
        return True
Пример #4
0
class SensorDataManager(object):

    actuator = ActuatorData.ActuatorData()
    connector = SMTPClientConnector.SMTPClientConnector
    sensorType = 'None'

    def __init__(self):
        self.config = ConfigUtil.ConfigUtil()
        self.config.loadConfig()
        self.actuatorAdaptor = MultiActuatorAdaptor.TempActuatorAdaptor()
        self.persistenceUtil = PersistenceUtil()

    def handleSensorData(self, curVal, sensorType, sensorData):
        '''
        this method  handles all the sensor data and updates the actuator settings
        '''
        if (sensorType == 'temp'):
            self.nominalTemp = float(
                self.config.getProperty(
                    self.config.configConst.CONSTRAINED_DEVICE,
                    self.config.configConst.NOMINAL_TEMP))

            #checks if my current temperature is greater than nominal temperature
            if (curVal > self.nominalTemp):
                # set the Actuator data according to current temperature
                self.actuator.setCommand(ActuatorData.CMD_ON)
                self.actuator.setStateData('Decrease')
                self.actuator.setValue(curVal - self.nominalTemp)
                self.actuatorAdaptor.updateActuator(self.actuator, 'temp')
                #               self.connector.publishMessage('Excessive Temperature Alert', self.actuator)
                self.persistenceUtil.writeSensorDataToDbms(sensorData)

            #checks if my current temperature is lesser than nominal temperature
            elif (curVal < self.nominalTemp):
                # set the Actuator data according to current temperature
                self.actuator.setCommand(ActuatorData.CMD_OFF)
                self.actuator.setStateData('Increase')
                self.actuator.setValue(curVal - self.nominalTemp)
                self.actuatorAdaptor.updateActuator(self.actuator, 'temp')
                #               self.connector.publishMessage('Excessive Temperature Alert', self.actuator)
                self.persistenceUtil.writeSensorDataToDbms(sensorData)
Пример #5
0
class SensorDataListener(object):
    '''
    classdocs
    '''
    persistenceUtil = PersistenceUtil()

    def __init__(self):
        '''
        Constructor
        '''
        self.r = redis.Redis(host='localhost', port=6379)

    def listener(self):
        pubsub = self.r.pubsub()
        pubsub.subscribe('SensorData')

        print("Starting message loop")
        while (True):
            message = pubsub.get_message()
            if message:
                #sensorDataJson = self.persistenceUtil.getSensorData()
                print(message['data'])
Пример #6
0
    def setUp(self):

        #instantiate persistenceUtil
        self.persistenceUtil = PersistenceUtil()
Пример #7
0
class PersistenceUtilTest(unittest.TestCase):
    """
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
    def setUp(self):

        #instantiate persistenceUtil
        self.persistenceUtil = PersistenceUtil()

    """
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""

    def tearDown(self):

        #set the reference to the variables to none to release any resources
        self.persistenceUtil = None

    """
	/**
	 * Tests the writeActuatorDataToDbms() method of PersistenceUtil class. 
	 * Checks whether it is able to write to redis and doesn't
	 * break if it cannot set up the connection to the server
	 */
	"""

    def testWriteActuatorDataToDbms(self):

        #Create ActuatorData instance
        actuatorData = ActuatorData()

        #write to redis and check if it returns true
        self.assertEqual(
            True, self.persistenceUtil.writeActuatorDataToDbms(actuatorData))

        #add an invalid port to the jedisActuator
        self.persistenceUtil.r_actuator = Redis(host="localhost", port=6379)

        #write to redis and check if it returns false
        self.assertEqual(
            True, self.persistenceUtil.writeActuatorDataToDbms(actuatorData))

    """	
	/**
	 * Tests the writeSensorDataToDbms() method of PersistenceUtil class. 
	 * Checks whether it is able to write to redis and doesn't
	 * break if it cannot set up the connection to the server
	 */
	"""

    def testWriteSensorDataToDbms(self):

        #Create ActuatorData instance
        sensorData = SensorData()

        #write to redis and check if it returns true
        self.assertEqual(
            True, self.persistenceUtil.writeSensorDataToDbms(sensorData))

        #add an invalid port to the jedisSensor
        self.persistenceUtil.r_sensor = Redis(host="localhost", port=6890)

        #write to redis and check if it returns false
        self.assertEqual(
            False, self.persistenceUtil.writeSensorDataToDbms(sensorData))

    """	
	/**
	 * Tests the registerSensorDataDbmsListener() method of PersistenceUtil class. 
	 * Checks whether it is able to register and doesn't
	 * break if it cannot set up the connection to the server
	 */
	"""

    def testRegisterSensorDataDbmsListener(self):

        #check for true when the connection variables are ok
        self.assertEqual(True,
                         self.persistenceUtil.registerSensorDataDbmsListener())

        #add an invalid port to the jedisSensor
        self.persistenceUtil.r_sensor = Redis(host="localhost", port=6890)

        #check for false when connection variables are invalid
        self.assertEqual(False,
                         self.persistenceUtil.registerSensorDataDbmsListener())

    """	
	/**
	 * Tests the registerActuatorDataDbmsListener() method of PersistenceUtil class. 
	 * Checks whether it is able to register and doesn't
	 * break if it cannot set up the connection to the server
	 */
	"""

    def testRegisterActuatorDataDbmsListener(self):

        #check for true when the connection variables are ok
        self.assertEqual(
            True, self.persistenceUtil.registerActuatorDataDbmsListener())

        #add an invalid port to the jedisSensor
        self.persistenceUtil.r_actuator = Redis(host="localhost", port=6890)

        #check for false when connection variables are invalid
        self.assertEqual(
            False, self.persistenceUtil.registerActuatorDataDbmsListener())
Пример #8
0
class MultiSensorAdaptor(threading.Thread):
    '''
    classdocs
    '''
    rateInSec = 10
    enableTempSensor = False
    enableHumidSensor = False
    tempSensorData = SensorData()
    humidSensorData = SensorData()
    hi2cSensorData = SensorData()
    manager = SensorDataManager()
    tempsensor = TempSensorAdaptorTask()
    #     humiditysensor = HumiditySensorAdaptorTask()
    #     hi2csensor = HI2CSensorAdaptorTask()
    persistenceutil = PersistenceUtil()

    def __init__(self, rateInSec=10):
        threading.Thread.__init__(self)
        #self.sensorData = SensorData()
        self.rateInSec = rateInSec
        #self.time      = self.sensorData.timeStamp

    def run(self):
        while True:

            if self.enableTempSensor:
                self.tempSensorData.setName('Temp')
                self.tempSensorData.addValue(self.tempsensor.getTemperature())
                #print(self.sensorData.curValue)
                #self.manager.handleSensorData(self.sensorData)
                self.persistenceutil.writeSensorDataToRedis(
                    self.tempSensorData)
                sleep(self.rateInSec)

            if self.enableHumidSensor:
                self.humidSensorData.setName("Humid")
                self.humidSensorData.addValue(
                    self.humiditysensor.getHumidity())
                #print(str(datetime.now()) + "SenseHat API Humidity   " + str(self.curHumid))
                #print(str(datetime.now()) + "I2C Direct Humidity:    " + str(self.i2cHumid.getHumidityData()))
                #print(self.sensorData.curValue)
                #self.manager.handleSensorData(self.sensorData)
                self.persistenceutil.writeSensorDataToRedis(
                    self.humidSensorData)

                sleep(self.rateInSec)

            if self.enableHI2CSensor:
                #                 self.displayAccelerometerData()
                #                 self.displayMagnetometerData()
                #                 self.displayPressureData()
                #                 self.displayHumidityData()
                #                 self.getHumidityData()
                #                 print(str(datetime.now()) + "I2C Direct Humidity:    " + str(self.RH))
                self.hi2cSensorData.setName("I2C_Humid")
                self.hi2cSensorData.addValue(self.hi2csensor.getHumidityData())
                #self.manager.handleSensorData(self.sensorData)
                self.persistenceutil.writeSensorDataToRedis(
                    self.hi2cSensorData)

                sleep(self.rateInSec)
Пример #9
0
class MultiSensorAdaptor(threading.Thread):
    '''
    classdocs
    '''
    rateInSec = 10
    enableTempSensor = False
    enableHumidSensor = False
    enableMoistureSensor = False
    tempSensorData = SensorData()
    humidSensorData = SensorData()
    moistureSensorData = SensorData()
    hi2cSensorData = SensorData()
    manager = SensorDataManager()
    tempsensor = TempSensorAdaptorTask()
    humiditysensor = HumiditySensorAdaptorTask()
    #moisturesensor = SoilMoistureSensorAdaptorTask()
    #     hi2csensor = HI2CSensorAdaptorTask()
    persistenceutil = PersistenceUtil()
    coapClientConnector = CoapClientConnector()
    dataUtil = DataUtil()

    def __init__(self, rateInSec=10):
        threading.Thread.__init__(self)
        #self.sensorData = SensorData()
        self.rateInSec = rateInSec
        #self.time      = self.sensorData.timeStamp

    def run(self):
        while True:

            if self.enableHumidSensor:
                resource = 'soilMoisture'
                self.humidSensorData.setName("SoilMoisture")
                self.humidSensorData.addValue(
                    self.humiditysensor.getHumidity())
                #print(str(datetime.now()) + "SenseHat API Humidity   " + str(self.curHumid))
                #print(str(datetime.now()) + "I2C Direct Humidity:    " + str(self.i2cHumid.getHumidityData()))
                #print(self.sensorData.curValue)
                self.manager.handleSensorData(self.humidSensorData)
                payload = self.dataUtil.toJsonFromSensorData(
                    self.humidSensorData)
                #print(payload)
                self.coapClientConnector.postRequest(resource, payload)
                sleep(15)

                self.coapClientConnector.getRequest(resource)
                sleep(5)

            if self.enableTempSensor:

                resource = 'temp'
                self.tempSensorData.setName('Temp')
                self.tempSensorData.addValue(self.tempsensor.getTemperature())
                #print(self.sensorData.curValue)
                #self.manager.handleSensorData(self.sensorData)
                #self.persistenceutil.writeSensorDataToRedis(self.tempSensorData)
                payload = self.dataUtil.toJsonFromSensorData(
                    self.tempSensorData)
                #print(payload)
                self.coapClientConnector.postRequest(resource, payload)
                sleep(5)
Пример #10
0
class TempSensorAdaptorTask(object):
    '''
    classdocs
    '''

    #instantiate the SenseHat class
    sense = SenseHat()

    #disable the emulator initially
    enableFetcher = False

    #instantiate the SensorData class
    sensorData = SensorData()
    sensorData.setName("Temperature Sensor")

    #instantiate PersistenceUtil
    pUtil = PersistenceUtil()

    #this method is used to set the readings and the frequency of readings if provided, else defaults to 10 and 5 respectively
    def __init__(self, numReadings=10, rateInSec=5):
        '''
        Constructor
        '''

        #set the number of readings you want to get
        self.numReadings = numReadings

        #set the rate at which you want to get the readings
        self.rateInSec = rateInSec

    #get the temperature from SenseHAT
    def getTemperature(self):

        #data is not f 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 fetcher is enabled
            if self.enableFetcher:

                #clear the sense hat
                self.sense.clear()

                #get the temperature from the sense hat
                temp = self.sense.get_temperature()

                #add it to the sensorData
                self.sensorData.addValue(temp)

                #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)

                self.sensorData.loggingData = data

                #write SensorData to redis
                self.pUtil.writeSensorDataToDbms(self.sensorData)

                #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 fetcher is not enabled
            else:

                #fetch didn't run
                return False

        #the fetcher is done running
        return True
Пример #11
0
from labs.module05.SensorDataManager import SensorDataManager
from labs.common.ConfigUtil import ConfigUtil
from labs.module05.TempActuatorAdaptor import TempActuatorAdaptor
import labs.module02.SmtpClientConnector as SmtpClientConnector
import logging
import time
import random
from sense_hat import SenseHat
from threading import Thread
from labs.module05.DataUtil import DataUtil
from labs.common.PersistenceUtil import PersistenceUtil
import json
import redis
from labs.module05.ActuatorDataListener import ActuatorDataListener
from labs.module07.coapclient import coapclient
pu = PersistenceUtil()


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
Пример #12
0
 def __init__(self):
     self.config = ConfigUtil.ConfigUtil()
     self.config.loadConfig()
     self.actuatorAdaptor = MultiActuatorAdaptor.TempActuatorAdaptor()
     self.persistenceUtil = PersistenceUtil()