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

        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Beispiel #2
0
def publisher():
    C = MQTTClient()
    ret = C.connect('mqtt://127.0.0.1:1883/')
    message = C.publish('/slack_in', b'TEST MESSAGE WITH QOS_0', qos=QOS_0)
    message = C.publish('/slack_in', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)
    message = C.publish('/slack_in', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)
    print(message)
    print("messages published")
    C.disconnect()
Beispiel #3
0
def test_coro():
    C = MQTTClient()
    yield from C.connect(url)
    tasks = [
        asyncio.ensure_future(C.publish(topic, b'up', qos=QOS_0)),
        asyncio.ensure_future(C.publish(topic, b'2', qos=QOS_1)),
        asyncio.ensure_future(C.publish(topic, b'3', qos=QOS_2)),
    ]
    yield from asyncio.wait(tasks)
    logger.info("messages published")
    yield from C.disconnect()
Beispiel #4
0
def test_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://test.mosquitto.org/')
    tasks = [
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_0')),
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)),
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)),
    ]
    yield from asyncio.wait(tasks)
    logger.info("messages published")
    yield from C.disconnect()
Beispiel #5
0
def test_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://test.mosquitto.org/')
    tasks = [
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_0')),
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)),
        asyncio.ensure_future(C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)),
    ]
    yield from asyncio.wait(tasks)
    logger.info("messages published")
    yield from C.disconnect()
Beispiel #6
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)
        logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Beispiel #7
0
def test_coro2():
    try:
        C = MQTTClient()
        yield from C.connect('mqtt://test.mosquitto.org:1883/')
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_0', qos=0x00)
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=0x01)
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=0x02)
        logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Beispiel #8
0
def test_coro2():
    try:
        C = MQTTClient()
        yield from C.connect('mqtt://test.mosquitto.org:1883/')
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_0', qos=0x00)
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_1', qos=0x01)
        yield from C.publish('a/b', b'TEST MESSAGE WITH QOS_2', qos=0x02)
        logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Beispiel #9
0
async def test_coro():
    C = MQTTClient()
    await 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)),
    ]
    await asyncio.wait(tasks)
    logger.info("messages published")
    await C.disconnect()
Beispiel #10
0
def test_coro():
    C = MQTTClient()
    yield from C.connect(SERVER)
    tasks = [
        asyncio.ensure_future(C.publish(TOPIC3, b'TEST MESSAGE WITH QOS_0')),
        asyncio.ensure_future(
            C.publish(TOPIC3, b'TEST MESSAGE WITH QOS_1', qos=QOS_1)),
        asyncio.ensure_future(
            C.publish(TOPIC3, b'TEST message with qos_2', qos=QOS_2)),
    ]
    yield from asyncio.wait(tasks)
    logger.info("message published")
    yield from C.disconnect
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()
Beispiel #12
0
def test_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://127.0.0.1:1883/')
    tasks = [
        asyncio.ensure_future(
            C.publish('/slack_in', b'TEST MESSAGE WITH QOS_0')),
        asyncio.ensure_future(
            C.publish('/slack_in', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)),
        asyncio.ensure_future(
            C.publish('/slack_in', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)),
    ]
    yield from asyncio.wait(tasks)
    print("messages published")
    yield from C.disconnect()
Beispiel #13
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://127.0.0.1/')
                self.assertEqual(ret, 0)

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

                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                MockPluginManager.assert_has_calls(
                    [
                        call().fire_event(EVENT_BROKER_MESSAGE_RECEIVED,
                                          client_id=pub_client.session.client_id,
                                          message=ret_message),
                    ], any_order=True)
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Beispiel #14
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))
Beispiel #15
0
        def test_coro():
            try:
                broker = Broker(test_config,
                                plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())

                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://localhost/')
                self.assertEqual(ret, 0)
                ret_message = yield from pub_client.publish('/topic',
                                                            b'data',
                                                            QOS_0,
                                                            retain=True)
                yield from pub_client.disconnect()
                yield from asyncio.sleep(0.1)
                self.assertIn('/topic', broker._retained_messages)
                retained_message = broker._retained_messages['/topic']
                self.assertEquals(retained_message.source_session,
                                  pub_client.session)
                self.assertEquals(retained_message.topic, '/topic')
                self.assertEquals(retained_message.data, b'data')
                self.assertEquals(retained_message.qos, QOS_0)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Beispiel #16
0
 def _client_publish(self, topic, data, qos, retain=False):
     pub_client = MQTTClient()
     ret = yield from pub_client.connect('mqtt://127.0.0.1/')
     self.assertEqual(ret, 0)
     ret = yield from pub_client.publish(topic, data, qos, retain)
     yield from pub_client.disconnect()
     return ret
Beispiel #17
0
        def test_coro():
            try:
                broker = Broker(test_config,
                                plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                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)
Beispiel #18
0
 def test_coro():
     try:
         broker = Broker(broker_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('test_topic', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         client_pub = MQTTClient()
         yield from client_pub.connect('mqtt://127.0.0.1/')
         yield from client_pub.publish('test_topic', data, QOS_0)
         yield from client_pub.disconnect()
         message = yield from client.deliver_message()
         self.assertIsNotNone(message)
         self.assertIsNotNone(message.publish_packet)
         self.assertEqual(message.data, data)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Beispiel #19
0
 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
Beispiel #20
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")
Beispiel #21
0
 def test_coro():
     try:
         broker = Broker(broker_config,
                         plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('test_topic', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         client_pub = MQTTClient()
         yield from client_pub.connect('mqtt://127.0.0.1/')
         yield from client_pub.publish('test_topic', data, QOS_0)
         yield from client_pub.disconnect()
         message = yield from client.deliver_message()
         self.assertIsNotNone(message)
         self.assertIsNotNone(message.publish_packet)
         self.assertEqual(message.data, data)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Beispiel #22
0
def run(arguments):
    global SUBSCRIPTIONS
    readSettings()
    loop_time = int(arguments['--loop-time'])
    retry = True
    while retry:
        C = MQTTClient(
            BASE_TOPIC + "/regler",
            config=CLIENT_CONFIG,
        )
        yield from C.connect(arguments['--uri'])
        yield from C.subscribe([(s[0], QOS_2) for s in SUBSCRIPTIONS])
        try:
            push_state['heat_pump'].setValue(state['heat_pump'])
            yield from C.publish(*push_state['heat_pump'].publish())
            yield from C.publish(*push_state['state'].publish())
            start = time.time()
            while True:
                packet = None
                wait_time = max(loop_time - (time.time() - start), 0)
                logging.debug("wait_time= %s", wait_time)
                try:
                    message = yield from C.deliver_message(timeout=wait_time)
                    packet = message.publish_packet
                except asyncio.TimeoutError:
                    pass
                if packet:
                    executePacket(packet)
                if (time.time() - start) > loop_time:
                    start = time.time()
                    calculateNominal()
                    calulateHeatPumpState()
                    push_state['heat_pump'].setValue(state['heat_pump'])
                    yield from C.publish(*push_state['heat_pump'].publish())
                    yield from C.publish(*push_state['state'].publish())
        except KeyboardInterrupt:
            retry = False
        except ClientException as e:
            logging.exception("Client exception: %s" % e)
        except Exception as e:
            logging.exception("Unknown exception: %s" % e)
        finally:
            yield from C.unsubscribe([s[0] for s in SUBSCRIPTIONS])
            yield from C.disconnect()
        if retry:
            print("retry")
Beispiel #23
0
async def send_video(client: MQTTClient, video: YtdlPafy, topics: List[str]):
    video_bytes = pickle.dumps(video)
    logging.debug(f"Sending video '{video.title}' to the following topics: '{topics}'")
    await asyncio.gather(
        *(
            asyncio.ensure_future(client.publish(topic, video_bytes, qos=QOS_2))
            for topic in topics
        )
    )
Beispiel #24
0
def test_coro2():
    try:
        C = MQTTClient()
        ret = yield from C.connect('mqtt://127.0.0.1:1883/')
        message = yield from C.publish('/slack_in',
                                       b'TEST MESSAGE WITH QOS_0',
                                       qos=0x00)
        message = yield from C.publish('/slack_in',
                                       b'TEST MESSAGE WITH QOS_1',
                                       qos=0x01)
        message = yield from C.publish('/slack_in',
                                       b'TEST MESSAGE WITH QOS_2',
                                       qos=0x02)
        #print(message)
        # logger.info("messages published")
        yield from C.disconnect()
    except ConnectException as ce:
        # logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Beispiel #25
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()
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()
Beispiel #27
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()
Beispiel #28
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()
Beispiel #29
0
 def get_led_vals_coro(self):
     try:
         C = MQTTClient()
         yield from C.connect(self.MQTT_BROKER_ADDR)
         yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID), QOS_1)])
         message = yield from C.publish('%s/%s/%s/read' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID), b'read', qos=QOS_1)
         response = yield from C.deliver_message()
         print(list(response.data))
         yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID))])
         yield from C.disconnect()
     except ClientException as ce:
         pass
Beispiel #30
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()
Beispiel #31
0
    def publish(self, message, topic=None, qos=None, retain=None):
        if not topic:
            topic = 'devices/' + self.session.username

        if isinstance(message, str):
            message = bytes(message, encoding='utf-8')
        elif isinstance(message, object):
             message = pickle.loads(message)
        else:
            message = bytes(str(message), encoding='utf-8')
        # yield from MQTTClient.publish(self, topic, message, qos=qos, retain=retain)
        self._loop.run_until_complete(MQTTClient.publish(self, topic, message, qos=qos, retain=retain))
Beispiel #32
0
def test(command):
    try:
        C = MQTTClient()
        yield from C.connect(url)
        message = yield from C.publish(topic, command.encode(), qos=0x00)
        #message = yield from C.publish(topic, command.encode(), qos=0x01)
        #message = yield from C.publish(topic, command.encode(), qos=0x02)
        logger.info("messages %s published" % (command))
        yield from C.disconnect()
    except ConnectException as ce:
        logger.error("Connection failed: %s" % ce)
        asyncio.get_event_loop().stop()
Beispiel #33
0
class ServerConnection:
    """MQTT Client."""
    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())

    async def _loop(self):
        """Connection handling loop."""
        while True:
            try:
                if self.subscriptions:
                    await self.mqtt.subscribe([
                        (t, qos) for t, (_, qos) in self.subscriptions.items()
                    ])
                while True:
                    message = await self.mqtt.deliver_message()
                    topic = message.publish_packet.variable_header.topic_name
                    payload = message.publish_packet.payload.data.decode()
                    callback = self.subscriptions.get(
                        topic, (self.message_handler, ))[0]
                    asyncio.ensure_future(callback(topic, payload))
            except KeyboardInterrupt:
                break
            except asyncio.CancelledError:
                break
            finally:
                await self.mqtt.disconnect()
            await asyncio.sleep(1)
            await self.mqtt.reconnect()

    async def pub(self, topic, payload, qos=0):
        """Publish message on topic."""
        if isinstance(payload, dict) or isinstance(payload, list):
            payload = json.dumps(payload)
        asyncio.ensure_future(self.mqtt.publish(topic, payload.encode(), qos))

    async def sub(self, topic, callback, qos=0):
        """Subscribe to topic with callback."""
        self.subscriptions[topic] = (callback, qos)
        await self.mqtt.subscribe([(topic, qos)])
        LOGGER.info("Subscribed to topic %s", topic)

    async def message_handler(self, topic, payload):
        """Default message handler."""
        LOGGER.info("Message on unknown topic: %s : {%s}", topic, payload)
Beispiel #34
0
    def get_thingy_name(self, thingy):
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID), QOS_1)])
            message = yield from C.publish('%s/%s/%s/read' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID), b'read', qos=QOS_1)
            response = yield from C.deliver_message()
            packet = response.publish_packet

            print("%s => %s" % (packet.variable_header.topic_name, response.data.decode("ascii")))
            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            pass
Beispiel #35
0
def run(arguments):
    poll_interval = int(arguments['--interval'])
    # connect to the MQTT brocker
    C = MQTTClient(
        BASE_TOPIC + "/sensorreader",
        config=CLIENT_CONFIG,
    )
    yield from C.connect(arguments['--uri'])
    try:
        for sensor in W1ThermSensor.get_available_sensors():
            logging.debug("Sensor: %s", sensor.id)
        while True:
            start = time.time()
            for name, s in SENSORS.items():
                if 'sensor_client' not in s:
                    try:
                        s['sensor_client'] = W1ThermSensor(
                            W1ThermSensor.THERM_SENSOR_DS18B20,
                            s['id'],
                        )
                        logging.info('[%s] sonsor found' % name)
                    except NoSensorFoundError:
                        logging.error('[%s] sonsor not found' % name)
                        continue
                t = s['sensor_client'].get_temperature()
                if t < s['min'] or t > s['max']:
                    logging.warning("[%s] temp %s outside [%s - %s]" % (
                        name, t, s['min'], s['max']
                    ))
                    continue
                now = datetime.now().replace(microsecond=0)
                data = '{}Z,{}'.format(now.isoformat(), t)
                yield from C.publish(
                    s['topic'],
                    bytes(data, 'utf-8'),
                    qos=QOS_2,
                )
            end = time.time()
            time.sleep(max(0, poll_interval - (end - start)))
    except KeyboardInterrupt:
        pass
    except:
        logging.exception("")
    finally:
        yield from C.disconnect()
Beispiel #36
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())

                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://127.0.0.1/')
                self.assertEqual(ret, 0)
                yield from pub_client.publish('/topic', b'', QOS_0, retain=True)
                yield from pub_client.disconnect()
                yield from asyncio.sleep(0.1)
                self.assertNotIn('/topic', broker._retained_messages)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)
Beispiel #37
0
async def publish(broker, topic, message, loop):
    """
    publish one message for testing
    :param broker: hostname of the broker
    :param topic: topic to publish
    :param message: message to publish
    :type message: str
    :param loop: async event loop
    :return: 
    """

    c = MQTTClient(loop=loop)
    await c.connect('mqtt://%s' % broker)
    tasks = [
        asyncio.ensure_future(c.publish(topic=topic, message=message)),
    ]
    await asyncio.wait(tasks)
    await c.disconnect()
Beispiel #38
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())

                pub_client = MQTTClient()
                ret = yield from pub_client.connect('mqtt://localhost/')
                self.assertEqual(ret, 0)
                ret_message = yield from pub_client.publish('/topic', b'data', QOS_0, retain=True)
                yield from pub_client.disconnect()
                yield from asyncio.sleep(0.1)
                self.assertIn('/topic', broker._retained_messages)
                retained_message = broker._retained_messages['/topic']
                self.assertEquals(retained_message.source_session, pub_client.session)
                self.assertEquals(retained_message.topic, '/topic')
                self.assertEquals(retained_message.data, b'data')
                self.assertEquals(retained_message.qos, QOS_0)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)