Esempio n. 1
0
    def setUp(self):

        #initialize the modules in Module 6
        self.deviceDataManager = DeviceDataManager()
        self.mqttClientConnector = MqttClientConnector()
        self.multiSensorAdaptor = MultiSensorAdaptor()
        self.tempSensorAdaptorTask = TempSensorAdaptorTask()
 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
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
Esempio n. 4
0
 def __init__(self):
     '''
     Constructor
     '''
     Thread.__init__(self)
     self.temp_topic = "/v1.6/devices/smart_home/temp-act/lv"
     self.led = False
     self.message = None
     self.brightness = 0
     self.actuator = ActuatorData()
     self.set = Settings()
     self.sensor = SensorData()
     self.temp_mqtt = MqttClientConnector(self.temp_topic)
     self.temp_mqtt.subscribe(self.temp_topic)
Esempio n. 5
0
class ActuatorEmulator(Thread):
    '''
    This class is used to send signal to actuator every 60 seconds and
    subscribe to actuator signal from cloud
    '''
    def __init__(self):
        '''
        Constructor
        '''
        Thread.__init__(self)
        self.temp_topic = "/v1.6/devices/smart_home/temp-act/lv"
        self.led = False
        self.message = None
        self.brightness = 0
        self.actuator = ActuatorData()
        self.set = Settings()
        self.sensor = SensorData()
        self.temp_mqtt = MqttClientConnector(self.temp_topic)
        self.temp_mqtt.subscribe(self.temp_topic)

    '''
    This thread is used to collect values from cloud using mqtt
    Based on given conditions, will send signal to actuator through sensehat
    Thread runs once every 60 seconds
    '''

    def run(self):
        while True:
            print("Temperature Actuator Value: " +
                  str(self.temp_mqtt.message()))
            if self.temp_mqtt.message(
            ) == 30 or self.sensor.temp_avg < self.sensor.temp_set:
                self.led = self.actuator.setHeater()
            elif self.sensor.temp_avg > self.sensor.temp_set or self.temp_mqtt.message(
            ) == 16:
                self.led = self.actuator.setCooler()
            else:
                None

            if self.sensor.humid_avg < self.sensor.humid_set:
                self.led = self.actuator.setHumid()
            else:
                self.led = self.actuator.resetHumid()

            self.brightness = self.actuator.setlightBrightness(0)

            if self.set.status == 1:
                self.actuator.setMessage(self.message)

            sleep(60)
Esempio n. 6
0
class DeviceDataManager(object):
    '''
    The manager for the device responsible for creating 
    the MqttClientConnector to be used for this Module
    Also responsible for starting the MultiSensorAdaptor thread
    '''
    #instantiate the modules
    mqttClientConnector = MqttClientConnector()
    multiSensorAdaptor = MultiSensorAdaptor()

    #empty constructor as we do not want to initialize anything during instantiation
    def __init__(self):
        '''
        Constructor
        '''

    """
    Method that passes its own reference MqttClientConnector to MultiSensorAdaptor
    and starts the MultiSensorAdaptor's thread so that it can get SensorData 
    """

    def run(self):

        #set the mqtt client of the MultiSensorAdaptor to the current MqttClientConnector reference
        self.multiSensorAdaptor.setMqttClient(self.mqttClientConnector)

        #enable the fetcher of adaptor
        self.multiSensorAdaptor.enableFetcher = True

        #start
        self.multiSensorAdaptor.start()
 def client_pub(self):
     client = mqtt.Client("pub_py")
     mqttClientConnector = MqttClientConnector(client,True,rootCertPath)
     #set the callback methods
     client.on_connect = self.on_connect
     client.on_message = self.on_message
     client.on_disconnect = self.on_disconnect
     #connect to the broker
     mqttClientConnector.connect(client)
     while True:
         #generate temperature 
         temperature = random.uniform(0.0,45.0)
         logging.info("current temperature:" + str(temperature))
         #publish the current temperature to ubidots
         client.publish(topic, temperature, 1, True) 
         logging.info("published successfully")
         sleep(5) 
    def client_sub(self):
        client = mqtt.Client("sub_py")
        mqttClientConnector = MqttClientConnector(client, True, rootCertPath)

        #connect to the broker
        mqttClientConnector.connect(client)

        #subscribe topic from the broker
        #mqttClientConnector.subscribeToTopic(client,topicAirconditioner)
        #client.subscribe(topicAirconditioner, 1)

        #set the callback methods
        client.on_connect = self.on_connect
        client.on_message = self.on_message
        client.on_disconnect = self.on_disconnect

        client.loop_forever()
Esempio n. 9
0
class MqttSubClientTestApp(object):
    address = '127.0.0.1'
    timeout = 30
    topic = "test"
    qos = 2
    time = 65

    connector = MqttClientConnector()
    connector.client.connect(address, timeout)
    connector.on_subscribe("topic", qos)
    connector.keep_listen(time)
    connector.disconnect(topic)
Esempio n. 10
0
 def client_loop(self):
     client = mqtt.Client("sub_py")
     mqttClientConnector = MqttClientConnector()
     #set the callback methods
     client.on_connect = self.on_connect
     client.on_message = self.on_message
     client.on_disconnect = self.on_disconnect
     #connect to the broker
     mqttClientConnector.connect(client)
     client.loop_start()
     #subscribe topic from the broker
     mqttClientConnector.subscribeToTopic(client, "test")
     sleep(5)
     mqttClientConnector.disconnect(client)
     client.loop_stop()
class MqttPubClientTestApp(object):
    sensorData = SensorData
    sense = SenseHat()
    curDgree = sense.get_temperature()
    sensorData.addValue(sensorData, curDgree)
    dataUtil = DataUtil
    msg = dataUtil.toJsonFromSensorData(dataUtil, sensorData)
    logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
                        level=logging.DEBUG)
    logging.info('Message converted to Json: \n' + str(msg))

    connector = MqttClientConnector()
    connector.client.on_connect = connector.on_connect
    #     connector.client.on_message = connector.on_message
    connector.on_publish("test", msg, 2)
    print("Message published!")
Esempio n. 12
0
class DeviceDataManager:
    #Default Constructor
    def __init__(self):
        self.sensorAdaptor = MultiSensorAdaptor()
        self.mqtt = MqttClientConnector()
        
    # Method execution block
    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
    
    #Method for evaluating the sensor values and create decision for actuation  
    def handleActuatorData(self,SensorData):
        self.actuator.max_value = SensorData.max_value
        self.actuator.min_value = SensorData.min_value
        self.actuator.readings_number = SensorData.readings_number
        self.actuator.value  = SensorData.getCurrentValue()
        self.actuator.avgTemp = (SensorData.total_value / SensorData.readings_number)
        self.actuator.total_value = SensorData.total_value
        self.actuator.setName(SensorData.getName())      
        self.actuatorOP.updateActuator(self.actuator)
        return True
'''
Created on Feb 5, 2020 

@author: sk199
'''
import logging
from time import sleep
from labs.module06.MqttClientConnector import MqttClientConnector
from labs.module06.TempSensorAdaptorTask import TempSensorAdaptorTask

#from labs.common.SensorDataListener import SensorDataListener

logging.getLogger().setLevel(logging.INFO)
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
                    level=logging.DEBUG)
logging.info("Starting temperature sensor adaptor daemon thread...")

mqttClient = MqttClientConnector()
mqttClient.run()

while (True):
    sleep(10)
    pass
Esempio n. 14
0
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):

        #initialize the modules in Module 6
        self.deviceDataManager = DeviceDataManager()
        self.mqttClientConnector = MqttClientConnector()
        self.multiSensorAdaptor = MultiSensorAdaptor()
        self.tempSensorAdaptorTask = TempSensorAdaptorTask()

    """
	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 references for the modules in Module 6 to None to release any resources
        self.deviceDataManager = None
        self.mqttClientConnector = None
        self.multiSensorAdaptor = None
        self.tempSensorAdaptorTask = None

    """
	This method tests the connect() method of the MqttClientConnector
	It checks for successful connection when the correct host and port are given 
	and if the program crashes if incorrect port/host is given
	"""

    def testConnect(self):

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

        #Give it time to connect
        sleep(1)

        #Assert isConnected is True for successful connection
        self.assertEqual(self.mqttClientConnector.client.is_connected(), True)

        #Call the connect method of MqttClientConnector with invalid host
        self.mqttClientConnector.connect("broker.hivemqqqq.com", 1883)

        #Assert isConnected for failure to connnect
        self.assertEqual(self.mqttClientConnector.client.is_connected(), False)

    """
	This method tests the testPublishSensorCommand() method of the MqttClientConnector
	It checks for false when failure to publish (due to no connection), and true when 
	publishes successfully
	"""

    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))

    """
	This method tests the testPublishActuatorCommand() method of the MqttClientConnector
	It checks for false when failure to publish (due to no connection), and true when 
	publishes successfully
	"""

    def testPublishActuatorCommand(self):

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

        #Let it connect
        sleep(2)

        #Create ActuatorData object and add a valid command
        actuatorData = ActuatorData()
        actuatorData.setCommand("Test Command")

        #Publish to topic and assert true for successful publishing
        self.assertEqual(
            True,
            self.mqttClientConnector.publishActuatorCommand(actuatorData, 2))

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

        #Let it connect
        sleep(2)

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

        #Pass a null to method and assert False for failure to publish
        self.assertEqual(
            False, self.mqttClientConnector.publishActuatorCommand(None, 2))

    """
	This method tests the testSubscribeToActuatorCommands() method of the MqttClientConnector
	It checks for false when failure to subscribe(due to no connection), and true when 
	subscribes successfully
	"""

    def testSubscribeToActuatorCommands(self):

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

        #Let it connect
        sleep(2)

        #Subscribe to topic and assert true for successful subscription
        self.assertEqual(
            True,
            self.mqttClientConnector.subscribeToActuatorCommands(
                1, "TestingTopic"))

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

        #Let it connect
        sleep(2)

        #Publish to topic and assert False for failure to subscribe
        self.assertEqual(
            False,
            self.mqttClientConnector.subscribeToActuatorCommands(
                1, "TestingTopic"))

    """
	This method tests the testSubscribeToActuatorCommands() method of the MqttClientConnector
	It checks for false when failure to subscribe(due to no connection), and true when 
	subscribes successfully
	"""

    def testSubscribeToSensorCommands(self):

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

        #Let it connect
        sleep(2)

        #Subscribe to topic and assert true for successful subscription
        self.assertEqual(
            True,
            self.mqttClientConnector.subscribeToSensorCommands(
                1, "TestingTopic"))

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

        #Let it connect
        sleep(2)

        #Publish to topic and assert False for failure to subscribe
        self.assertEqual(
            False,
            self.mqttClientConnector.subscribeToSensorCommands(
                1, "TestingTopic"))

    """
	This method tests the setMqttClient() method of the MultiSensorAdaptor
	It checks for false when sent a null instead of a reference of type MqttClientConnector, and true when 
	appropriate reference type passed
	"""

    def testSetMqttClientConnector(self):

        #Set a valid reference and assert True for successful assignment
        self.assertEqual(False, self.multiSensorAdaptor.setMqttClient(None))

        #Set an invalid reference and assert False for failure too assign
        self.assertEqual(
            True,
            self.multiSensorAdaptor.setMqttClient(self.mqttClientConnector))

    """
	This method tests the start() method of the MultiSensorAdaptor
	It checks for false if the number of readings needed is 0 
	or if fetcher is not enabled. Checks true if the readings are taken
	"""

    def testStart(self):

        #Check for false when there is no reference to MQTT client connector
        self.assertEqual(False, self.multiSensorAdaptor.start())

        #Set the MQTT client connector reference to the current reference
        self.multiSensorAdaptor.setMqttClient(self.mqttClientConnector)

        #Enable the fetcher
        self.multiSensorAdaptor.enableFetcher = True

        #Change numReadings to a small finite value to check
        self.multiSensorAdaptor.numReadings = 1

        #Change sleep time (rateInSec) to a small amount
        self.multiSensorAdaptor.rateInSec = 1

        #Run when numReadings > 0 and adaptor is enabled, assert True for readings were taken
        self.assertEqual(True, self.multiSensorAdaptor.start())

        #Change numReadings to 0
        self.multiSensorAdaptor.numReadings = 0

        #Run when numReadings = 0 and fetcher is enabled, should return false because readings weren't taken
        self.assertEqual(False, self.multiSensorAdaptor.start())

        #Disable the fetcher
        self.multiSensorAdaptor.enableFetcher = False

        #Change readings to > 0
        self.multiSensorAdaptor.numReadings = 1

        #run when numReadings > 0 and Fetcher is disabled, should return false because readings weren't taken
        self.assertEqual(False, self.multiSensorAdaptor.start())
Esempio n. 15
0
'''
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)
        
Esempio n. 16
0
'''
Created on Feb 6, 2020
@author: Naveen Rajendran
'''
from labs.common.SensorData import SensorData
from sense_hat import SenseHat
import threading
import time
from labs.module06.MqttClientConnector import MqttClientConnector
data_object = SensorData()  # class object
sense_hat = SenseHat()  # class object
mqtt = MqttClientConnector()
'''
* This class polls temperature sensor data from sense hat via its API  
'''


class TempSensorAdaptorTask(threading.Thread):
    '''      
    * Constructor function which sets daemon of TempSensorAdaptorTask thread to true 
    '''
    data_object.set_sensor_name("Temperature Sensor")

    def __init__(self, max_sample):
        threading.Thread.__init__(self)  # Invoking Thread Function
        TempSensorAdaptorTask.setDaemon(self, True)
        self.max_sample = max_sample

    '''      
    * This function uses sensehat function to extract temperature data and returns
    '''
Esempio n. 17
0
class MultiSensorAdaptor(threading.Thread):
    '''
    The MultiSensorAdaptor gets the temperature from the TempSensorAdaptorTask. It
    gets the amount of reading at a frequency indicated during instantiation
    '''
    #Instantiate TempSensorAdaptorTask
    tempSensorAdaptorTask = TempSensorAdaptorTask()
    
    #Instantiate MqttClientConnector
    mqttClientConnector = MqttClientConnector()
    
    #Disable the fetcher initially
    enableFetcher = False

    """
    The constructor is used to set the readings (numReadings) and the 
    frequency of readings (rateInSec) if provided, else defaults to 10 and 5 respectively
    """
    def __init__(self, numReadings = 10, rateInSec = 5):
        '''
        Constructor
        '''
        #Initialize the thread
        threading.Thread.__init__(self)
        
        #If provided numReadings and rateInSec
        self.numReadings = numReadings
        self.rateInSec = rateInSec
    
    """    
    This method takes in a MqttClientConnector reference and assigns it to its own
    MqttClientConnector
    """
    def setMqttClient(self, mqttClientConnector):
        
        #Check if the parameter passed is of the type mqttClientConnector, only set it then
        if(type(mqttClientConnector) == MqttClientConnector):
    
            #Set the reference of mqttClientConnector
            self.mqttClientConnector = mqttClientConnector
            
            #Return True for successful assignment
            return True
        
        #if its of any other type besides MqttClientConnector
        else:
            
            #return False for failure to assign
            return False
    
    """    
    This method polls the TempSensorAdaptor task to get the SensorData from it,
    it then calls the MQTTClientConnector to publish it MQTT
    """    
    def start(self):
        
        #Only run if there is a valid reference to mqttClientConnector and setMqttClientConnector has been called first
        if(self.mqttClientConnector!=None):
        
            #Connect the MQTT client
            self.mqttClientConnector.connect("broker.mqttdashboard.com", 1883)
            
            #Sleep for 1 second to let it connect
            sleep(1)
        
            #Data is not fetched if only 0 readings set:
            if self.numReadings == 0:
                    
                #Return false because fetcher didn't run 
                return False
                
            #Run the loop as many times as indicated in the numReadings variable
            while self.numReadings > 0:
                    
                #If the fetcher is enabled
                if self.enableFetcher:
                        
                    #Get the sensorData from the task
                    sensorData = self.tempSensorAdaptorTask.getTemperature()
                            
                    #Publish data to MQTT
                    self.mqttClientConnector.publishSensorCommand(sensorData, 2)
                        
                    #Decrement the number of readings by 1
                    self.numReadings -= 1
                    
                    #Sleep for time specified by user
                    sleep(self.rateInSec)
                        
                #If fetcher is disabled    
                else: 
                        
                    #Return false to indicate no readings taken
                    return False
                 
            #Disconnect from MQTT once done publishing all SensorData
            self.mqttClientConnector.client.disconnect()
                
            #Stop the MQTT loop that listens for MQTT events
            self.mqttClientConnector.client.loop_stop()
                
            #Fetcher is done running, return true to indicate readings were taken   
            return True
            
        #If MQTT client not connected        
        else:
                
            #Return false to indicate no readings were taken
            return False     
Esempio n. 18
0
    Setting values for Topic and address for MQTT broker
'''
topic = "Temperature Sensor"
config = ConfigUtil('../../../config/ConnectedDevicesConfig.props');
host = config.getProperty(ConfigConst.MQTT_GATEWAY_SECTION, ConfigConst.HOST_KEY)


'''

'''


'''
    Construct objects
'''
connector = MqttClientConnector(topic)
connector.daemon = True
print("Starting system performance application daemon thread...")


### Create an object for sensor data
##  call the function 
## PAss JSon data into the function

connector.subscribe(host)
time.sleep(3)
print("Ready for receiving data")

msg =connector.message()  

logging.debug('JSon Data Received:')
Esempio n. 19
0
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
pubclient.publish(host, topic, jsondata)
Created on Mar 5, 2019
Simple Python script for MQTT Subscriber Client
@author: Shyama Sastha Krishnamoorthy Srinivasan
'''

import logging
from labs.common import ConfigConst
from labs.common.ConfigUtil import ConfigUtil
from labs.common.DataUtil import DataUtil
from labs.module06.MqttClientConnector import MqttClientConnector

#Setting values for Topic and address for MQTT broker
topic = "Temperature Sensor"
config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
host = config.getProperty(ConfigConst.MQTT_GATEWAY_SECTION,
                          ConfigConst.HOST_KEY)

subscribe = MqttClientConnector(topic)
subscribe.subscribe(host)  # Connecting to MQTT Broker
msg = subscribe.message()  # Subscribing to required topic
logging.debug('\nJSon Received: ')
print("\nReceived Json data: \n" + str(msg))

data = DataUtil()
sensorData = data.jsonTosensor(msg)  # Converting Jsondata to Sensordata
logging.debug('\nJson in "SensorData format": ')
print("\nMessage received in 'SensorData format': \n" + str(sensorData) + "\n")

jsondata = data.sensorTojson(sensorData)  # Converting Jsondata to Sensordata
logging.debug('\nBack to Json: ')
print("\nMessage converted back to Json: \n" + str(jsondata) + "\n")
Esempio n. 21
0
from labs.common import ConfigConst
from labs.common.DataUtil import DataUtil
from labs.common.ConfigUtil import ConfigUtil
from labs.module06.MqttClientConnector import MqttClientConnector
'''
Setting the values for Topic and address for the MQTT broker
'''
topic = "Temperature Sensor"
config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
host = config.getProperty(ConfigConst.ConfigConst.MQTT_CLOUD_SECTION,
                          ConfigConst.ConfigConst.HOST_KEY)
'''
Connecting to the MQTT Broker and Subscribing to a specified topic
'''
subscribe = MqttClientConnector(topic)
subscribe.subscribe(host)
msg = subscribe.message()
logging.debug('JSON Data Received: ')
print("Json Data Received: " + "\n" + str(msg) + "\n")
'''
Converting the JSON data into Sensor Data
'''
data = DataUtil()
sensor = data.jsonToSensorData(msg)
logging.debug('Json data converted into SensorData')
print("Received SensorData format message " + str(sensor))
'''
Converting the Sensor data to JSON data again
'''
json = data.SensorDataToJson(sensor)
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 = sensor.toJSon()
logging.info('SensorData converted into Json:')
print("SensorData in Json Format before publishing\n" + str(json_data) + "\n")

# pub_client = MqttClientConnector();
'''
    Construct objects
'''
connector = MqttClientConnector()
connector.daemon = True
print("Starting system performance application daemon thread...")
'''
    Run thread
'''
brokers_out = {"broker2": "test.mosquitto.org"}
print(brokers_out)
print("brokers_out is a ", type(brokers_out))
print("broker 2 address = ", brokers_out["broker2"])

# data_out=json.dumps(brokers_out)# encode oject to JSON
# print("\nConverting to JSON\n")
# print ("data -type ",type(data_out))
# print ("data out =",data_out)
# #At Receiver
Esempio n. 23
0
 def __init__(self):
     self.sensorAdaptor = MultiSensorAdaptor()
     self.mqtt = MqttClientConnector()