Exemple #1
0
	def testPrepareAndSendSensorData(self):

		#Get the current event loop
		loop = asyncio.get_event_loop()

		#Assert false when the event loop given is running but not valid SensorData given
		self.assertEqual(self.coapClientConnector.prepareAndSendSensorData("Hello", loop, "pallybook.lan", "Temp"), False)

		#Create a sensorData object
		sensorData = SensorData()

		#add a value to SensorData
		sensorData.addValue(9)

		#Assert true when given the current event loop is running and valid SensorData
		self.assertEqual(self.coapClientConnector.prepareAndSendSensorData(sensorData, loop, "pallybook.lan", "Temp"), True)

		#Get a new event loop
		loop = asyncio.new_event_loop()

		#Stop the loop such that there is no event loop currently
		loop.stop()

		#Assert false when the event loop given is not running but valid SensorData
		self.assertEqual(self.coapClientConnector.prepareAndSendSensorData(sensorData, loop, "pallybook.lan", "Temp"), False)
Exemple #2
0
class Module05Test(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):
        self.tempTask = TempSensorAdaptorTask()
        self.tempSensorData = SensorData()
        self.dataUtil = DataUtil()

    """
	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):
        pass

    """
	Place your comments describing the test here.
	"""

    def testtoJsonFromSensorData(self):
        self.tempSensorData.addValue(self.tempTask.getTemperature())
        self.jsonData = self.dataUtil.toJsonFromSensorData(self.tempSensorData)
        print(type(self.jsonData))
        self.assertTrue(type(self.jsonData) == str)
        pass
Exemple #3
0
    def testPublishSensorCommand(self):

        #Call the connect method of MqttClientConnector with valid values
        self.mqttClientConnector.connect("broker.hivemq.com", 1883)

        #Let it connect
        sleep(2)

        #Create SensorData object and add a valid value
        sensorData = SensorData()
        sensorData.addValue(9)

        #Publish and assert true for successful publishing
        self.assertEqual(
            True, self.mqttClientConnector.publishSensorCommand(sensorData, 2))

        #Call the connect method of MqttClientConnector with invalid host value
        self.mqttClientConnector.connect("brosdf235iytksg", 1883)

        #Let it connect
        sleep(2)

        #Create sensorData and add a valid value
        sensorData = SensorData()
        sensorData.addValue(9)

        #Publish to topic and assert False for failure to publish
        self.assertEqual(
            False,
            self.mqttClientConnector.publishSensorCommand(sensorData, 2))

        #Pass a null to method and assert False for failure to publish
        self.assertEqual(
            False, self.mqttClientConnector.publishSensorCommand(None, 2))
Exemple #4
0
    def testSensorDataToJson(self):

        #Create two sensorData instances
        sensorData1 = SensorData()
        sensorData2 = SensorData()

        #Create two sensor Data instances and check if their jsonStr are equal
        #First sensorData
        sensorData1.setName("Temperature Sensor")
        sensorData1.addValue(9)

        #change timestamp to bogus value because they will be different
        sensorData1.timeStamp = "None"

        #Second sensorData
        sensorData2.setName("Temperature Sensor")
        sensorData2.addValue(9)

        #change timestamp to bogus value because they will be different
        sensorData2.timeStamp = "None"

        #Get their JSON strings
        jsonStr1 = self.dataUtil.toJsonFromSensorData(sensorData1)
        jsonStr2 = self.dataUtil.toJsonFromSensorData(sensorData2)

        #Check for equality
        self.assertEqual(jsonStr1, jsonStr2)

        pass
Exemple #5
0
    def runTests(self, resourceName):
        #generated a random temperture data and created a sensordata object
        sensordata = SensorData()
        temperature = random.uniform(0.0, 30.0)
        sensordata.addValue(temperature)

        #created DataUtil instance and converted the sensordata to json data
        datautil = DataUtil()
        jsondata = datautil.toJsonFromSensorData(sensordata)
        print("the first json:\n" + jsondata)

        #post the jsondata to the server
        response = self.client.post(resourceName, jsondata, None, 10)
        logging.info(response.pretty_print())

        #get data from the server
        response = self.client.get(resourceName)
        logging.info(response.pretty_print())

        #put jsondata to the server
        response = self.client.put(resourceName, jsondata, None, 10)
        logging.info(response.pretty_print())

        #delete resources
        response = self.client.delete(resourceName, None, 10)
        logging.info(response.pretty_print())

        #stop the client
        self.client.stop()
class Cpu(threading.Thread):
    '''
    Class to create a threaded task to report the system CPU and 
    memory usage using coAP
    '''
    def __init__(self,
                 coAPClient: CoAPClientConnector,
                 intervalTime=20,
                 looplimit=-1):
        '''
        Constructor
        '''
        #Get an asyncio loop
        self.loop = asyncio.get_event_loop()
        self.looplimit = looplimit
        #Initialzing the threaded class
        threading.Thread.__init__(self, args=(self.loop, ))
        self.interval = intervalTime
        self.coAPClient = coAPClient

        #Initializing the sensorData instance
        self.hrSensorData = SensorData()

    def getCpu(self):
        '''
        Method to return percentage of CPU being used
        '''
        i = 0
        psutil.cpu_percent(interval=1)
        #Running to repeatidly read data
        while True:
            i = i + 1
            data = psutil.cpu_percent(interval=1)
            #Only adding the data to sensorData instance
            #if it's not None
            if data != None:
                self.hrSensorData.addValue(float(data))
                self.hrSensorData.setName("CPU Usage")
                self.coAPClient.sendSensorDataPOST(self.loop,
                                                   self.hrSensorData)
            sleep(self.interval)

            if self.looplimit != -1:
                if i == self.looplimit:
                    break

    def run(self):
        self.getCpu()
        return True


# if __name__ == "__main__":
#     coAP = CoAPClientConnector("coap://bubblegum.lan:5683/cpu")
#     task = Cpu(coAP)
#     task.start()
class Module06Test(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):
        self.ddm = DeviceDataManager()
        self.ddm.actuator.addValue(15)
        self.mqt = MqttClientConnector()
        self.sd = SensorData()
        self.sd.addValue(14)
        mm = MQTTMessage()
        mm.payload = "ss"
        pass

    """
	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):
        pass

    """
	Place your comments describing the test here.
	"""

    def testconnect(self):
        self.assertTrue(self.mqt.connect(), "Connection Failed")
        pass


# 	def testpublishActuatorCommand(self):
# 		ac = ActuatorData();
# 		ac.addValue(14)
# 		self.assertTrue(self.mqt.publishActuatorCommand(ac,1), "publishActuator Failed")
# 		pass

    def testpublishSensorData(self):
        self.assertTrue(self.mqt.publishSensorData(self.sd, 1),
                        "publishSensor Failed")
        pass

    def testMessageReceived(self):
        self.assertTrue(self.mqt.MessageReceived(MQTTMessage),
                        "Message Failed")
        pass

    def testClientClose(self):
        self.assertTrue(self.mqt.clientClose(),
                        "Client connection close Failed")
        pass
Exemple #8
0
    def testwriteSensorDataToFile(self):

        #create sensorData object
        sensorData = SensorData()

        #add a value
        sensorData.addValue(9)

        #write to file and assert True
        self.assertEqual(True, self.dataUtil.writeSensorDataToFile(sensorData))

        pass
Exemple #9
0
class HumiditySensorAdaptorTask:
    #Default Constructor    
    def __init__(self):
        self.sensor = SenseHat()
        self.sensorData = SensorData()
        self.sdm = None
    #Method to implement lazy object initialization     
    def objectLoader(self):
        self.sensorData.setName("HumiditySenseHat")
    #Method for fetching the sensor value from senseHat module   
    def readSensorValue(self):
        humidity = self.sensor.get_humidity()
        self.sensorData.addValue(humidity)
        return self.sensorData
class SensorDataTest(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):
		self.sensor = SensorData()
		self.sensor.addValue(11)
		pass

	"""
	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):
		pass
	
	"""
	Place your comments describing the test here.
	"""
	def testSomething(self):
		pass
	
	'@Test'
	def testgetCurrent(self):
		self.assertGreaterEqual(self.sensor.getCurrentValue(),0.0,'Current temperature coming less than 0')
		pass
	
	'@Test'
	def testgetAvg(self):
		self.assertGreaterEqual(self.sensor.getAverageValue(),0.0,'Avg coming less than 0')
		pass
	
	'@Test'
	def testgetMin(self):
		self.assertGreaterEqual(self.sensor.getMinValue(),0.0,'Min coming less than 0')
		pass
		
	'@Test'
	def testgetMax(self):
		self.assertGreaterEqual(self.sensor.getMaxValue(),0.0,'Max coming less than 0')
		pass
	
	'@Test'
	def testgetCount(self):
		self.assertGreaterEqual(self.sensor.getCount(),0.0,'sample count coming less than 0')
		pass
class I2CSensorAdaptorTask:
    def __init__(self):
        self.sdm = None
        self.sensorData = None
        self.i2cBus = smbus.SMBus(1)
        self.humidAddr = 0x5F  # address for humidity sensor
        self.bits = 8
        self.i2cBus.write_byte_data(self.humidAddr, 0, 0)

    #Method to implement lazy object initialization
    def objectLoader(self):
        self.sensorData = SensorData()
        self.sensorData.setName("HumidityI2C")
        self.sdm = SensorDataManager.SensorDataManager()

    #Method for fetching the sensor value from senseHat I2C module
    def displayHumidityData(self):
        coeffH0 = self.i2cBus.read_byte_data(self.humidAddr, 0x30)
        coeffH1 = self.i2cBus.read_byte_data(self.humidAddr, 0x31)
        H0_rH = float(coeffH0 / 2.0)
        H1_rH = float(coeffH1 / 2.0)
        #print("H0_RH = " + str(H0_rH))
        #print("H1_rH = " + str(H1_rH))
        valH0T0a = self.i2cBus.read_byte_data(self.humidAddr, 0x36)
        valH0T0b = self.i2cBus.read_byte_data(self.humidAddr, 0x37)
        H0_T0_OUT = (valH0T0b << self.bits) | valH0T0a
        if H0_T0_OUT & (1 << 16 - 1):
            H0_T0_OUT -= (1 << 16)
        #print("H0_T0_OUT = " + str(H0_T0_OUT))
        valH1T1a = self.i2cBus.read_byte_data(self.humidAddr, 0x3A)
        valH1T1b = self.i2cBus.read_byte_data(self.humidAddr, 0x3B)
        H1_TO_OUT = (valH1T1b << self.bits) | valH1T1a
        if H1_TO_OUT & (1 << 16 - 1):
            H1_TO_OUT -= (1 << 16)
        #print("H1_T0_OUT = " + str(H1_TO_OUT))
        rawH1T1a = self.i2cBus.read_byte_data(self.humidAddr, 0x28)
        rawH1T1b = self.i2cBus.read_byte_data(self.humidAddr, 0x29)
        H_T_OUT = (rawH1T1b << self.bits) | rawH1T1a
        if H_T_OUT & (1 << 16 - 1):
            H_T_OUT -= (1 << 16)
        hper = float(((H1_rH - H0_rH) * (H_T_OUT - H0_T0_OUT)) /
                     (H1_TO_OUT - H0_T0_OUT)) + H0_rH
        self.sensorData.addValue(hper)
        return self.sensorData.current
        #print("I2C Humidity = " + str(Ih) + "%")

    #Method to push data to SensorDataManger
    def pushData(self):
        self.sdm.hadleSensorData(self.sensorData)
Exemple #12
0
 def testAddValue(self):
     testValue = 10.0
     sensordata = SensorData()
     sensordata.addValue(testValue)
     sampleCount = sensordata.getSampleCount()
     assert sampleCount == 1
     curValue = sensordata.getValue()
     assert curValue == testValue
     avgValue = sensordata.getAvgValue()
     assert avgValue == testValue
     minValue = sensordata.getMinValue()
     assert minValue == testValue
     maxValue = sensordata.getMaxValue()
     assert maxValue == testValue
     totValue = sensordata.getTotValue()
     assert totValue == testValue
Exemple #13
0
 def runTests(self, resource):
     sensorData = SensorData(resource, 10, 30)
     sensorData.addValue(10)
     dataUtil = DataUtil()
     jsondata = dataUtil.sensorTojson(sensorData)
     self.initClient()
     self.pingServer()
     self.handleGet(resource)
     self.handlePost(resource, jsondata)
     self.handleGet(resource)
     sensorData.addValue(20)
     jsondata = dataUtil.sensorTojson(sensorData)
     self.handlePut(resource, jsondata)
     self.handleGet(resource)
     self.handleDelete(resource)
     self.handleGet(resource)
class Mem(threading.Thread):
    '''
    Class to create a threaded task to report the system CPU and 
    memory usage using coAP
    '''
    def __init__(self,
                 coAPClient: CoAPClientConnector,
                 intervalTime=20,
                 looplimit=-1):
        '''
        Constructor
        '''
        #Get an event loop
        self.loop = asyncio.get_event_loop()
        self.looplimit = looplimit
        #Initialzing the threaded class
        threading.Thread.__init__(self, args=(self.loop, ))
        self.interval = intervalTime
        self.coAPClient = coAPClient

        #Initializing the sensorData instance
        self.hrSensorData = SensorData()

    def getRam(self):
        '''
        Method to return percentage of system memory being used
        '''
        i = 0
        while True:
            i = i + 1
            data = psutil.virtual_memory()[2]
            #Only adding the data to sensorData instance
            #if it's not None
            if data != None:
                self.hrSensorData.addValue(float(data))
                self.hrSensorData.setName("Memory Usage")
                self.coAPClient.sendSensorDataPOST(self.loop,
                                                   self.hrSensorData)
            sleep(self.interval)

            if self.looplimit != -1:
                if i == self.looplimit:
                    break

    def run(self):
        self.getRam()
        return True
Exemple #15
0
class Module05Test(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):
		
		self.ac = ActuatorData()
		self.ac.addValue(15)
		self.sensor = SensorData()
		self.sensor.addValue(15)
		self.hsa = HumiditySensorAdaptorTask()
		self.hsa.objectLoader()
		self.pu = PersistenceUtil()
		pass

	"""
	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):
		pass

	"""
	Place your comments describing the test here.
	"""
	def testSenseHatActivator(self):
		hat = SenseHatLedActivator()
		self.assertTrue(hat.updateLed("Test"),"Led Update Failed")
		pass
	
	def testSensorData(self):
		a = self.hsa.readSensorValue()
		self.assertGreaterEqual(a.current, 0, "Issue with sensor")
		pass
	
	def testWriteActuator(self):
		self.assertTrue(self.pu.writeActuatorToDataDbms(self.ac))
		pass
 	
	def testWriteSensor(self):
		self.assertTrue(self.pu.writeSensorToDataDbms(self.sensor))
		pass
Exemple #16
0
    def testJsonToSensorData(self):

        #Create sensorData
        sensorData = SensorData()

        #Add some value and set a name
        sensorData.addValue(9.0)
        sensorData.setName("Temperature Sensor")

        #convert to JSON
        jsonStr = self.dataUtil.toJsonFromSensorData(sensorData)

        #convert back to ActuatorData
        sensorDataTest = self.dataUtil.toSensorDataFromJson(jsonStr)

        #test if their variables are equal
        self.assertEqual("Temperature Sensor", sensorDataTest.getName())
        self.assertEqual(9.0, sensorDataTest.getCurrentValue(), 0)
class TempSensorAdaptorTask(threading.Thread):
    def __init__(self):
        self.data = SensorData()
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
                            level=logging.DEBUG)  # logging basic data

    ''' get sensordata from senshat API'''

    def run(self):
        sensData = SenseHat()  #instance of SenseHat
        sense = sensData.get_temperature(
        )  #calling method get_Temperature for SenseHat
        #         self.data.setName('Temperature')
        self.data.addValue(sense)  #updating values using addvalue method
        #         print(self.data.getRecord()) #printing record
        logging.info("Temperature Value: " + str(self.data.getCurrentValue()))
        #         json = "Temperature Value:"+ str(self.data.getCurrentValue())
        data = self.data.getCurrentValue()
        return sense
Exemple #18
0
class TempSensorAdaptorTask:
       
    
    def run(self):
        i=0
        while(i<11):
            self.readSensorValue()
            sleep(10)
            i+=1
            
    #Default Constructor    
    def __init__(self):
        self.sensor = SenseHat()
        self.sensorData = SensorData()
        
    #Method for fetching the sensor value from senseHat module   
    def readSensorValue(self):
        temp = self.sensor.get_temperature()
        self.sensorData.addValue(temp)
        self.sdm = SensorDataManager.SensorDataManager()
        self.sdm.hadleSensorData(self.sensorData)
        return self.sensorData.current
Exemple #19
0
    def testGetHandleSensorData(self):

        #initialize sensor data
        sensorData = SensorData()

        #when current value is greater than nominal temp
        sensorData.addValue(90)

        #get the actuatorData returned from the sensor data manager
        actuatorData = self.sensorDataManager.handleSensorData(sensorData)

        #check if actuatorData is of type ActuatorData
        self.assertIsInstance(actuatorData, ActuatorData)

        #test the value, which should be "arrowBlueDec"
        self.assertEqual(self.arrowBlueDec, actuatorData.getValue())

        #actuatorData command should be decrease temp
        self.assertEqual(actuatorData.getCommand(), "DECREASE TEMP")

        #when current value is less than nominal temp
        sensorData.addValue(10)

        #get the actuatorData returned from the sensor data manager
        actuatorData = self.sensorDataManager.handleSensorData(sensorData)

        #check if actuatorData is of type ActuatorData
        self.assertIsInstance(actuatorData, ActuatorData)

        #actuatorData command should be increase temp
        self.assertEqual(actuatorData.getCommand(), "INCREASE TEMP")

        #when current value is equal to the nominal temp
        sensorData.addValue(20)

        #get the actuatorData returned from the sensor data manager
        actuatorData = self.sensorDataManager.handleSensorData(sensorData)

        #actuatorData is none sensor data equal to nominal temp
        self.assertEqual(actuatorData, None)

        pass
Exemple #20
0
from random import uniform
from datetime import datetime  #importing datetime to perform date and time operations

topic = "Temperature Sensor"

config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
host = config.getProperty(ConfigConst.ConfigConst.MQTT_CLOUD_SECTION,
                          ConfigConst.ConfigConst.HOST_KEY)
'''
Creating Sensor Data
'''
sensor = SensorData(topic, 15, 30)
sensor.curVal = uniform(float(sensor.getMinValue()),
                        float(sensor.getMaxValue()))
sensor.addValue(sensor.curVal)
sensor.diffVal = sensor.curVal - sensor.avgVal
sensor.timestamp = datetime.now()
logging.info('SensorData to be sent:')
print("Sensor Value before converting to Json: " + str(sensor))
'''
Converting SensorData to json format
'''
data = DataUtil()
json_data = data.toJsonfromSensor(sensor)
logging.info('SensorData converted into Json:')
print("SensorData in Json Format before publishing" + str(json_data) + "\n")

pub_client = MqttClientConnector()
'''
Function is used to publish the Json to the MQTT broker through MQTT ClientConnector
Exemple #21
0
from labs.common.SensorData import SensorData
from labs.module08.TempSensorAdaptorTask import TempSensorAdaptorTask
from labs.common.DataUtil import DataUtil
import logging
from time import sleep

if __name__ == '__main__':
    resource = 'temp'
    #payload = "for test"

    logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
                        level=logging.DEBUG)
    print('------->')
    logging.info("Connecting to Coap Server...")
    coapClientConnector = CoapClientConnector()
    tempSensorData = SensorData()
    temp = TempSensorAdaptorTask()
    dataUtil = DataUtil()
    while (True):

        tempSensorData.addValue(temp.getTemperature())
        payload = dataUtil.toJsonFromSensorData(tempSensorData)
        print("Json Before issuing the request...")
        logging.info(payload)
        print('------->')
        coapClientConnector.postRequest(resource, payload)
        #         coapClientConnector.putRequest(resource, payload)
        coapClientConnector.getRequest(resource)
        #         coapClientConnector.deleteRequest(resource)
        sleep(10)
Exemple #22
0
class Module03Test(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):
        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()

    """
	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):
        pass

    """
	Place your comments describing the test here.
	"""

    def testloadConfig(self):
        self.assertTrue(
            self.config.loadConfig(
                '../../../config/ConnectedDevicesConfig.props'))

    def testhasConfigData(self):
        self.assertTrue(self.config.hasConfigData())

    def testgetValue(self):
        self.assertEqual(self.config.getValue("smtp.cloud", "port"), '465')

    def testgetSensorData(self):
        assert self.tempsensor.getTemperature(
        ) > 0 and self.tempsensor.getTemperature() < 30

    def testgetAverageValue(self):
        assert self.sensordata.getAverageValue(
        ) > 0 and self.sensordata.getAverageValue() < 30

    def testgetCount(self):
        self.assertEqual(self.sensordata.getCount(), 4)

    def testgetCurrentValue(self):
        assert self.sensordata.getCurrentValue(
        ) > 0 and self.sensordata.getCurrentValue() < 30

    def testMinValue(self):
        assert self.sensordata.getMinValue(
        ) >= 0 and self.sensordata.getMinValue() < 30

    def testMaxValue(self):
        assert self.sensordata.getMaxValue(
        ) > 0 and self.sensordata.getMaxValue() < 30

    def testName(self):
        self.assertEqual(self.sensordata.getName(), 'Temperature')

    def testgetCommand(self):
        self.assertEqual(self.actuatordata.getCommand(), 'Increasing')

    def testName2(self):
        self.assertEqual(self.actuatordata.getName(), 'SenseHat')

    def testhandleSenseData(self):
        assert self.sdmanager.handleSensorData(self.sensordata) is not None
Exemple #23
0
class HeartRateTask(threading.Thread):
    '''
    Threaded class to read the heart-rate data 
    from the shared sensor resource.
    '''
    def __init__(self,
                 coAPClient: CoAPClientConnector,
                 intervalTime=2,
                 looplimit=-1):
        '''
        Constructor
        Sets the interval time and mqttClient
        creates a sensorData instace
        '''
        self.loop = asyncio.get_event_loop()
        self.looplimit = looplimit
        #Initialzing the threaded class
        threading.Thread.__init__(self, args=(self.loop, ))
        self.interval = intervalTime
        self.coAPClient = coAPClient
        #Getting an instance of the shared resource
        self.dataStore = SensorResource.getInstance()
        #Initializing the sensorData instance
        self.hrSensorData = SensorData()

    def readData(self):
        '''
        Function to read data from the shared resource
        '''
        i = 0
        #Running to repeatidly read data
        while True:
            i = i + 1
            data = self.dataStore.heartRate
            #Only adding the data to sensorData instance
            #if it's not None
            if data != None:
                self.hrSensorData.addValue(float(data))
                self.hrSensorData.setName("Heart Rate Monitor")
                self.coAPClient.sendSensorDataPOST(self.loop,
                                                   self.hrSensorData)
            sleep(self.interval)

            if self.looplimit != -1:
                if i == self.looplimit:
                    break

    def run(self):
        '''
        Run function for the thread to
        call readData function
        '''
        self.readData()
        return True


# if __name__ == "__main__":
#     coAP = CoAPClientConnector("coap://bubblegum.lan:5683/heartrate")
#     sensorRead = SerialCommunicator(115200)
#     sensorRead.start()
#     task = HeartRateTask(coAP)
#     task.run()
Exemple #24
0
from labs.common.ConfigUtil import ConfigUtil
from labs.common.DataUtil   import DataUtil
from labs.common.SensorData import SensorData
from labs.module06.MqttClientConnector  import MqttClientConnector

topic   = "Temperature Sensor"

config  = ConfigUtil('../../../config/ConnectedDevicesConfig.props');
host    = config.getProperty(ConfigConst.ConfigConst.MQTT_CLOUD_SECTION, ConfigConst.ConfigConst.HOST_KEY)

'''
Creating the Sensor Data
'''
sensor              = SensorData(topic,0,30)
sensor.curValue     = uniform(float(sensor.getMinValue()), float(sensor.getMaxValue())); 
sensor.addValue(sensor.curValue);
sensor.diffValue    = sensor.curValue - sensor.avgVal;
sensor.timestamp    = datetime.now();
logging.info('SensorData to be sent:')
print("Sensor data before converting to Json: " + str(sensor));

'''
Converting the Sensor Data to the JSON format
'''
data        = DataUtil()
jsonData    = data.SensorDataToJson(sensor)
logging.info('SensorData converted into Json:')
print("SensorData in Json Format before publishing" + "\n" + str(jsonData) + "\n")
pub_client  = MqttClientConnector();

'''
'''
This will connect to the CoAP server using CoapClientConnector, 
run a number of tests, then exit.
'''
config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
config.loadConfig()

data = DataUtil()

host = config.getProperty(ConfigConst.ConfigConst.COAP_DEVICE_SECTION, ConfigConst.ConfigConst.HOST_KEY)
port = int(config.getProperty(ConfigConst.ConfigConst.COAP_DEVICE_SECTION, ConfigConst.ConfigConst.PORT_KEY))
path = 'temperature'

sensor = SensorData("Temperature",0.0,30.0)
sensor.addValue(4.0)
print(str(sensor))

coapClient = CoapClientConnector(host, port, path)

coapClient.ping()
json_data = data.SensorDataToJson(sensor)
print("json"+json_data)

#coapClient.get() #Get will respond with NOT_FOUND since data object on server is not initialized
coapClient.post((json_data)) #Post JSON to server
coapClient.get()

sensor.addValue(5.00)
coapClient.put(data.SensorDataToJson(sensor)) #Update resource on the server
coapClient.get()
Exemple #26
0
class TempSensorAdaptor(Thread):

    curTemp = 0
    updateTime = 0
    rateInSec = 0
    sensorData = 0
    senseHat = 0
    connector = 0
    alertDiff = 0
    senseHatLed = 0
    actuatorData = 0
    TAE = 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))

    def getCurrValue(self):

        return self.currValue

    def setEnableTempEmulator(self, flag):
        self.enableTempEmulator = flag

    def run(self):
        while True:
            TAE = TempActuatorEmulator()
            TAE.start()
            self.curTemp = self.senseHat.get_temperature()
            self.sensorData.addValue(self.curTemp)
            print('\n--------------------')
            print('New sensor readings: \n')
            print(' ' + str(self.sensorData))
            
            print('New actuator readings: \n')
            print(' ' + str(self.actuatorData))

            if (abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))) > self.alertDiff):
                print('\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggering alert...')
                try:
                    self.connector.publishMessage('Exceptional sensor data [test]', self.sensorData)
                except Exception as e:
                    print("Failed to send email\n" + str(e))
                    
                print('\n Actuator activating...')
                if (self.curTemp > float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))):
                    self.actuatorData.addValue(1, abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))))
                else:
                    self.actuatorData.addValue(2, abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))))
            
            
                
                # LED Display
                #self.senseHatLed.displayMsg(abs(self.curTemp - self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY)))
               
                
            else:
                self.actuatorData.addValue(0, 0)
            
        self.enableTempEmulator.updateData(self.actuatorData)    
        sleep(self.updateTime)
Exemple #27
0
    def testGetHandleSensorData(self):

        #log the test
        logging.info(
            "\nTesting the handleSensorData() method of SensorDataManager")

        #initialize sensor data to represent reading from I2C
        sensorDataI2C = SensorData()

        #add a humidity value
        sensorDataI2C.addValue(10)

        #set the name for i2c
        sensorDataI2C.setName("i2c humidity")

        #initialize sensor data to represent reading from SenseHAT API
        sensorDataAPI = SensorData()

        #add a humidity value
        sensorDataAPI.addValue(9)

        #set the name for i2c
        sensorDataAPI.setName("sense_hat API humidity")

        #add them to a list
        sensorDataTest = []
        sensorDataTest.append(sensorDataI2C)
        sensorDataTest.append(sensorDataAPI)

        #get the actuatorDataList returned from the sensor data manager
        actuatorDataList = self.sensorDataManager.handleSensorData(
            sensorDataTest)

        #check if actuatorData at both indexes are of type ActuatorData
        self.assertIsInstance(actuatorDataList[0], ActuatorData)
        self.assertIsInstance(actuatorDataList[1], ActuatorData)

        #test the actuatorData value at the first index, which should simply be the first value (10)
        self.assertEqual(10, actuatorDataList[0].getValue())

        #test the actuatorData command at the first index which should be DISPLAY I2C Humidity
        self.assertEqual(actuatorDataList[0].getCommand(),
                         "DISPLAY I2C Humidity")

        #test the actuatorData name at the second index which should be I2C Humidity
        self.assertEqual(actuatorDataList[0].getName(), "I2C Humidity")

        #test the value at the second index, which should simply be the first value (9)
        self.assertEqual(9, actuatorDataList[1].getValue())

        #test the actuatorData command at the second index which should be DISPLAY I2C Humidity
        self.assertEqual(actuatorDataList[1].getCommand(),
                         "DISPLAY SENSE HAT API Humidity")

        #test the actuatorData name at the second index which should be I2C Humidity
        self.assertEqual(actuatorDataList[1].getName(),
                         "SENSE HAT API Humidity")

        #initialize a random sensorData object and add it to the list and call the manager again
        sensorData = SensorData()

        #set invalid sensor data name
        sensorData.setName("blah blah")

        #append to list
        sensorDataTest.append(sensorData)

        #get the actuatorDataList returned from the manager should still have a length of 2 because we only added an invalid type
        actuatorDataList = self.sensorDataManager.handleSensorData(
            sensorDataTest)

        #check if length of actuatorDataList is 2
        self.assertEqual(len(actuatorDataList), 2)

        #clear the list and only add invalid sensor data
        sensorDataTest = []
        sensorDataTest.append(sensorData)

        #get the actuatorDataList returned from the manager should be None
        actuatorDataList = self.sensorDataManager.handleSensorData(
            sensorDataTest)

        #check if it is none
        self.assertEqual(actuatorDataList, None)
class DataUtilTest(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):
        self.du = DataUtil()
        self.sd = SensorData()
        self.sd.addValue(15)
        self.sd.setName("Test")
        self.ad = ActuatorData()
        self.ad.addValue(44)
        self.ad.setName("Test")
        self.ad.setCommand("Test")
        pass

    """
	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):
        pass

    """
	Place your comments describing the test here.
	"""

    def testSomething(self):
        pass

    '@Test'

    def testCheckJsonData(self):
        jstring = self.du.toJsonFromSensorData(self.sd)
        #print(jstring)
        sd1 = self.du.toSensorDataFromJson(jstring)

        #print(str(self.sd.getCurrentValue()))
        #print(str(sd1.getCurrentValue()))
        self.assertTrue(self.sd.getCount() == sd1.getCount(),
                        "count does not match")
        self.assertTrue(self.sd.getCurrentValue() == sd1.getCurrentValue(),
                        "current does not match")
        pass

    '@Test'

    def testCheckActuatorData(self):
        jstring = self.du.toJsonFromActuatorData(self.ad)

    '@Test'

    def testtoActuatorDataFromJsonFile(self):
        self.assertTrue(self.du.toActuatorDataFromJsonFile(),
                        "File to actuator failed")
        pass

    '@Test'

    def testwriteActuatorDataToFile(self):
        self.assertTrue(self.du.writeActuatorDataToFile(self.ad),
                        "File to actuator failed")
        pass

    '@Test'

    def testwriteSensorDataToFile(self):
        self.assertTrue(self.du.toActuatorDataFromJsonFile(),
                        "File to actuator failed")
        pass
Exemple #29
0
from labs.common.ConfigUtil import ConfigUtil
from labs.common.SensorData import SensorData
from labs.common.DataUtil import DataUtil
from labs.module06.MqttClientConnector import MqttClientConnector

topic = "Temperature Sensor"

config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
host = config.getProperty(ConfigConst.MQTT_GATEWAY_SECTION,
                          ConfigConst.HOST_KEY)

#Creating Sensor Data
sensorData = SensorData(topic, 10, 30)
sensorData.curVal = uniform(float(sensorData.getMinValue()),
                            float(sensorData.getMaxValue()))
sensorData.addValue(sensorData.curVal)
sensorData.diffVal = sensorData.curVal - sensorData.avgVal
sensorData.timestamp = datetime.now().replace(microsecond=0)
sensorData.sampleCount = 1
logging.info('\nSensorData for sending: ')
print("\n" + str(sensorData))

#Converting SensorData to json format
data = DataUtil()
jsondata = data.sensorTojson(sensorData)
logging.info('\nSensorData after Json conversion: ')
print("\nSensorData in Json Format for publishing: \n" + str(jsondata) + "\n")

pubclient = MqttClientConnector()

#Function call to publish the Json to the MQTT broker through MQTT ClientConnector
 def getSensorData(self):
     d = random.uniform(0, 30)
     SensorData.addValue(d)
     self.sendNotification()