Skip to main content

Asynchronous MQTT client for 3.1.1 protocol version.

Project description

About

Asynchronous MQTT client for 3.1.1 protocol version.

Installation

Recommended way (via pip):

$ pip install aio-mqtt

Example

Simple echo server:

import asyncio as aio
import logging
import typing as ty

import aio_mqtt

logger = logging.getLogger(__name__)


class EchoServer:

    def __init__(
            self,
            reconnection_interval: int = 10,
            loop: ty.Optional[aio.AbstractEventLoop] = None
    ) -> None:
        self._reconnection_interval = reconnection_interval
        self._loop = loop or aio.get_event_loop()
        self._client = aio_mqtt.Client(loop=self._loop)
        self._tasks = [
            self._loop.create_task(self._connect_forever()),
            self._loop.create_task(self._handle_messages())
        ]

    async def close(self) -> None:
        for task in self._tasks:
            if task.done():
                continue
            task.cancel()
            try:
                await task
            except aio.CancelledError:
                pass
        if self._client.is_connected():
            await self._client.disconnect()

    async def _handle_messages(self) -> None:
        async for message in self._client.delivered_messages('in'):
            while True:
                try:
                    await self._client.publish(
                        aio_mqtt.PublishableMessage(
                            topic_name='out',
                            payload=message.payload,
                            qos=aio_mqtt.QOSLevel.QOS_1
                        )
                    )
                except aio_mqtt.ConnectionClosedError as e:
                    logger.error("Connection closed", exc_info=e)
                    await self._client.wait_for_connect()
                    continue

                except Exception as e:
                    logger.error("Unhandled exception during echo message publishing", exc_info=e)

                break

    async def _connect_forever(self) -> None:
        while True:
            try:
                connect_result = await self._client.connect('localhost')
                logger.info("Connected")

                await self._client.subscribe(('in', aio_mqtt.QOSLevel.QOS_1))

                logger.info("Wait for network interruptions...")
                await connect_result.disconnect_reason
            except aio.CancelledError:
                raise

            except aio_mqtt.AccessRefusedError as e:
                logger.error("Access refused", exc_info=e)

            except aio_mqtt.ConnectionLostError as e:
                logger.error("Connection lost. Will retry in %d seconds", self._reconnection_interval, exc_info=e)
                await aio.sleep(self._reconnection_interval, loop=self._loop)

            except aio_mqtt.ConnectionCloseForcedError as e:
                logger.error("Connection close forced", exc_info=e)
                return

            except Exception as e:
                logger.error("Unhandled exception during connecting", exc_info=e)
                return

            else:
                logger.info("Disconnected")
                return


if __name__ == '__main__':
    logging.basicConfig(
        level='DEBUG'
    )
    loop = aio.new_event_loop()
    server = EchoServer(reconnection_interval=10, loop=loop)
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    finally:
        loop.run_until_complete(server.close())
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.close()

License

Copyright 2019-2020 Not Just A Toy Corp.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aio-mqtt-0.2.0.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

aio_mqtt-0.2.0-py3-none-any.whl (18.3 kB view details)

Uploaded Python 3

File details

Details for the file aio-mqtt-0.2.0.tar.gz.

File metadata

  • Download URL: aio-mqtt-0.2.0.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/3.7.4

File hashes

Hashes for aio-mqtt-0.2.0.tar.gz
Algorithm Hash digest
SHA256 c1dcce2e536cb25277b5f222cf3699a5c64cd461597545c28a7c2625d022c08d
MD5 18b0a5b8cb4ed99c3f0b862dcac7bffa
BLAKE2b-256 0adf0c57d87e20ef466f58245a339627533bcbf0b40b6098ddba0342c9e70c75

See more details on using hashes here.

File details

Details for the file aio_mqtt-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: aio_mqtt-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 18.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/3.7.4

File hashes

Hashes for aio_mqtt-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 546a56620d962011bd0a8a8be21ddffb9175ff2c8065b5f8a30f457f53271808
MD5 30ccd3987b61c667fc0a45962a19614a
BLAKE2b-256 85e9da5262130fd605cfdcc4b7fd33468ceb432d49499a9df29622449003754d

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page