''' 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 Function is used to publish the JSON data to the MQTT broker through the MQTT ClientConnector class @param topic: Topic of the message @param jsonData: It is the JSON Payload @param host: It is the address of the MQTT broker ''' pub_client.publish(topic,jsonData,host)
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 pubclient.publish(host, topic, jsondata)