Example #1
0
 def test_coro():
     try:
         broker = Broker(broker_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('test_topic', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         client_pub = MQTTClient()
         yield from client_pub.connect('mqtt://127.0.0.1/')
         yield from client_pub.publish('test_topic', data, QOS_0)
         yield from client_pub.disconnect()
         message = yield from client.deliver_message()
         self.assertIsNotNone(message)
         self.assertIsNotNone(message.publish_packet)
         self.assertEqual(message.data, data)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #2
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                sub_client = MQTTClient()
                yield from sub_client.connect('mqtt://127.0.0.1')
                ret = yield from sub_client.subscribe([('+/monitor/Clients', QOS_0)])
                self.assertEqual(ret, [QOS_0])

                yield from self._client_publish('/test/monitor/Clients', b'data', QOS_0)
                message = yield from sub_client.deliver_message()
                self.assertIsNotNone(message)

                yield from self._client_publish('$SYS/monitor/Clients', b'data', QOS_0)
                yield from asyncio.sleep(0.1)
                message = None
                try:
                    message = yield from sub_client.deliver_message(timeout=2)
                except Exception as e:
                    pass
                self.assertIsNone(message)
                yield from sub_client.disconnect()
                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #3
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                sub_client = MQTTClient()
                yield from sub_client.connect('mqtt://127.0.0.1', cleansession=False)
                ret = yield from sub_client.subscribe([('/qos0', QOS_0), ('/qos1', QOS_1), ('/qos2', QOS_2)])
                self.assertEqual(ret, [QOS_0, QOS_1, QOS_2])
                yield from sub_client.disconnect()
                yield from asyncio.sleep(0.1)

                yield from self._client_publish('/qos0', b'data', QOS_0, retain=True)
                yield from self._client_publish('/qos1', b'data', QOS_1, retain=True)
                yield from self._client_publish('/qos2', b'data', QOS_2, retain=True)
                yield from sub_client.reconnect()
                for qos in [QOS_0, QOS_1, QOS_2]:
                    log.debug("TEST QOS: %d" % qos)
                    message = yield from sub_client.deliver_message()
                    log.debug("Message: " + repr(message.publish_packet))
                    self.assertIsNotNone(message)
                    self.assertEqual(message.topic, '/qos%s' % qos)
                    self.assertEqual(message.data, b'data')
                    self.assertEqual(message.qos, qos)
                yield from sub_client.disconnect()
                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #4
0
 def _client_publish(self, topic, data, qos, retain=False):
     pub_client = MQTTClient()
     ret = yield from pub_client.connect('mqtt://127.0.0.1/')
     self.assertEqual(ret, 0)
     ret = yield from pub_client.publish(topic, data, qos, retain)
     yield from pub_client.disconnect()
     return ret
Example #5
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                sub_client = MQTTClient()
                yield from sub_client.connect('mqtt://localhost')
                ret = yield from sub_client.subscribe([('/qos0', QOS_0), ('/qos1', QOS_1), ('/qos2', QOS_2)])
                self.assertEquals(ret, [QOS_0, QOS_1, QOS_2])

                yield from self._client_publish('/qos0', b'data', QOS_0)
                yield from self._client_publish('/qos1', b'data', QOS_1)
                yield from self._client_publish('/qos2', b'data', QOS_2)
                yield from asyncio.sleep(0.1)
                for qos in [QOS_0, QOS_1, QOS_2]:
                    message = yield from sub_client.deliver_message()
                    self.assertIsNotNone(message)
                    self.assertEquals(message.topic, '/qos%s' % qos)
                    self.assertEquals(message.data, b'data')
                    self.assertEquals(message.qos, qos)
                yield from sub_client.disconnect()
                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #6
0
 def test_coro():
     try:
         config = {'auto_reconnect': False}
         client = MQTTClient(config=config)
         yield from client.connect('mqtt://127.0.0.1/')
     except ConnectException as e:
         future.set_result(True)
Example #7
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                client = MQTTClient()
                ret = yield from client.connect('mqtt://127.0.0.1/')
                self.assertEqual(ret, 0)
                yield from client.subscribe([('/topic', QOS_0)])

                # Test if the client test client subscription is registered
                self.assertIn('/topic', broker._subscriptions)
                subs = broker._subscriptions['/topic']
                self.assertEqual(len(subs), 1)
                (s, qos) = subs[0]
                self.assertEqual(s, client.session)
                self.assertEqual(qos, QOS_0)

                yield from client.subscribe([('/topic', QOS_0)])
                self.assertEqual(len(subs), 1)
                (s, qos) = subs[0]
                self.assertEqual(s, client.session)
                self.assertEqual(qos, QOS_0)

                yield from client.disconnect()
                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                MockPluginManager.assert_has_calls(
                    [call().fire_event(EVENT_BROKER_CLIENT_SUBSCRIBED,
                                       client_id=client.session.client_id,
                                       topic='/topic', qos=QOS_0)], any_order=True)
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #8
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://127.0.0.1/')
                self.assertEqual(ret, 0)

                ret_message = yield from pub_client.publish('/topic', bytearray(b'\x99' * 256 * 1024), QOS_2)
                yield from pub_client.disconnect()
                self.assertEqual(broker._retained_messages, {})

                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                MockPluginManager.assert_has_calls(
                    [
                        call().fire_event(EVENT_BROKER_MESSAGE_RECEIVED,
                                          client_id=pub_client.session.client_id,
                                          message=ret_message),
                    ], any_order=True)
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #9
0
 def test_coro():
     try:
         client = MQTTClient()
         yield from client.connect('mqtt://test.mosquitto.org/')
         self.assertIsNotNone(client.session)
         yield from client.disconnect()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #10
0
 def test_coro():
     try:
         client = MQTTClient(config={'check_hostname': False})
         ca = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mosquitto.org.crt')
         yield from client.connect('mqtts://test.mosquitto.org/', cafile=ca)
         self.assertIsNotNone(client.session)
         yield from client.disconnect()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #11
0
def test_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://test.mosquitto.org/')
    tasks = [
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_0')),
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)),
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)),
    ]
    yield from asyncio.wait(tasks)
    logger.info("messages published")
    yield from C.disconnect()
Example #12
0
def test_coro2():
    try:
        C = MQTTClient()
        yield from C.connect('mqtt://test.mosquitto.org:1883/')
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_0', qos=0x00)
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=0x01)
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=0x02)
        logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Example #13
0
 def test_coro():
     try:
         broker = Broker(broker_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('ws://127.0.0.1:8080/')
         self.assertIsNotNone(client.session)
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #14
0
 def test_coro():
     try:
         broker = Broker(broker_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         ca = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mosquitto.org.crt')
         yield from client.connect('ws://127.0.0.1:8081/', cafile=ca)
         self.assertIsNotNone(client.session)
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #15
0
def test_coro():
    try:
        C = MQTTClient()
        yield from C.connect('mqtt://0.0.0.0:1883')
        yield from C.publish('data/classified', b'TOP SECRET', qos=0x01)
        yield from C.publish('data/memes', b'REAL FUN', qos=0x01)
        yield from C.publish('repositories/hbmqtt/master', b'NEW STABLE RELEASE', qos=0x01)
        yield from C.publish('repositories/hbmqtt/devel', b'THIS NEEDS TO BE CHECKED', qos=0x01)
        yield from C.publish('calendar/hbmqtt/releases', b'NEW RELEASE', qos=0x01)
        logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Example #16
0
 def test_coro():
     try:
         client = MQTTClient()
         yield from client.connect('mqtt://test.mosquitto.org/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
         ])
         self.assertEquals(ret[0], QOS_0)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #17
0
 def test_coro():
     try:
         broker = Broker(broker_config,
                         plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         ca = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                           'mosquitto.org.crt')
         yield from client.connect('ws://localhost:8081/', cafile=ca)
         self.assertIsNotNone(client.session)
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #18
0
def test_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://127.0.0.1:1883/')
    tasks = [
        asyncio. async (C.publish('/slack_in', b'TEST MESSAGE WITH QOS_0')),
        asyncio. async (C.publish('/slack_in',
                                  b'TEST MESSAGE WITH QOS_1',
                                  qos=QOS_1)),
        asyncio. async (C.publish('/slack_in',
                                  b'TEST MESSAGE WITH QOS_2',
                                  qos=QOS_2)),
    ]
    yield from asyncio.wait(tasks)
    # logger.info("messages published")
    yield from C.disconnect()
Example #19
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost/')
    yield from C.subscribe([
            ('sputnik/test', QOS_1),
         ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['sputnik/test'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #20
0
def uptime_coro():
    global answer
    try:
        while True:
            answer = ''
            C = MQTTClient()

            yield from C.connect('mqtt://127.0.0.1:8080')
            # Subscribe to '$SYS/broker/uptime' with QOS=1
            yield from C.subscribe([('bot/#', QOS_1)])
            logger.info("Subscribed")
            message = yield from C.deliver_message()
            packet = message.publish_packet
            str = packet.payload.data.decode('utf-8')
            header = packet.variable_header.topic_name.split('/')[1:-1]
            topic = ''
            for s in header:
                topic += s + '/'
            answer = ''
            if str == 'starting':
                asyncio.ensure_future(
                    bot_answer(C, 'game/bot/' + topic, b'makerandompole'))
                asyncio.ensure_future(get_answer(C, 'bot/', topic))
                print('here3')
                answer = ''
            answer = ''
            coord = 0
            if header[len(header) - 1] == 'shoot':
                coord = random_coord()
                send = bytearray(coord + '//' + str, encoding='utf-8')
                asyncio.ensure_future(
                    bot_answer(C, 'game/bot/' + topic + 'checkshoot/', send))
                asyncio.ensure_future(
                    get_answer(C, 'bot/', topic + 'checkshoot/', coord))
                answer = answer.encode('utf-8')

            answer = ''

        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)

    yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
    logger.info("UnSubscribed")

    yield from C.disconnect()
Example #21
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtts://*****:*****@0.0.0.0:8883', cafile='ca.crt')
    yield from C.subscribe([
            ('vaibhavagg2/test', QOS_1),
            ('vaibhavagg2/device2/test', QOS_1)
         ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['a/b', 'test_topic'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #22
0
def brokerGetMessage():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost:9999/')
    yield from C.subscribe([("test", QOS_1)])
    logger.info('Subscribed!')
    try:
        for i in range(1, 100):
            print("---------------------")
            message = yield from C.deliver_message()
            packet = message.publish_packet()
            print(
                f"{i}:  {packet.variable_header.topic_name} => {packet.payload.data}"
            )
            print(packet.payload.data.decode('utf-8'))
    except ClientException as ce:
        logger.error("Client exception : %s" % ce)
Example #23
0
 def test_coro():
     try:
         broker = Broker(broker_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #24
0
def run(arguments):
    global SUBSCRIPTIONS
    readSettings()
    loop_time = int(arguments['--loop-time'])
    retry = True
    while retry:
        C = MQTTClient(
            BASE_TOPIC + "/regler",
            config=CLIENT_CONFIG,
        )
        yield from C.connect(arguments['--uri'])
        yield from C.subscribe([(s[0], QOS_2) for s in SUBSCRIPTIONS])
        try:
            push_state['heat_pump'].setValue(state['heat_pump'])
            yield from C.publish(*push_state['heat_pump'].publish())
            yield from C.publish(*push_state['state'].publish())
            start = time.time()
            while True:
                packet = None
                wait_time = max(loop_time - (time.time() - start), 0)
                logging.debug("wait_time= %s", wait_time)
                try:
                    message = yield from C.deliver_message(timeout=wait_time)
                    packet = message.publish_packet
                except asyncio.TimeoutError:
                    pass
                if packet:
                    executePacket(packet)
                if (time.time() - start) > loop_time:
                    start = time.time()
                    calculateNominal()
                    calulateHeatPumpState()
                    push_state['heat_pump'].setValue(state['heat_pump'])
                    yield from C.publish(*push_state['heat_pump'].publish())
                    yield from C.publish(*push_state['state'].publish())
        except KeyboardInterrupt:
            retry = False
        except ClientException as e:
            logging.exception("Client exception: %s" % e)
        except Exception as e:
            logging.exception("Unknown exception: %s" % e)
        finally:
            yield from C.unsubscribe([s[0] for s in SUBSCRIPTIONS])
            yield from C.disconnect()
        if retry:
            print("retry")
Example #25
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://127.0.0.1:1883/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    # Subscribe to '$SYS/broker/load/#' with QOS=2
    yield from C.subscribe([
            ('/slack_in', QOS_1),
         ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data.decode())))
        yield from C.unsubscribe(['/slack_in'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #26
0
        def test_coro():
            try:
                broker = Broker(broker_config,
                                plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                client = MQTTClient()
                yield from client.connect('ws://*****:*****@127.0.0.1:8080/')
                self.assertIsNotNone(client.session)
                yield from client.disconnect()
                yield from client.reconnect()

                self.assertIsNotNone(client.session.username)
                self.assertIsNotNone(client.session.password)
                yield from broker.shutdown()
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #27
0
 def test_coro():
     try:
         client = MQTTClient()
         yield from client.connect('mqtt://test.mosquitto.org/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
             ('$SYS/broker/uptime', QOS_1),
             ('$SYS/broker/uptime', QOS_2),
         ])
         self.assertEquals(ret[0], QOS_0)
         self.assertEquals(ret[1], QOS_1)
         self.assertEquals(ret[2], QOS_2)
         yield from client.disconnect()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #28
0
 def main(self):
     client = MQTTClient()
     yield from client.connect('mqtt://localhost:1883/')
     for key in self.__registry.keys():
         yield from client.subscribe([{'filter': key, 'qos': 0x00}])
     while True:
         packet = yield from client.deliver_message()
         log.debug("%s : %s" % (packet.variable_header.topic_name, str(packet.payload.data)))
         try:
             #yield from self.getSensor("pressure-main").setValue(float(packet.payload.data))
             self.update(packet.variable_header.topic_name, packet.payload.data)
         except Exception as exception:
             log.exception(exception)
         yield from client.acknowledge_delivery(packet.variable_header.packet_id)
     for key in self.__registry.keys():
         yield from client.unsubscribe([key])
     yield from client.disconnect()
Example #29
0
def run(arguments):
    poll_interval = int(arguments['--interval'])
    # connect to the MQTT brocker
    C = MQTTClient(
        BASE_TOPIC + "/sensorreader",
        config=CLIENT_CONFIG,
    )
    yield from C.connect(arguments['--uri'])
    try:
        for sensor in W1ThermSensor.get_available_sensors():
            logging.debug("Sensor: %s", sensor.id)
        while True:
            start = time.time()
            for name, s in SENSORS.items():
                if 'sensor_client' not in s:
                    try:
                        s['sensor_client'] = W1ThermSensor(
                            W1ThermSensor.THERM_SENSOR_DS18B20,
                            s['id'],
                        )
                        logging.info('[%s] sonsor found' % name)
                    except NoSensorFoundError:
                        logging.error('[%s] sonsor not found' % name)
                        continue
                t = s['sensor_client'].get_temperature()
                if t < s['min'] or t > s['max']:
                    logging.warning("[%s] temp %s outside [%s - %s]" % (
                        name, t, s['min'], s['max']
                    ))
                    continue
                now = datetime.now().replace(microsecond=0)
                data = '{}Z,{}'.format(now.isoformat(), t)
                yield from C.publish(
                    s['topic'],
                    bytes(data, 'utf-8'),
                    qos=QOS_2,
                )
            end = time.time()
            time.sleep(max(0, poll_interval - (end - start)))
    except KeyboardInterrupt:
        pass
    except:
        logging.exception("")
    finally:
        yield from C.disconnect()
Example #30
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())

                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://127.0.0.1/')
                self.assertEqual(ret, 0)
                yield from pub_client.publish('/topic', b'', QOS_0, retain=True)
                yield from pub_client.disconnect()
                yield from asyncio.sleep(0.1)
                self.assertNotIn('/topic', broker._retained_messages)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #31
0
    def recv_mqtt(self):

        C = MQTTClient()
        yield from C.connect('mqtt://' + str(self.arg.server_ip))

        yield from C.subscribe([(self.arg.topic, QOS_1)])
        try:
            while True:
                message = yield from C.deliver_message()
                packet = message.publish_packet
                print("%s" % (str(packet.payload.data).split("'")[1]))
                v = str(packet.payload.data).split("'")[1]
                self.db.writeDB("node1", int(v))

            yield from C.unsubscribe([self.arg.topic])
            yield from C.disconnect()
        except ClientException as ce:
            logger.error("Client exception: %s" % ce)
Example #32
0
 def test_coro():
     try:
         broker = Broker(broker_config,
                         plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #33
0
    def button_coro(self, thingy):
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_BUTTON_UUID), QOS_1)])

            for i in range(10):
                message = yield from C.deliver_message()
                packet = message.publish_packet
                if packet.payload.data:
                    print("Button pressed")
                else:
                    print("Button not pressed")

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_BUTTON_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
Example #34
0
    def light_coro(self, database, thingy, key):
        """
        Get light intensity readings from Thingy and store in database
        """
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_LIGHT_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])

            while True:
                # Remove expires entries in database
                database.del_expired_items(key, datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                color = {
                'red':  packet.payload.data[0],
                'green': packet.payload.data[2],
                'blue': packet.payload.data[4],
                'clear': packet.payload.data[6]
                }
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(color)))

                data = {
                    'color': color,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_LIGHT_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
        
        readings = database.get_set('light_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Example #35
0
        def test_coro():
            try:
                broker = Broker(test_config,
                                plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                sub_client = MQTTClient()
                yield from sub_client.connect('mqtt://localhost',
                                              cleansession=False)
                ret = yield from sub_client.subscribe([('/qos0', QOS_0),
                                                       ('/qos1', QOS_1),
                                                       ('/qos2', QOS_2)])
                self.assertEquals(ret, [QOS_0, QOS_1, QOS_2])
                yield from sub_client.disconnect()
                yield from asyncio.sleep(0.1)

                yield from self._client_publish('/qos0',
                                                b'data',
                                                QOS_0,
                                                retain=True)
                yield from self._client_publish('/qos1',
                                                b'data',
                                                QOS_1,
                                                retain=True)
                yield from self._client_publish('/qos2',
                                                b'data',
                                                QOS_2,
                                                retain=True)
                yield from sub_client.reconnect()
                for qos in [QOS_0, QOS_1, QOS_2]:
                    log.debug("TEST QOS: %d" % qos)
                    message = yield from sub_client.deliver_message()
                    log.debug("Message: " + repr(message.publish_packet))
                    self.assertIsNotNone(message)
                    self.assertEquals(message.topic, '/qos%s' % qos)
                    self.assertEquals(message.data, b'data')
                    self.assertEquals(message.qos, qos)
                yield from sub_client.disconnect()
                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #36
0
class Publisher(object):
    """This class is to connect and publish values of temperature in MQTT server.
        Attribute:
            cliente (Object): An object that represent a connection with MQTT
            dataToSend (int): An integer representing a temperature.
            tasks (generator): An generator representing a task object.

    """

    def __init__(self, args):
        """ This constructor for Publisher """
        self.arg = args
        try:
            self.client = MQTTClient()
        except Exception as e:
            print(e)

    @asyncio.coroutine
    def send_mqtt(self, data):
        """This method is responsible to connect on client   and publish temperature values.
            Parameter:
                data (int): Value of temperature

         """
        self.dataToSend = data

        try:
            yield from self.client.connect('mqtt://' + str(self.arg.server_ip))            
            tasks = [asyncio.ensure_future(self.client.publish(self.arg.topic, bytes(str(self.dataToSend), 'utf-8')))]

            yield from asyncio.wait(tasks)

            # Disconnects the client when finished.
            yield from self.client.disconnect()
        except Exception as e:
            print(e)

    def run(self, recv_generator):
        """This method is responsible to start the process.
            Parameter:
                recv_generator (generator): An generator of connection and publish.

         """
        asyncio.get_event_loop().run_until_complete(recv_generator)
Example #37
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://*****:*****@0.0.0.0:1883')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('data/memes', QOS_1),  # Topic allowed
        ('data/classified', QOS_1),  # Topic forbidden
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #38
0
    def pressure_coro(self, database, thingy, key):
        """
        Get pressure readings from Thingy and store in database
        """
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_PRESS_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])

            while True:
                # Remove expires entries in database
                database.del_expired_items(key, datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                # TODO: check the parsing of pressure data - it seems like wrong values (~180 instead of ~1000)

                integer = packet.payload.data[0]
                decimal = packet.payload.data[4]
                pressure = integer + (decimal / 100.0)
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(pressure)))

                data = {
                    'pressure': pressure,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_PRESS_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
        
        readings = database.get_set('pressure_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Example #39
0
 def test_coro():
     try:
         broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         self.assertTrue(broker.transitions.is_started())
         client = MQTTClient(client_id="", config={'auto_reconnect': False})
         return_code = None
         try:
             yield from client.connect('mqtt://127.0.0.1/', cleansession=False)
         except ConnectException as ce:
             return_code = ce.return_code
         self.assertEqual(return_code, 0x02)
         self.assertNotIn(client.session.client_id, broker._sessions)
         yield from client.disconnect()
         yield from asyncio.sleep(0.1)
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #40
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect(url)
    yield from C.subscribe([(topic, QOS_1), (topic, QOS_2)], )
    logger.info("Subscribed")
    i = 1
    try:
        while i:
            message = yield from C.deliver_message()
            packet = message.publish_packet
            j = json.loads(packet.payload.data.decode())
            print(j)
            #print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
            i = i + 1
        yield from C.unsubscribe([topic, topic])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #41
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                sub_client = MQTTClient()
                yield from sub_client.connect('mqtt://127.0.0.1')
                ret = yield from sub_client.subscribe(
                    [('+', QOS_0), ('+/tennis/#', QOS_0), ('sport+', QOS_0), ('sport/+/player1', QOS_0)])
                self.assertEqual(ret, [QOS_0, QOS_0, 0x80, QOS_0])

                yield from asyncio.sleep(0.1)
                yield from sub_client.disconnect()
                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Example #42
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://test.mosquitto.org/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('$SYS/broker/uptime', QOS_1),
        ('$SYS/broker/load/#', QOS_2),
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #43
0
def mqtt_listener():
    C = MQTTClient()
    yield from C.connect(mqtt_broker)

    yield from C.subscribe([(mqtt_topic, QOS_1)])
    try:
        while True:
            message = yield from C.deliver_message()
            packet = message.publish_packet
            logger.debug(
                "%s => %s" %
                (packet.variable_header.topic_name, str(packet.payload.data)))
            text = packet.payload.data.decode()
            logging.debug(text)
            sign.write_text(text, font_name=display_font)
        yield from C.unsubscribe([mqtt_topic])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #44
0
def test_coro2():
    try:
        C = MQTTClient()
        ret = yield from C.connect('mqtt://127.0.0.1:1883/')
        message = yield from C.publish('/slack_in',
                                       b'TEST MESSAGE WITH QOS_0',
                                       qos=0x00)
        message = yield from C.publish('/slack_in',
                                       b'TEST MESSAGE WITH QOS_1',
                                       qos=0x01)
        message = yield from C.publish('/slack_in',
                                       b'TEST MESSAGE WITH QOS_2',
                                       qos=0x02)
        #print(message)
        # logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        # logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Example #45
0
    def check_conn():
        broker_url = get_test_broker_url()

        if not broker_url:
            logging.warning("Undefined MQTT broker URL")
            raise tornado.gen.Return(False)

        try:
            hbmqtt_client = MQTTClient()
            ack_con = yield hbmqtt_client.connect(broker_url)
            if ack_con != MQTTCodesACK.CON_OK:
                logging.warning(
                    "Error ACK on MQTT broker connection: {}".format(ack_con))
                raise tornado.gen.Return(False)
        except ConnectException as ex:
            logging.warning("MQTT broker connection error: {}".format(ex))
            raise tornado.gen.Return(False)

        raise tornado.gen.Return(True)
Example #46
0
def run(arguments):
    retry = True
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(heatPumpPin, GPIO.OUT)
    GPIO.setup(waterPumpPin, GPIO.OUT)
    GPIO.output(heatPumpPin, HEAT_PUMP_OFF)
    GPIO.output(waterPumpPin, WATER_PUMP_ON)
    while retry:
        C = MQTTClient(
            BASE_TOPIC + "/pumpswitch",
            config=CLIENT_CONFIG,
        )
        yield from C.connect(arguments['--uri'])
        yield from C.subscribe(SUBSCRIPTIONS)
        try:
            while True:
                message = yield from C.deliver_message()
                packet = message.publish_packet
                topic = packet.variable_header.topic_name
                state = packet.payload.data.decode('utf-8').split(',')[-1]
                state = pinStateFromMQTTState(state)
                if state == UNKNOWN:
                    continue
                if topic.endswith('heat_pump'):
                    if state == ON:
                        GPIO.output(heatPumpPin, HEAT_PUMP_ON)
                    else:
                        GPIO.output(heatPumpPin, HEAT_PUMP_OFF)
                    if state == ON:
                        GPIO.output(waterPumpPin, WATER_PUMP_ON)
                elif topic.endswith('water_pump'):
                    if state == ON:
                        GPIO.output(heatPumpPin, WATER_PUMP_ON)
                    else:
                        GPIO.output(heatPumpPin, WATER_PUMP_OFF)
        except KeyboardInterrupt:
            retry = False
        except ClientException as e:
            logging.error("Client exception: %s" % e)
        except:
            yield from C.unsubscribe(SUBSCRIPTIONS)
        finally:
            yield from C.disconnect()
Example #47
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://test.mosquitto.org/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
                ('$SYS/broker/uptime', QOS_1),
                ('$SYS/broker/load/#', QOS_2),
             ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #48
0
def test_coro2():
    try:
        C = MQTTClient()
        ret = yield from C.connect('mqtt://test.mosquitto.org/')
        message = yield from C.publish(TOPIC3,
                                       b'TEST MESSAGE WITH QOS_0',
                                       qos=0x00)
        message = yield from C.publish(TOPIC3,
                                       b'TEST MESSAGE WITH QOS_1',
                                       qos=0x01)
        message = yield from C.publish(TOPIC3,
                                       b'TEST MESSAGE WITH QOS_2',
                                       qos=0x02)
        #print(message)
        logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
def brokerGetMessage():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost:9999/')
    yield from C.subscribe([("LINTANGtopic/test", QOS_1)])
    logger.info('Subscribed!')
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print(packet.payload.data.decode('utf-8'))

            mydb = mymongo['mqttpy']
            mycol = mydb['mqttpy']
            mydata = {"message": packet.payload.data.decode('utf-8')}
            x = mycol.insert_one(mydata)
            print('Data saved!')

    except ClientException as ce:
        logger.error("Client exception : %s" % ce)
Example #50
0
    def gas_coro(self, database, thingy, key):
        """
        Get CO2 readings from Thingy and store in database
        """
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_GAS_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])

            while True:
                # Remove expires entries in database
                database.del_expired_items(key, datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                gas = {
                'eco2': packet.payload.data[0],
                'tvoc': packet.payload.data[2]
                }
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(gas)))

                data = {
                    'gas': gas,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_GAS_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
        
        readings = database.get_set('gas_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Example #51
0
    def temp_coro(self, database, thingy, key):
        """
        Get temperature readings from Thingy and store in database
        """
        
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_TMP_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])
            
            while True:
                # Remove expires entries in database
                database.del_expired_items('key', datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                integer = packet.payload.data[0]
                decimal = packet.payload.data[1]
                temperature = integer + (decimal / 100)
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(temperature)))
                data = {
                    'temperature': temperature,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_TMP_UUID))])
            yield from C.disconnect()

        except ClientException as ce:
            print(ce)

        readings = database.get_set('temperature_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Example #52
0
        def test_coro():
            try:
                broker = Broker(test_config,
                                plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://localhost/')
                self.assertEqual(ret, 0)

                yield from pub_client.publish('/+', b'data', QOS_0)
                yield from asyncio.sleep(0.1)
                yield from pub_client.disconnect()

                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
def uptime_coro(url, cafile):
    C = MQTTClient()
    yield from C.connect(url, cafile=cafile)

    # Subscribe to '$SYS/broker/uptime' with QOS=1
    # Subscribe to '$SYS/broker/load/#' with QOS=2
    yield from C.subscribe([
        ('$SYS/broker/uptime', QOS_1),
        ('$SYS/broker/load/#', QOS_2),
    ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name,
                                     str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Example #54
0
 def test_coro():
     try:
         broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         self.assertTrue(broker.transitions.is_started())
         client = MQTTClient()
         ret = yield from client.connect('mqtt://127.0.0.1/')
         self.assertEqual(ret, 0)
         self.assertIn(client.session.client_id, broker._sessions)
         yield from client.disconnect()
         yield from asyncio.sleep(0.1)
         yield from broker.shutdown()
         self.assertTrue(broker.transitions.is_stopped())
         self.assertDictEqual(broker._sessions, {})
         MockPluginManager.assert_has_calls(
             [call().fire_event(EVENT_BROKER_CLIENT_CONNECTED, client_id=client.session.client_id),
              call().fire_event(EVENT_BROKER_CLIENT_DISCONNECTED, client_id=client.session.client_id)],
             any_order=True)
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Example #55
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())

                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://localhost/')
                self.assertEqual(ret, 0)
                ret_message = yield from pub_client.publish('/topic', b'data', QOS_0, retain=True)
                yield from pub_client.disconnect()
                yield from asyncio.sleep(0.1)
                self.assertIn('/topic', broker._retained_messages)
                retained_message = broker._retained_messages['/topic']
                self.assertEquals(retained_message.source_session, pub_client.session)
                self.assertEquals(retained_message.topic, '/topic')
                self.assertEquals(retained_message.data, b'data')
                self.assertEquals(retained_message.qos, QOS_0)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://*****:*****@0.0.0.0:1883')
    # yield from C.connect('mqtt://0.0.0.0:1883')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('data/memes', QOS_1),  # Topic allowed
        ('data/classified', QOS_1),  # Topic forbidden
        ('repositories/hbmqtt/master', QOS_1),  # Topic allowed
        ('repositories/hbmqtt/devel', QOS_1),  # Topic forbidden
        ('calendar/hbmqtt/releases', QOS_1),  # Topic allowed
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)