def toJsonfromSensor(self, SensorData): data = {} data['name'] = SensorData.name data['avgVal'] = SensorData.avgVal data['maxVal'] = SensorData.getMaxValue() data['minVal'] = SensorData.getMinValue() data['curVal'] = SensorData.getValue() data['timeStamp'] = str(SensorData.timestamp) self.jsonSd = json.dumps(data) outputSd = open('sensordata.txt', 'w') outputSd.write(self.jsonSd) return self.jsonSd
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
def sensorTojson(self, SensorData): data = {}; data['name'] = SensorData.name; data['avgVal'] = SensorData.avgVal; data['maxVal'] = SensorData.getMaxValue(); data['minVal'] = SensorData.getMinValue(); data['curVal'] = SensorData.getValue(); data['timeStamp'] = str(SensorData.timeStamp); data['totVal'] = SensorData.getTotalValue(); data['sampleCount'] = SensorData.getSamplecount(); self.jsonSd = json.dumps(data) outputSd = open('sensedata.txt','w') outputSd.write(self.jsonSd) return self.jsonSd
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
def toJsonFromSensorData(self, sensorData: SensorData.SensorData) -> str: ''' Convert from SensorData instance to JSON ''' #Converting the sensorData to a dictionary jsonData = { "currentValue": sensorData.getCurrentValue(), "totalCount": sensorData.getCount(), "avgValue": sensorData.getAverageValue(), "maxValue": sensorData.getMinValue(), "minValue": sensorData.getMaxValue(), "timestamp": sensorData.timestamp, "name": sensorData.getName() } #dumping the json data and returning it jsonStr = json.dumps(jsonData) #Logging and writing to file self.writeSensorDataToFile("Creating JSON for sensorData" + jsonStr) return jsonStr
class TempSensorEmulatorTask : minTemp = 0 maxTemp = 0 currentTemp = 0 avgTemp = 0 threshold = 5 sensor = None def __init__(self): self.sensor = SensorData(); #Fetch current readings from the sensor def getSensorData(self): self.currentTemp = self.sensor.getCurrentValue() self.minTemp = self.sensor.getMinValue() self.maxTemp = self.sensor.getMaxValue() self.avgTemp = self.sensor.getAverageValue() self.readings = self.sensor.getCount() logging.info("\n \nTemperature: \nTime: "+str(self.sensor.timestamp)+"\ncurrent : "+str(self.currentTemp) +"\nAverage :"+str(self.avgTemp)+"\nSamples :"+str(self.readings)+"\nMin: "+str(self.minTemp)+"\nMax :"+str(self.maxTemp)+"\n") return self.currentTemp #Testing if the threshold has been breached. If breached a mail has been triggered def sendNotification(self): try: self.getSensorData() if(abs(self.currentTemp - self.avgTemp) > self.threshold): logging.info('Current temp exceeds average beyond ' + str(self.threshold) + '. Triggering alert...') mail = SmtpClientConnector() #Creating mail body text data = "Temperature Exceeded Warning!\n \nTemperature: \nTime: "+str(self.sensor.timestamp)+"\ncurrent : "+str(self.currentTemp) +"\nAverage :"+str(self.avgTemp)+"\nSamples :"+str(self.readings)+"\nMin: "+str(self.minTemp)+"\nMax :"+str(self.maxTemp) mail.publishMessage("Temperature Alert Python", data) logging.info('\nMail sent') return True except: #If the mailing fails, the method returns false return False
from labs.common import ConfigConst 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();
from labs.common import ConfigConst 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()
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
import logging 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() '''
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())