MQTT Broker and IoT Capabilities written in Rust for Python, Django and FastAPI
MIT License
A Python package, written in Rust, helps to run MQTT Broker and subscribe to MQTT topics in a multithreaded manner without any extra Python dependency. The internals of the MQTT server are written in Rust using the Tokio framework. The motive of the project is to overcome the GIL limitation, provide simple-to-use MQTT broker Python projects, and bring all the concurrent features offered by Rust to Python.
pip install iotcore
Create a new file called mqtt.toml in your root project directory and copy pase the sample mqtt.toml from https://tomvictor.github.io/iotcore/config/
Broker only
from fastapi import FastAPI
from iotcore.fastapi import iotcore_broker
app = FastAPI(lifespan=iotcore_broker)
@app.get("/")
def read_root():
return {"Hello": "World"}
Broker plus Mqtt client
from fastapi import FastAPI
from contextlib import asynccontextmanager
from iotcore import IotCore
iot = IotCore()
@asynccontextmanager
async def lifespan(app: FastAPI):
iot.background_loop_forever()
yield
app = FastAPI(lifespan=lifespan)
@iot.accept(topic="temperature")
def temperature_data(request):
print(f"Temperature data : {request}")
def mqtt_callback(data):
print(f"iot >: {data}")
@app.get("/sub")
def sub():
iot.subscribe("iot", mqtt_callback)
return {"response": "subscribed"}
@app.get("/pub")
def pub():
iot.publish("temperature", "{'temp': 18}")
return {"response": "published"}
@app.get("/")
def home():
return {"Hello": "World"}
from django.http import JsonResponse
from iotcore import IotCore
iot = IotCore()
iot.background_loop_forever()
def mqtt_callback(data):
print(f"Django >: {data}")
def subscribe(request):
iot.subscribe("iot", mqtt_callback)
return JsonResponse({"response": "subscribed"})
def publish(request):
iot.publish("iot", "demo")
return JsonResponse({"response": "published"})
Now Connect to mqtt broker on localhost MQTT Port : 1883
Django
pip install iotcore
pip install django
python examples/django/manage.py runserver
FastAPI
pip install iotcore
pip install fastapi
pip install uvicorn
uvicorn examples.fastapi.main:app
Open you mqtt client and use below details to connect to the broker: Host: 127.0.0.1 or localhost Port: 1883
Star the project on GitHub :)
The project is licensed under the MIT license.