Beispiel #1
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)
Beispiel #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())
                client = MQTTClient()
                ret = yield from client.connect('mqtt://localhost/')
                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.assertEquals(len(subs), 1)
                (s, qos) = subs[0]
                self.assertEquals(s, client.session)
                self.assertEquals(qos, QOS_0)

                yield from client.subscribe([('/topic', QOS_0)])
                self.assertEquals(len(subs), 1)
                (s, qos) = subs[0]
                self.assertEquals(s, client.session)
                self.assertEquals(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)
Beispiel #3
0
def start_client():
    """
    Connect to MQTT broker and subscribe to node check resource.
    """
    global __LED_VALUE__
    mqtt_client = MQTTClient()
    yield from mqtt_client.connect(MQTT_URL)

    # Subscribe to 'gateway/check' with QOS=1
    yield from mqtt_client.subscribe([('gateway/{}/discover'.format(NODE_ID),
                                       QOS_1)])
    yield from mqtt_client.subscribe([('gateway/{}/led/set'.format(NODE_ID),
                                       QOS_1)])
    asyncio.get_event_loop().create_task(send_check(mqtt_client))
    asyncio.get_event_loop().create_task(send_values(mqtt_client))

    while True:
        try:
            logger.debug("Waiting for incoming MQTT messages from gateway")
            # Blocked here until a message is received
            message = yield from mqtt_client.deliver_message()
        except ClientException as ce:
            logger.error("Client exception: {}".format(ce))
            break
        except Exception as exc:
            logger.error("General exception: {}".format(exc))
            break

        packet = message.publish_packet
        topic_name = packet.variable_header.topic_name
        data = packet.payload.data.decode()
        logger.debug("Received message from gateway: {} => {}".format(
            topic_name, data))

        if topic_name.endswith("/discover"):
            if data == "resources":
                topic = 'node/{}/resources'.format(NODE_ID)
                value = json.dumps(list(NODE_RESOURCES.keys())).encode()
                asyncio.get_event_loop().create_task(
                    publish(mqtt_client, topic, value))
            else:
                for resource in NODE_RESOURCES:
                    topic = 'node/{}/{}'.format(NODE_ID, resource)
                    value = NODE_RESOURCES[resource]['value']
                    msg = json.dumps({'value': value()})
                    asyncio.get_event_loop().create_task(
                        publish(mqtt_client, topic, msg))
        elif topic_name.endswith("/led/set"):
            LED_VALUE = data
            topic = 'node/{}/led'.format(NODE_ID)
            data = json.dumps({'value': data}, ensure_ascii=False)
            asyncio.get_event_loop().create_task(
                publish(mqtt_client, topic, data.encode()))
        else:
            logger.debug("Topic not supported: {}".format(topic_name))
Beispiel #4
0
def uptime_coro():

    try:
        while True:
            C = MQTTClient()

            yield from C.connect('mqtt://127.0.0.1:8080')
            # Subscribe to '$SYS/broker/uptime' with QOS=1
            yield from C.subscribe([
                ('bd/#', QOS_1),

            ])
            logger.info("Subscribed")
            message = yield from C.deliver_message()
            packet = message.publish_packet
            get_request = packet.payload.data
            header = packet.variable_header.topic_name.split('/')
            if  get_request == b'bot':
                print("%d: %s => %s" % (1, packet.variable_header.topic_name, str))
                db_maybe.bot_session(C, packet.variable_header.topic_name, packet.payload.data)
            if header[1] == 'two':
                print("%d: %s => %s" % (1, packet.variable_header.topic_name, str))
                db_maybe.two_players_session(C, packet.variable_header.topic_name, 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)

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

    yield from C.disconnect()
Beispiel #5
0
def get_data():
    C = MQTTClient(config=config)
    yield from C.connect(server_address)
    yield from C.subscribe([('/comReq/' + building_id, QOS_1),
                            ('/opi/' + building_id, QOS_1),
                            ('/name/' + building_id, QOS_1)])
    logger.info('---Listener is subscribing---')
    try:
        while (True):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            topic = packet.variable_header.topic_name
            # 这个data就是你接受到的内容
            data = packet.payload.data
            data = eval(data)
            print(type(topic))
            print(topic)
            print(type(data))
            print(data)

            out = []
            out.append(topic)
            out.append(data)

            return out

    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
    finally:
        yield from C.disconnect()
Beispiel #6
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)
Beispiel #7
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)
Beispiel #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())
                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)
Beispiel #9
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('LINTANGtopic/test', 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)))
            # print(packet.payload.data)
            # print(str(packet.payload.data))
            print(packet.payload.data.decode("utf-8"))
            mydb = myclient["mqtt_lintang"]
            mycol = mydb["mqtt"]
            mydata = {"message": packet.payload.data.decode("utf-8")}
            x = mycol.insert_one(mydata)
            print('Data tersimpan!')
        # 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)
Beispiel #10
0
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'))

            con = pymysql.connect(host='localhost',
                                  user='******',
                                  password='******',
                                  db='mqttpy',
                                  cursorclass=pymysql.cursors.DictCursor)
            kursor = con.cursor()
            sql = '''insert into mqttpy (message) values (%s)'''
            val = str(packet.payload.data.decode('utf-8'))
            kursor.execute(sql, val)
            con.commit()
            print(kursor.rowcount, 'Data saved!')

    except ClientException as ce:
        logger.error("Client exception : %s" % ce)
Beispiel #11
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://krzyzak.duckdns.org/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('test/#', QOS_1),
        ('stacja/#', QOS_2),
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet 
            pub = str(packet.payload.data.decode('utf-8'))
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data.decode('utf-8'))))
            if (pub == 'siema'):
              task = [asyncio.create_task(C.publish('a/b', b'TEST MESSAGE WITH QOS_0', qos=0x00)),
                      asyncio.create_task(C.publish('a/c', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)),
                      asyncio.create_task(C.publish('a/d', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)),]
              yield from asyncio.wait(task)

        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)
Beispiel #12
0
def uptime_coro():
    C = MQTTClient()
    try:
        #Change IP address to the broker/server IP
        yield from C.connect('mqtt://localhost')
        #Edit here for what lora cards you want to receive data from.
        yield from C.subscribe([('lora/' + DEVeui[0] + '/down', QOS_1),
                                ('lora/' + DEVeui[1] + '/down', QOS_1)])

        while True:
            try:
                message = yield from C.deliver_message()
                packet = message.publish_packet
                print("%s => %s" % (packet.variable_header.topic_name,
                                    str(packet.payload.data)))
                decode = json.loads(packet.payload.data)
                handle_packet(decode, packet.variable_header.topic_name)
            except MQTTException:
                logger.debug("Error reading packet")

        #yield from C.unsubscribe(['lora/86-78-00-00-00-00-86-00/down']) #Might be unnessessary
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
        yield from C.disconnect()
    except KeyboardInterrupt:
        yield from C.disconnect()
Beispiel #13
0
def run(arguments):
    alive = True
    while alive:
        C = MQTTClient(
            "hassio/test",
            config=CLIENT_CONFIG,
        )
        yield from C.connect(arguments['--uri'])
        yield from C.subscribe(SUBSCRIPTIONS)
        for settings in HANDLERS.values():
            if settings['active']:
                yield from publishConfig(C, settings)
        try:
            while True:
                message = yield from C.deliver_message()
                packet = message.publish_packet
                topic = packet.topic_name
                if topic in HANDLERS:
                    settings = HANDLERS[topic]
                    yield from settings['handler'](settings, C, packet)
                    row = packet.payload.data.decode('utf-8').split(',', 1)
                    print(packet.topic_name, row)
        except KeyboardInterrupt:
            alive = False
        except ClientException as ce:
            print("Client exception: %s" % ce)
            yield from C.unsubscribe([s[0] for s in SUBSCRIPTIONS])
        finally:
            yield from C.disconnect()
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('LINTANGtopic/test', 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)))
            # print(packet.payload.data)
            # print(str(packet.payload.data))
            print(packet.payload.data.decode("utf-8"))
            con = pymysql.connect(host='localhost',
                                  user='******',
                                  password='******',
                                  db='mqtt_lintang',
                                  cursorclass=pymysql.cursors.DictCursor)
            kursor = con.cursor()
            sql = '''insert into mqtt (message) values (%s)'''
            val = str(packet.payload.data.decode("utf-8"))
            kursor.execute(sql, val)
            con.commit()
            print(kursor.rowcount, "Data tersimpan!")
        # 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)
Beispiel #15
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost/')
    # Subscribe to '/vjoy/#' with QOS=2
    yield from C.subscribe(myoptions)
    logger.info("Subscribed")
    try:
        mybool = True
        while True:
            message = yield from C.deliver_message()
            packet = message.publish_packet
            # Work starts here
            jstr = json.loads(packet.payload.data.decode("utf-8"))
            if jstr['type'] == "j":
                print("%s => %d => %d" %
                      (jstr['type'], getattr(
                          pyvjoy, jstr['index']), int(jstr['value'])))
                j.set_axis(getattr(pyvjoy, jstr['index']), int(jstr['value']))
                pass
            elif jstr['type'] == "b":
                print("%s => %s => %d" %
                      (jstr['type'], jstr['index'], int(jstr['value'])))
                j.set_button(int(jstr['index']), jstr['value'])
            pass
        yield from C.unsubscribe(myoptions)
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Beispiel #16
0
def run(arguments):
    with open(arguments['--output'], 'a') as outfile:
        retry = True
        while retry:
            C = MQTTClient(
                BASE_TOPIC + "/sensorlogger",
                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
                    outfile.write("{},{}\n".format(
                        packet.payload.data.decode('utf-8'),
                        packet.variable_header.topic_name))
                    outfile.flush()
            except KeyboardInterrupt:
                retry = False
            except ClientException as ce:
                logging.error("Client exception: %s" % ce)
                yield from C.unsubscribe([s[0] for s in SUBSCRIPTIONS])
            finally:
                yield from C.disconnect()
Beispiel #17
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)
Beispiel #18
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)
Beispiel #19
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([('+/monitor/Clients',
                                                        QOS_0)])
                self.assertEquals(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)
Beispiel #20
0
    def _connect(self):
        """MQTT connection helper function."""

        config = self._build_client_config()

        self._log(logging.DEBUG, "MQTT client ID: {}".format(self._client_id))
        self._log(logging.DEBUG, "MQTT client config: {}".format(config))

        hbmqtt_client = MQTTClient(client_id=self._client_id, config=config)

        self._log(
            logging.INFO,
            "Connecting MQTT client to broker: {}".format(self._broker_url))

        ack_con = yield hbmqtt_client.connect(self._broker_url,
                                              cleansession=False)

        if ack_con != MQTTCodesACK.CON_OK:
            raise ConnectException(
                "Error code in connection ACK: {}".format(ack_con))

        if self._mqtt_handler.topics:
            self._log(logging.DEBUG,
                      "Subscribing to: {}".format(self._mqtt_handler.topics))
            ack_sub = yield hbmqtt_client.subscribe(self._mqtt_handler.topics)

            if MQTTCodesACK.SUB_ERROR in ack_sub:
                raise ConnectException(
                    "Error code in subscription ACK: {}".format(ack_sub))

        self._client = hbmqtt_client
Beispiel #21
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)
Beispiel #22
0
def connect_broker(topics):
    """Connects to the test MQTT broker and subscribes to the topics."""

    topics = [(topics,
               QOS_0)] if isinstance(topics, six.string_types) else topics

    hbmqtt_client = MQTTClient()
    yield hbmqtt_client.connect(get_test_broker_url())
    yield hbmqtt_client.subscribe(topics)

    raise tornado.gen.Return(hbmqtt_client)
def brokerGetMessage():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost:1883/')
    yield from C.subscribe([("test/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'))
    except ClientException as ce:
        logger.error("Client exception : %s" % ce)
Beispiel #24
0
 def get_led_vals_coro(self):
     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_LED_UUID), QOS_1)])
         message = yield from C.publish('%s/%s/%s/read' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID), b'read', qos=QOS_1)
         response = yield from C.deliver_message()
         print(list(response.data))
         yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID))])
         yield from C.disconnect()
     except ClientException as ce:
         pass
Beispiel #25
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)
def subscriber():
    C = MQTTClient()
    yield from C.connect(get_endpoint())
    yield from C.subscribe([(TOPIC_NAME, QOS_0)])
    try:
        for i in range(NUM_MESSAGES):
            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([TOPIC_NAME])
        yield from C.disconnect()
    except ClientException as ce:
        print("Client exception: %s" % ce)
Beispiel #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),
         ])
         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)
Beispiel #28
0
    def get_thingy_name(self, thingy):
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID), QOS_1)])
            message = yield from C.publish('%s/%s/%s/read' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID), b'read', qos=QOS_1)
            response = yield from C.deliver_message()
            packet = response.publish_packet

            print("%s => %s" % (packet.variable_header.topic_name, response.data.decode("ascii")))
            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            pass
Beispiel #29
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)
Beispiel #30
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()
Beispiel #31
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)
Beispiel #32
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)
Beispiel #33
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)
Beispiel #34
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)
Beispiel #35
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")
Beispiel #36
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()
Beispiel #37
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)
Beispiel #38
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)
Beispiel #39
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)
Beispiel #40
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)
Beispiel #41
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)
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)