Esempio n. 1
0
    def client_sub(self):
        client = mqtt.Client("sub_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)

        #subscribe topic from the broker
        mqttClientConnector.subscribeToTopic(client, topic)
        client.loop_forever()
Esempio n. 2
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()
 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) 
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. 5
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
Esempio n. 6
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())