What is FastApi-MQTT
mastergmqtt Python module, providing an async implementation of the MQTT protocol. It supports the MQTT version 5.0 protocol, making it suitable for machine-to-machine (M2M) telemetry and low-bandwidth environments.repository·master·Indexed 18 days ago
https://github.com/sabuhish/fastapi-mqttAn asynchronous MQTT client for FastAPI built on top of the gmqtt module. It provides a wrapper to integrate MQTT publish/subscribe capabilities into FastAPI applications using Pydantic-based configuration (MQTTConfig) and decorators for lifecycle events such as on_connect, on_disconnect, on_subscribe, and on_message. Version 2.2.0 supports MQTT v5.0 and integrates with FastAPI's lifespan for managed startup and shutdown.
gmqtt Python module, providing an async implementation of the MQTT protocol. It supports the MQTT version 5.0 protocol, making it suitable for machine-to-machine (M2M) telemetry and low-bandwidth environments.Topics are used by the broker to filter and distribute messages. When designing your topic structure, follow these rules:
/, it is considered bad practice. It is better to use a hierarchical structure without a leading slash (e.g., house/room1/sensor1).Valid hierarchical structures include:
house/room1/sensor1house/room2/sensor1house-room1-sensor1 (using delimiters other than /)FastApi-MQTT provides decorator-based methods to handle specific MQTT lifecycle events and message arrivals. You can implement custom logic by defining functions and decorating them with these hooks:
on_connect(): Triggered when the client successfully connects to the broker.on_disconnect(): Triggered when the client disconnects from the broker.on_subscribe(): Triggered when a subscription is successfully established.on_message(): Triggered when a new message is received on a subscribed topic.MQTT (Message Queuing Telemetry Transport) is a lightweight, publish/subscribe messaging protocol designed for machine-to-machine (M2M) and IoT communication. It is optimized for low bandwidth, high latency, or unreliable networks.
When subscribing to topics, you can use wildcard characters to match multiple topics at once. Wildcards can only be used in subscriptions, not in publishing.
+ (Plus character): Single-level wildcard. Matches exactly one level in the hierarchy.# (Hash character): Multi-level wildcard. Matches all remaining levels in the hierarchy.+)Subscribing to house/+/main-light will match:
house/room1/main-lighthouse/room2/main-lighthouse/garage/main-lightIt will not match:
house/room1/side-light (because the last level does not match main-light)house/room1/sub/main-light (because + only covers one level)#)Subscribing to house/# will match every topic that starts with house/, regardless of how many levels follow (e.g., house/room1, house/room1/sensor/temp, etc.).
You cannot use wildcards at the end of a partial level without a separator. The following are invalid:
house+ (No topic level defined)house# (No topic level defined)house/+/main-light
house/#MQTT settings and configurations are managed using pydantic classes. This allows for structured configuration of:
unsubscribe from specific topics and publish messages to specific topics.If you use poetry for dependency management, you can add fastapi-mqtt to your project by entering the poetry shell and using the add command.
poetry shell
poetry add fastapi-mqttWhen running example applications or tests against a local broker (e.g., the Docker container mentioned above), set the TEST_BROKER_HOST environment variable to localhost.
# Run the example app with uvicorn
TEST_BROKER_HOST=localhost uvicorn examples.app:app --port 8000 --reload
# Run the websocket example app
TEST_BROKER_HOST=localhost uvicorn examples.ws_app.app:application --port 8000 --reload
# Run pytest against local broker
TEST_BROKER_HOST=localhost pytestTo use fastapi-mqtt, you need to instantiate an MQTTConfig object for your connection settings and pass it to the FastMQTT client. This client is then integrated with your FastAPI application instance.
from fastapi import FastAPI
from fastapi_mqtt import FastMQTT, MQTTConfig
app = FastAPI()
mqtt_config = MQTTConfig()
mqtt = FastMQTT(
config=mqtt_config
)To contribute to the project, you need to set up the development environment using poetry and pre-commit. This includes installing dependencies, activating the virtual environment, and setting up the linting hooks to ensure code quality.
git clone https://github.com/sabuhish/fastapi-mqtt.git
cd fastapi-mqtt
poetry install
# activate the poetry virtualenv
poetry shell
# to make changes and validate them
pre-commit install
pre-commit install-hooks
pre-commit run --all-files
# to run the test suite
pytestTo test your implementation locally, you can run a Mosquitto MQTT broker using Docker with the following command:
docker run -d --name mosquitto -p 9001:9001 -p 1883:1883 eclipse-mosquitto:1.6.15To ensure the MQTT client starts and shuts down correctly with your FastAPI application, use an asynccontextmanager within the FastAPI lifespan parameter. Call fast_mqtt.mqtt_startup() during startup and fast_mqtt.mqtt_shutdown() during shutdown.
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi_mqtt import FastMQTT, MQTTConfig
mqtt_config = MQTTConfig()
fast_mqtt = FastMQTT(config=mqtt_config)
@asynccontextmanager
async def _lifespan(_app: FastAPI):
await fast_mqtt.mqtt_startup()
yield
await fast_mqtt.mqtt_shutdown()
app = FastAPI(lifespan=_lifespan)