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
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 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 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)
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
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 GasSensor(object): def __init__(self): self.sendata = SensorValueGenerator() self.data = SensorData() logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) # logging basic data '''if(gasValue > 1000 | gasValue < 1500): print(" Healthy environment -- Enough CO2 for plants") if(gasValue > 2000): print("GAS ALERT!! Co2 exceeding in the air") else: print(" please increase the co2 value for good growth of plants!!!") ''' def gasSensorvalue(self): gasValue = self.sendata.GasEmulator() self.data.setName('gasValue') #setting sensor name with setName method self.data.getCurrentValue() return gasValue
class LuminanceSensor(threading.Thread): def __init__(self): self.data = SensorData() self.sendata = SensorValueGenerator() logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) # logging basic data ''' if(Luminance < 589 and Luminance > 495): print("\n Intensity of green and yellow is good!!") elif(Luminance < 627 and Luminance > 589): print("\n Intensity of Orange is good for maximum Photosynthesis!!") elif(Luminance < 770 and Luminance > 627): print("\n Intensity enhancing flowering") else: print("\n Luminance is harmful !! plant will burn!!!") ''' def Luminance(self): Luminance = self.sendata.LuminanceEmulator() self.data.setName( 'luminance') #setting sensor name with setName method return Luminance
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
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
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()
class Module04Test(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.sd = SensorData() self.sd.addValue(11) self.sd.setName("Test") self.sdm = SensorDataManager() self.sdm.actuator.addValue(11) self.actuator = ActuatorData() self.actuator.addValue(2) self.actuator.setName("Test") self.tsa = MultiSensorAdaptor() self.taa = MultiActuatorAdaptor() self.tat = HumiditySensorAdaptorTask() self.tat.sensorData = SensorData() self.shla = SenseHatLedActivator() """ 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. """ '@Test' def testSendNotification(self): self.assertTrue(self.sdm.sendNotification(), "Notification Unsucessful") pass '@Test' def testhadleSensorData(self): self.assertTrue(self.sdm.hadleSensorData(self.sd), "Sensor handle data method not working") '@Test' def testgetSensorData(self): self.assertTrue(self.tsa.getSensorData(), "Issue in temperature adaptor") '@Test' def testreadSensorValueMin(self): self.assertGreaterEqual(self.tat.readSensorValue(), 0.0, 'sensor value coming less than 0') self.assertGreaterEqual(100, self.tat.readSensorValue(), 'sensor value coming more than 100') '@Test' def testupdateActuator(self): self.assertTrue(self.taa.updateActuator(self.actuator), "Actuator update failed") '@Test' def testupdateLed(self): self.assertTrue(self.shla.updateLed("Test Message"), "Led update failed") '@Test' def testreadSensorValuePushNotification(self): self.tat.sensorData = SensorData() self.tat.sensorData.addValue(12) self.tat.sensorData.setName("Test") self.tat.sdm = SensorDataManager() self.assertTrue(self.tat.pushData(), "Message not getting pushed to Sensor Data Manager")
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): #instantiate sensorData self.sensorData = SensorData() 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): #set the reference to the variables to none to release any resources self.sensorData = None """ This test tests the addValue() method of SensorData module. It checks whether the values are being correctly stored by getting the current value, the average value and the count """ def testAddValue(self): logging.info('Running testAddValue()') #add any valid value self.sensorData.addValue(120) #the current value should represent the recently added value self.assertEqual(120, self.sensorData.getCurrentValue()) #as it is the first test, the count should return 1 self.assertEqual(1, self.sensorData.getCount()) #add any valid value self.sensorData.addValue(140) #average value should return (120 + 140)/2 = 260/2 = 130 self.assertEqual(130, self.sensorData.getAverageValue()) #add an invalid non-numeric value self.sensorData.addValue('blahblahblah') #current value should still remain 140 self.assertEqual(140, self.sensorData.getCurrentValue()) pass """ This test tests the getAverageValue() method of SensorData module. It checks whether the average is being accurately calculated by the method """ def testGetAverageValue(self): #add some valid values self.sensorData.addValue(60) self.sensorData.addValue(90) self.sensorData.addValue(180) #get the average average = self.sensorData.getAverageValue() #check if average value = total value / count self.assertEqual( average, self.sensorData.totalValue / self.sensorData.getCount()) #add invalid values and check if average remains the same self.sensorData.addValue(None) #check if average value = total value / count self.assertEqual( average, self.sensorData.totalValue / self.sensorData.getCount()) """ This test tests the getCount() method of SensorData module. It checks whether the count is incremented properly """ def testGetCount(self): #add some valid values self.sensorData.addValue(30) self.sensorData.addValue(39) self.sensorData.addValue(300) #check if count is 3 self.assertEqual(3, self.sensorData.getCount()) #add an invalid value self.sensorData.addValue('baah') #check if count is still 3 self.assertEqual(3, self.sensorData.getCount()) """ This test tests the getCurrentValue() method of SensorData module. It checks whether the current value is updated properly """ def testGetCurrentValue(self): #add some valid value self.sensorData.addValue(30) #check if current value is 30 self.assertEqual(30, self.sensorData.getCurrentValue()) #add an invalid value self.sensorData.addValue('baah') #check if count is still 30 self.assertEqual(30, self.sensorData.getCurrentValue()) #add another valid value self.sensorData.addValue('60') #check if current value is 30 self.assertEqual(60, self.sensorData.getCurrentValue()) """ This test tests the getMaxValue() method of SensorData module. It checks whether the max value is updated properly """ def getMaxValue(self): #when there are no values it should return none self.assertEqual(None, self.sensorData.getMaxValue()) #add a valid value self.sensorData.addValue('60') #check if max value updates to 60 self.assertEqual(60, self.sensorData.getMaxValue()) #add a large valid value self.sensorData.addValue('90') #check if max value updates to 60 self.assertEqual(90, self.sensorData.getMaxValue()) """ This test tests the getMinValue() method of SensorData module. It checks whether the min value is updated properly """ def getMinValue(self): #when there are no values it should return none self.assertEqual(None, self.sensorData.getMinValue()) #add a valid value self.sensorData.addValue('60') #check if max value updates to 60 self.assertEqual(60, self.sensorData.getMinValue()) #add a small valid value self.sensorData.addValue('-30') #check if min value updates to -30 self.assertEqual(-30, self.sensorData.getMinValue()) """ This test tests the getName() method of SensorData module. It checks whether the the name is being returned properly """ def testGetName(self): #when name is not set, it has been initialized to 'Not Set', check if 'Not Set' self.assertEqual('Not Set', self.sensorData.getName()) #change name self.sensorData.setName("Pallak's Sensor") #check whether the name is now "Pallak's Sensor" self.assertEqual("Pallak's Sensor", self.sensorData.getName()) #check for none self.sensorData.setName(None) #it should return 'Not Set' self.assertEqual('Not Set', self.sensorData.getName()) """ This test tests the setName() method of SensorData module. It checks whether the the name is being updated properly """ def testSetName(self): #change name self.sensorData.setName("Temperature Sensor") #check whether the name is now "Temperature Sensor" self.assertEqual("Temperature Sensor", self.sensorData.getName()) #change to none self.sensorData.setName(None) #check whether the name is now be 'Not Set' self.assertEqual("Not Set", self.sensorData.getName())