コード例 #1
0
    def __init__(self, name, client=None):
        """Set up a new tower.

        :param name: name of tower/station
        :param client: (optional) an existing MQTTClient.
        """
        if client is None:
            self.client = MQTTClient()
        else:
            self.client = client
        self.dispatcher = MQTTDispatcher(self.client)
        self.connected = False
        self.name = name
        self.managers = [
            BlockEnd, BlockStart, Counter, DistantSignal, OuterButton, Route,
            Signal, Track, Turnout
        ]

        OuterButton(self, 'AsT').add_counter()
        OuterButton(self, 'BlGT')
        OuterButton(self, 'ErsGT').add_counter()
        OuterButton(self, 'FHT').add_counter()
        OuterButton(self, 'HaGT')
        OuterButton(self, 'SGT')
        OuterButton(self, 'WGT')
        OuterButton(self, 'WHT').add_counter()

        logger.setLevel(logging.DEBUG)
コード例 #2
0
 def __init__(self, args):
     """ This constructor for Publisher """
     self.arg = args
     try:
         self.client = MQTTClient()
     except Exception as e:
         print(e)
コード例 #3
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)
コード例 #4
0
ファイル: runner.py プロジェクト: agmangas/wot-py
    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
コード例 #5
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([('/qos0', QOS_0), ('/qos1', QOS_1), ('/qos2', QOS_2)])
                self.assertEqual(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.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)
コード例 #6
0
 async def test_coro():
     try:
         broker = Broker(
             self._test_config, plugin_namespace="hbmqtt.test.plugins"
         )
         await broker.start()
         client = MQTTClient()
         await client.connect(f"mqtt://127.0.0.1:{self._tcp_port}/")
         self.assertIsNotNone(client.session)
         ret = await client.subscribe(
             [
                 ("test_topic", QOS_0),
             ]
         )
         self.assertEqual(ret[0], QOS_0)
         client_pub = MQTTClient()
         await client_pub.connect(f"mqtt://127.0.0.1:{self._tcp_port}/")
         await client_pub.publish("test_topic", data, QOS_0)
         await client_pub.disconnect()
         message = await client.deliver_message()
         self.assertIsNotNone(message)
         self.assertIsNotNone(message.publish_packet)
         self.assertEqual(message.data, data)
         await client.unsubscribe(["$SYS/broker/uptime"])
         await client.disconnect()
         await broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
コード例 #7
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())
                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://localhost/')
                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.assertEquals(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)
コード例 #8
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())
                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)
コード例 #9
0
class MiaoMiaoMQPublisher(MiaoMiaoDevice):
    def __init__(self, btaddr, mqurl, mqtopic, *, aioloop=None):
        super().__init__(btaddr)
        self.aioloop = aioloop
        self.mqurl = mqurl
        self.mqtopic = mqtopic
        self.mqclient = MQTTClient()

    def _ensure_aioloop(self):
        """get the event loop here.  we may have been initialized
           in a different thread, hopefully we were called in the
           right one and the default event loop is fine
        """
        if not self.aioloop:
            self.aioloop = asyncio.get_event_loop()

    def handleConnect(self):
        """connect to MQTT when we connect to the actual device"""
        super().handleConnect()
        self._ensure_aioloop()
        self.aioloop.run_until_complete(self.mqclient.connect(self.mqurl))

    def handleDisconnect(self):
        """disconnect from MQTT when we disconnect from the actual device"""
        super().handleDisconnect()
        self._ensure_aioloop()
        self.aioloop.run_until_complete(self.mqclient.disconnect())

    def handlePacket(self, data):
        self._ensure_aioloop()
        self.aioloop.run_until_complete(
            self.mqclient.publish(self.mqtopic, data))
コード例 #10
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())

                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)
コード例 #11
0
ファイル: test_broker.py プロジェクト: maniacs-ops/hbmqtt
 def _client_publish(self, topic, data, qos, retain=False):
     pub_client = MQTTClient()
     ret = yield from pub_client.connect('mqtt://localhost/')
     self.assertEqual(ret, 0)
     ret = yield from pub_client.publish(topic, data, qos, retain)
     yield from pub_client.disconnect()
     return ret
コード例 #12
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())
         client = MQTTClient()
         ret = yield from client.connect('mqtt://localhost/')
         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)
コード例 #13
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)
コード例 #14
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)
コード例 #15
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())
                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.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)
コード例 #16
0
ファイル: test_client.py プロジェクト: beerfactory/hbmqtt
 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)
コード例 #17
0
    def __init__(self,cbpi):

        self.config = {
            'listeners': {
                'default': {
                    'type': 'tcp',
                    'bind': '0.0.0.0:1885',
                },
                'ws': {
                    'bind': '0.0.0.0:8081',
                    'type': 'ws'
                }
            },
            'sys_interval': 10,
            'topic-check': {
                'enabled': True,
                'plugins': [
                    'topic_taboo'
                ]
            },
            'auth': {
                'allow-anonymous': True,
                'password-file': '/Users/manuelfritsch/github/aio_sample.cbpi/user.txt'
            }
        }

        self.cbpi = cbpi
        self.broker = Broker(self.config, plugin_namespace="hbmqtt.broker.plugins")
        self.client = MQTTClient()
        self.matcher = MQTTMatcher()
        self.mqtt_methods = {"test": self.ok_msg, "$SYS/broker/#": self.sysmsg}
        self.cbpi.app.on_startup.append(self.start_broker)
        self.count = 0
コード例 #18
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)
コード例 #19
0
def main():
    if sys.version_info[:2] < (3, 4):
        logger.fatal("Error: Python 3.4+ is required")
        sys.exit(-1)

    config = None
    config = read_yaml_config(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'default_client.yaml'))
    logger.debug("Using default configuration")
    
    loop = asyncio.get_event_loop()

    client_id = "mqtt_publisher_exp"
    
    client = MQTTClient(client_id=client_id, config=config, loop=loop)
    try:
        logger.info("%s Connecting to broker" % client.client_id)

        loop.run_until_complete(client.connect(uri=BROKER_URL))
        qos = QOS_1
        topic = "topic_1"

        for _, row in data.iterrows():
            row['TIMING_client_request_timestamp'] = time()
            message = row.to_json().encode(encoding='utf-8')
            logger.info("%s Publishing to '%s'" % (client.client_id, topic))
            loop.run_until_complete(client.publish(topic, message, qos))
            sleep(0.01)
    except KeyboardInterrupt:
        loop.run_until_complete(client.disconnect())
        logger.info("%s Disconnected from broker" % client.client_id)
    except ConnectException as ce:
        logger.fatal("connection to '%s' failed: %r" % (BROKER_URL, ce))
    except asyncio.CancelledError as cae:
        logger.fatal("Publish canceled due to prvious error")
コード例 #20
0
ファイル: unipoll.py プロジェクト: mhemeryck/unipoll
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("uri", help="MQTT broker URI")
    parser.add_argument("--cafile",
                        help="Optional path to CA file for MQTT over TLS")
    parser.add_argument("--sleep",
                        type=float,
                        default=SLEEP_INTERVAL,
                        help="Sleep time between updates")
    parser.add_argument(
        "--sysfs_root",
        default=SYSFS_ROOT,
        help="sysfs root folder to scan for digital inputs",
    )
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

    loop = asyncio.get_event_loop()

    # Create MQTT client
    client = MQTTClient()
    loop.run_until_complete(client.connect(args.uri, cafile=args.cafile))

    # Digital inputs
    digital_inputs = create_digital_inputs(args.sysfs_root, client)

    loop.run_until_complete(poll(digital_inputs, args.sleep))
    loop.close()
コード例 #21
0
ファイル: test_client.py プロジェクト: zyp/hbmqtt
 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)
コード例 #22
0
ファイル: test_broker.py プロジェクト: beerfactory/hbmqtt
 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
コード例 #23
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())
                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)
コード例 #24
0
 def __init__(self, on_message_cb, port=MQTT_PORT, max_time=MAX_TIME):
     # on_message_cb = send_to_broker method in gateway application
     self._on_message_cb = on_message_cb
     self.port = port
     self.max_time = max_time
     self.nodes = {}
     self.mqtt_client = MQTTClient()
     asyncio.get_event_loop().create_task(self.start())
コード例 #25
0
 def __init__(self, pin, ipAddress, networkId, asyncio_loop):
     self.loop = asyncio_loop
     self.pin = pin
     self.networkId = networkId
     self.ipAddress = ipAddress
     self.topic = 'devices/io-expander/{id}/digital-input/{pin}'.format(
         id=self.networkId, pin=self.pin)
     self.client = MQTTClient()
コード例 #26
0
ファイル: test_client.py プロジェクト: beerfactory/hbmqtt
 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)
コード例 #27
0
ファイル: test_client.py プロジェクト: zyp/hbmqtt
 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)
コード例 #28
0
ファイル: test_client.py プロジェクト: beerfactory/hbmqtt
 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)
コード例 #29
0
 def __connect(self):
     connect = MQTTClient(
         config={
             'keep_alive': 10,
             'ping_delay': 1,
             'reconnect_retries': 10000,
             'reconnect_max_interval': 30
         })
     yield from connect.connect(self.host)
     self.connect = connect
コード例 #30
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()
コード例 #31
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)
コード例 #32
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)
コード例 #33
0
ファイル: mqtt.py プロジェクト: GypsyBud/hearth
 async def __init__(self, uri="mqtt://localhost:1883"):
     if "://" not in uri:
         uri = "mqtt://" + uri
     self.uri = uri
     self.subscriptions = {}
     self.mqtt = MQTTClient(config={"auto_reconnect": False})
     for key in logging.Logger.manager.loggerDict:
         if key.startswith("hbmqtt"):
             logging.getLogger(key).setLevel(logging.WARNING)
     await self.mqtt.connect(self.uri)
     asyncio.ensure_future(self._loop())
コード例 #34
0
def pub_picture(temp, address):
    C = MQTTClient(config=config)
    yield from C.connect(address)
    #temp = json.dumps(temp)
    temp = str.encode(temp)
    tasks = [
        asyncio.ensure_future(C.publish('/picture', temp)),
    ]
    yield from asyncio.wait(tasks)
    logger.info("messages published")
    yield from C.disconnect()
コード例 #35
0
def publisher():
    C = MQTTClient()
    yield from C.connect(get_endpoint())
    for i in range(NUM_MESSAGES):
        tasks = [
            asyncio.ensure_future(
                C.publish(TOPIC_NAME, ('TEST MESSAGE %s' % i).encode('utf-8')))
        ]
        yield from asyncio.wait(tasks)
    print('%s messages published' % NUM_MESSAGES)
    yield from C.disconnect()
コード例 #36
0
ファイル: client_publish.py プロジェクト: beerfactory/hbmqtt
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()
コード例 #37
0
def response(url, topic, status):
    print(status)
    try:
        Conn = MQTTClient()
        yield from Conn.connect(url)
        #message = yield from Conn.publish(topic, status.encode(), qos=0x00)
        message = yield from Conn.publish(topic, status.encode(), qos=0x01)
        #message = yield from Conn.publish(topic, status.encode(), qos=0x02)
        print("messages %s published" % (status))
        yield from Conn.disconnect()
    except ConnectException as ce:
        asyncio.get_event_loop().stop()
コード例 #38
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('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)
コード例 #39
0
ファイル: client_publish.py プロジェクト: beerfactory/hbmqtt
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()
コード例 #40
0
def pub_comRes(temp, address, building_id):
    C = MQTTClient(config=config)
    yield from C.connect(address)
    temp = json.dumps(temp)
    temp = str.encode(temp)
    print (temp)
    tasks = [
        asyncio.ensure_future(C.publish('/comRes/'+building_id, temp)),
    ]
    yield from asyncio.wait(tasks)
    logger.info("messages published")
    yield from C.disconnect()
コード例 #41
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)
コード例 #42
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()
         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)
コード例 #43
0
ファイル: test_client.py プロジェクト: FlorianLudwig/hbmqtt
 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)
コード例 #44
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([
             ('$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)
コード例 #45
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', 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)
コード例 #46
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())

                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)
コード例 #47
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())
         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)
コード例 #48
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(
                    [('+', 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)
コード例 #49
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())
         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)
コード例 #50
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()
コード例 #51
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)
コード例 #52
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())

                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)
コード例 #53
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()
コード例 #54
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)
コード例 #55
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)
コード例 #56
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)