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 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
class publisher(): def __init__(self): logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) self.connector = MqttClientConnector() self.datautil = DataUtil() self.broker_address = "broker.hivemq.com" self.port = 1883 self.client_id = "Charmi" self.password = None self.mul = MultiSensorAdaptorTask() '''connecting with mqtt client and defining callbacks on class MqttClientConnector and publushing data after checking topic''' def publish(self): logging.info("Running publisher") client = mqtt.Client("Charmi") client.username_pw_set(self.client_id, self.password) client.connect(self.broker_address, self.port) logging.info("Connected !!!") client.loop_start() while True: #comment this for PING control Packets sleep(2) data = self.datautil.toJsonFromSensorData(self.mul.run()) print(data) client.on_connect = self.connector.on_connect( client, self.mul.run()) client.publish("test", data, 2, True)
class PersistenceUtil(object): #Default Constructor def __init__(self): self.dataUtil = DataUtil() self.redis_connection = redis.Redis(host='localhost', port=6379) self.actuatorDataListener = ActuatorDataListener() self.sensorDataListener = SensorDataListener() ''' Write the actutorData to the DBMS ''' def readActuatorDataToDbms(self): redis_subscribe = self.redis_connection().pubsub() actuatorData_subscribe = redis_subscribe.subscribe("ActuatorData") redis_message = redis_subscribe.getMessage() self.registerActuatorDatatoDbmsListener() return ''' Method to write SensorData to DBMS''' def writeSensorDataToDbms(self, sensorData): json_sensorData = self.dataUtil.toJsonFromSensorData(sensorData) self.redis_connection.pubsub() self.redis_connection.publish("SensorData", json_sensorData) self.registerSensorDataToDbmsListener() return def registerSensorDataToDbmsListener(self): self.sensorDataListener.OnMessage() def registerActuatorDataToDbmsListener(self): self.actuatorDataListener.OnMessage()
def writeSensorToDataDbms(self,SensorData): dbData = DataUtil.toJsonFromSensorData(SensorData) r = redis.StrictRedis(host=self.host, port=self.port, password=self.auth, decode_responses=True) r.set("Sensor"+SensorData.getTimeStamp(),dbData) r.publish("Sensor", "Sensor"+SensorData.getTimeStamp()) #logging.info("Sending data to DB") r.close() return True
def __init__(self, host): self.sensorData = SensorData self.sensorData.addValue(self.sensorData, 23.34) self.data = DataUtil.toJsonFromSensorData(self, self.sensorData) logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) logging.info("Json to send: " + self.data) host, port, self.path = parse_uri(host) self.client = HelperClient(server=(host, port))
def run(self): i=0 logging.info("Connecting to broker") self.mqtt.connect() logging.info("Connecting to broker") while(i<2): logging.info("Publishing data using QoS1") message = DataUtil.toJsonFromSensorData(self.sensorAdaptor.getSensorData()) self.mqtt.publishSensorData(message,1) i+=1 sleep(5) while(i<4): logging.info("Publishing data using QoS2") message = DataUtil.toJsonFromSensorData(self.sensorAdaptor.getSensorData()) self.mqtt.publishSensorData(message,2) i+=1 sleep(10) self.mqtt.clientClose() logging.info("Finished Publishing") return True
def run(self): i = 0 logging.info("Connecting to Server") while (i < 1): logging.info("Publishing data") message = DataUtil.toJsonFromSensorData( self.sensorAdaptor.getSensorData()) self.ccc.send(message) i += 1 sleep(5) logging.info("Finished Publishing") return True
def on_message(self, client, userdata, msg): logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) logging.info("Received Json: " + msg.topic + " " + str(msg.payload)) # Convert the received json data to sensordata instance self.sensorData = SensorData self.sensorData = DataUtil.toSensorDataFromJson( self, str(msg.payload)[1:].lstrip('\'').rstrip('\'')) # Convert the instance to json again data = DataUtil.toJsonFromSensorData(self, self.sensorData) # Log new JSON string. logging.info("The new JSON string: " + data)
def run(self): sensordata = SensorData.SensorData() while True: sense = SenseHat() #generate new temperature data temperature = sense.get_temperature() sensordata.addValue(temperature) #add into log logging.info( "\n---------------------------------\nNew sensor readings:\n" + "name=" + sensordata.name + ",timeStamp=" + sensordata.timeStamp + ",minValue=" + str(sensordata.minValue) + ",aveValue=" + str(sensordata.avgValue) + ",maxValue=" + str(sensordata.maxValue) + ",curValue=" + str(sensordata.curValue) + ",totValue=" + str(sensordata.totValue) + ",sampleCount=" + str(sensordata.sampleCount)) #convert to json format from python object datautil = DataUtil() jsondata = datautil.toJsonFromSensorData(sensordata) if (abs(sensordata.curValue - sensordata.avgValue) > 2): logging.info( "\nCurrent temp exceeds average by >2. Converting data...\n" + "JSON data:\n" + jsondata) #smtp module smtpClientConnector = SmtpClientConnector.SmtpClientConnector() smtpClientConnector.publishMessage("Temperature", jsondata) # logging.info("send email successfully") #write json dta to filesystem of = open("tempData.json", "w+") of.write(jsondata) of.close() # logging.info("write data as JSON file to filesystem successfully") time.sleep(10)
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)
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
def on_disconnect(self, client, userdata, rc): logging.info("disconnecting reason " + str(rc)) def on_message(self, client, userdata, msg): #log the jsondata that the subsriber received logging.info("the second json:\n" + str(msg.payload.decode("utf-8"))) logging.info("message topic=" + str(msg.topic)) logging.info("message qos=" + str(msg.qos)) logging.info("message retain flag=" + str(msg.retain)) self.json = str(msg.payload.decode("utf-8")) #logging.info("the second json:\n" + self.json) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO) mqttSubClientTestApp = MqttSubClientTestApp() mqttSubClientTestApp.client_loop() #if(mqttSubClientTestApp.json!=None): #convert the jsondata to sensedata object dataUtil = DataUtil() #print("json\n"+str(mqttSubClientTestApp.json)) sensordata = dataUtil.toSensorDataFromJson(mqttSubClientTestApp.json) logging.info("sensordata converted from json:" + str(sensordata.getAvgValue())) #convert the sensedata object to jsondata again and log the third jsondata finaljson = dataUtil.toJsonFromSensorData(sensordata) logging.info("the third json:\n" + finaljson)
#creating my instance variable for SensorData class sensorData = SensorData() #adding a new sensordata value sensorData.addValue(10.00) #calling the Coapclient connector coapClient = CoapClientConnector(host, port, path) #ping request coapClient.ping() #get request coapClient.get() #post request coapClient.post(data.toJsonFromSensorData(sensorData)) #add new value to sensor data sensorData.addValue(5.00) #put request coapClient.put(data.toJsonFromSensorData(sensorData)) #delete request coapClient.delete() #stop the Coap client coapClient.stop()
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): #instantiate DataUtil self.dataUtil = DataUtil() 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 null to release any resources self.dataUtil = None pass """ /** * This method tests the toJsonFromActuatorData() of DataUtil class * Checks if two actuatorData instances with same values produce the same * JSONStr */ """ def testActuatorDataToJson(self): #instantiate two actuatorData instances actuatorData1 = ActuatorData() actuatorData2 = ActuatorData() #ceate two actuatorData instances and check if their jsonStr are equal actuatorData1.setName("Temp Actuator") actuatorData2.setName("Temp Actuator") actuatorData1.setCommand("INCREASE") actuatorData2.setCommand("INCREASE") actuatorData1.setValue("UP") actuatorData2.setValue("UP") #get their JSON strings jsonStr1 = self.dataUtil.toJsonFromActuatorData(actuatorData1) jsonStr2 = self.dataUtil.toJsonFromActuatorData(actuatorData2) #check for equality self.assertEqual(jsonStr1, jsonStr2) #pass a non ActuatorData type to write jsonStr1 = self.dataUtil.toJsonFromActuatorData("Hello") #get the actuatorData back from the string passed actuatorData = self.dataUtil.toActuatorDataFromJson(jsonStr1) #the values should be "Not Set: self.assertEqual("Not Set", actuatorData.getCommand()) self.assertEqual("Not Set", actuatorData.getName()) self.assertEqual("Not Set", actuatorData.getValue()) pass """ /** * This method tests the toJsonFromSensorData() of DataUtil class * Checks if two sensorData instances with same values produce the same * JSONStr */ """ 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 """ /** * This method tests writeSensorDataToFile() of DataUtil class. */ """ 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 """ /** * This method tests writeActuatorDataToFile() of DataUtil class. */ """ def testwriteActuatorDataToFile(self): #create sensorData object actuatorData = ActuatorData() #add a value actuatorData.setName("Testinng") #write to file and assert True self.assertEqual(True, self.dataUtil.writeActuatorDataToFile(actuatorData)) pass """ /** * This method tests the toActuatorDataFromJson() of DataUtil class * Checks if the actuatorData instances created from JSONString are equivalent in values * and if they have the same data type */ """ def testJsonToActuatorData(self): #Create actuatorData actuatorData = ActuatorData() #Set some command, name and value actuatorData.setName("Temp Actuator") actuatorData.setCommand("INCREASE") actuatorData.setValue("UP") #convert to JSON jsonStr = self.dataUtil.toJsonFromActuatorData(actuatorData) #convert back to ActuatorData actuatorDataTest = self.dataUtil.toActuatorDataFromJson(jsonStr) #test if their variables are equal self.assertEqual("Temp Actuator", actuatorDataTest.getName()) self.assertEqual("INCREASE", actuatorDataTest.getCommand()) self.assertEqual("UP", actuatorDataTest.getValue()) """ /* * Set the variable to a double value, check if the conversion to JsonStr and back * to ActuatorData value remains of double type */ """ #Set some command, name and double value actuatorData.setName("Temp Actuator") actuatorData.setCommand("INCREASE") actuatorData.setValue(6.0) #convert to JSON jsonStr = self.dataUtil.toJsonFromActuatorData(actuatorData) #convert back to ActuatorData actuatorDataTest = self.dataUtil.toActuatorDataFromJson(jsonStr) #test if their variables are equal self.assertEqual("Temp Actuator", actuatorDataTest.getName()) self.assertEqual("INCREASE", actuatorDataTest.getCommand()) self.assertEqual(6.0, actuatorDataTest.getValue()) """ /** * This method tests the toSensorDataFromJson() of DataUtil class * Checks if the sensorData instances created from JSONString are equivalent in values * and if they have the same data type */ """ 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)