コード例 #1
0
ファイル: test_broker.py プロジェクト: maniacs-ops/hbmqtt
        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)
コード例 #2
0
ファイル: test_broker.py プロジェクト: beerfactory/hbmqtt
        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)
コード例 #3
0
ファイル: test_broker.py プロジェクト: FlorianLudwig/hbmqtt
        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)
コード例 #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()
コード例 #5
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()
コード例 #6
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()
コード例 #7
0
ファイル: test_client.py プロジェクト: zyp/hbmqtt
 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)
コード例 #8
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)
コード例 #9
0
ファイル: test_broker.py プロジェクト: maniacs-ops/hbmqtt
        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)
コード例 #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)
コード例 #11
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"))
            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)
コード例 #12
0
ファイル: test_client.py プロジェクト: beerfactory/hbmqtt
 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)
コード例 #13
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()
コード例 #14
0
ファイル: test_broker.py プロジェクト: beerfactory/hbmqtt
        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)
コード例 #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)
コード例 #16
0
ファイル: hassio.py プロジェクト: jukart/heizung
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()
コード例 #17
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)
コード例 #18
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))
コード例 #19
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
コード例 #20
0
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)
コード例 #21
0
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)
コード例 #22
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
コード例 #23
0
ファイル: mqtt.py プロジェクト: helgrind/sputnik
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)
コード例 #24
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()
コード例 #25
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)
コード例 #26
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)
コード例 #27
0
ファイル: mqtt.py プロジェクト: simudream/poupool
 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()
コード例 #28
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)
コード例 #29
0
ファイル: regler.py プロジェクト: jukart/heizung
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")
コード例 #30
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)
コード例 #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)
コード例 #32
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)
コード例 #33
0
ファイル: test_broker.py プロジェクト: zyp/hbmqtt
        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)
コード例 #34
0
ファイル: test_client.py プロジェクト: beerfactory/hbmqtt
 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)
         with self.assertRaises(asyncio.TimeoutError):
             yield from client.deliver_message(timeout=2)
         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)
コード例 #35
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()
コード例 #36
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)
コード例 #37
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)
コード例 #38
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)
コード例 #39
0
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)