Skip to main content

MQRoute is a Python library designed to simplify working with MQTT

Project description

MQRoute

MQRoute is a Python MQTT routing library designed to simplify working with MQTT topics by abstracting complexity. It supports advanced topic matching (including wildcards and parameterized topics), allows easy registration of callbacks using decorators, and provides scalable asynchronous callback handling.

Whether you're building an IoT platform or a messaging service, MQRoute makes it easy to manage MQTT subscriptions and streamline message processing.


Features

  • Dynamic Topic Matching:
    Supports + and # MQTT wildcards, as well as parameterized topics (+parameter_name+) for extracting parameters from topic strings.

  • Asynchronous by Design:
    Built with asyncio for responsive handling of incoming MQTT messages and user-defined asynchronous callbacks.

  • Decorator-Based Callbacks:
    Subscribe to MQTT topics effortlessly using Python decorators.

  • Type Safety:
    Includes type hints and validation with the typeguard library.

  • Extensive Logging and Debugging:
    Detailed logs for easy troubleshooting of MQTT operations and callbacks.

  • Customizable Payload Handling:
    Easy-to-use mechanisms for handling raw or JSON-formatted payloads.


Installation

You can install MQRoute simply by using pip:

pip install mqroute

You may also down it from git for example when some local modification are needed. That's your call!

Getting Started

Below are the steps to start using MQRoute. For more advanced usage, refer to detailed examples in the testclient.py.

Initialize the MQTT Client

Use the MQTTClient class to connect to the MQTT broker, subscribe to topics, and handle messages.

import asyncio
from mqroute.mqtt_client import MQTTClient

mqtt = MQTTClient(host="test.mosquitto.org", port=1883)
asyncio.run(mqtt.run())  # Establishes connection and starts listening

Subscribe to Topics

Use the @mqtt.subscribe decorator to register a specific callback for a topic. The library supports + and # MQTT wildcards and parameterized topics.

@mqtt.subscribe(topic="devices/+/status")
async def handle_device_status(topic, msg, params):
    print(f"Device {params[0]} status: {msg.message}")

@mqtt.subscribe(topic="sensors/+/data/+/type/#")
async def handle_sensor_data(topic, msg, params):
    print(f"Sensor {params[0]} data at {params[1]}: {msg.message}")

Handle JSON Payloads Automatically

JSON payloads are converted automatically to dictionaries. In case this is not desired convert_json parameter in the decorator can be set to False to receive raw data in callback instead. The value of convert_json defaults to True.

@mqtt.subscribe(topic="config/update/json", convert_json=True)
async def handle_config_update(topic, msg, params):
    # Access the payload as a Python dictionary
    config_data_as_dict = msg.message
    print(f"Received config update: {config_data_as_dict}")

@mqtt.subscribe(topic="config/update/raw", convert_json=False)
async def handle_config_update(topic, msg, params):
    # Access the payload as a raw string
    config_data_as_raw = msg.message
    print(f"Received config update: {config_data_as_raw}")

Example: Full Client Code

Below is a complete example that demonstrates how to use MQRoute:

import asyncio
from mqroute.mqtt_client import MQTTClient

mqtt = MQTTClient(host="test.mosquitto.org", port=1883)


@mqtt.subscribe(topic="devices/+/status")
async def handle_device_status(topic, msg, params):
    print(f"Device {params[0]} status: {msg.message}")


@mqtt.subscribe(topic="sensors/+light+/status", convert_json=True)
async def handle_light_status(topic, msg, params):
    sensor = params["light"]
    print(f"{sensor} sensor status: {msg.message}")


asyncio.run(mqtt.run())

Advanced Features

1. Parameterized Topics

Extract dynamic portions of a topic using parameterized syntax:

@mqtt.subscribe(topic="room/+room+/device/+device+/status")
async def handle_parametrized(topic, msg, params):
    print(f"Device {params['device']} in room {params['room']} has status: {msg.message}")

2. Custom Callback Runner

For advanced use cases, directly manage callbacks using the CallbackRunner class.


Testing

Integration and unit testing can be performed using pytest. Sample test cases are provided in the repository.

Run the tests:

pytest tests/

Planned Improvements

  • Message Publishing API: Simple methods for publishing MQTT messages.
  • Graceful Shutdowns: Cleaning up resources (e.g., unsubscribing tasks) on application stop.
  • Customization and extendability: Allow easy means to support for example custom payload formats
  • Dynamic subscriptions: Subscribe MQTT topics without decorators in order to allow dynamic construction of mqroute application.

Contributing

Contributions and feedback are welcome! If you'd like to contribute, please follow these steps:

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature-name).
  3. Commit your changes (git commit -m 'Add new feature').
  4. Push to the branch (git push origin feature-name).
  5. Submit a pull request.

For major changes, please open an issue first to discuss what you'd like to improve.


License

This project is licensed under the MIT License. See the LICENSE file for details.


Additional Notes

  • For complete functionality and advanced examples, refer to the testclient.py file provided in the repository.
  • MQRoute is in active development. Feel free to report bugs.

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

mqroute-0.1.1.tar.gz (19.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mqroute-0.1.1-py3-none-any.whl (19.9 kB view details)

Uploaded Python 3

File details

Details for the file mqroute-0.1.1.tar.gz.

File metadata

  • Download URL: mqroute-0.1.1.tar.gz
  • Upload date:
  • Size: 19.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.13.1

File hashes

Hashes for mqroute-0.1.1.tar.gz
Algorithm Hash digest
SHA256 867e82256354ebe3a4f604cbdc6a41f8ead892a38a2e2192ac5b47861ffed3ae
MD5 8ed3ecd460e63f6a3403ca85e1ec212d
BLAKE2b-256 3ba79fb5b63188853729295c9aacc0ace34e8b183d7d6101c6c0b08dab63a722

See more details on using hashes here.

File details

Details for the file mqroute-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: mqroute-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.13.1

File hashes

Hashes for mqroute-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7f41de5482c9929b8cd495704a8f9db1fe9a1084aaed02b883f5d2af3aca17e1
MD5 fa95717ee6ec3e57993c7506ec1e2c5a
BLAKE2b-256 dc394d0f9b0615e89ef78998e36c46164124bff315ef01defd327ca65f4e30a5

See more details on using hashes here.

Supported by

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