My goal is to setup a Django application, retrieving MQTT messages from a broker. (For example using Paho MQTT Client ).
It would seem to me that the asynchronous fetching of incoming messages would be a nice fit for the new Django Channels. As this would provide an event driven setup.
My question is: can Django Channels indeed be a tool to bridge MQTT messages? If so: how could I set this up?
I have implemented a very simple interface between MQTT broker and ASGI. It's still experimental and has some limitations, but you can use it to fetch messages published in MQTT broker (or use the code as example).
Run the MQTT broker:
$ systemctl start mosquitto
Run the MQTT-ASGI interface (similar to daphne)
$ asgimqtt my_django_project.asgi:channels_layer
Define a route in my_django_project/routing.py
from channels import route
from my_django_app.consumers import on_mqtt_message
channels_routing = [
route("mqtt.sub", on_mqtt_message),
]
Implement a consumer (e.g. store the MQTT messages in database) in my_django_app/consumers.py
from .models import MqttMessage
def on_mqtt_message(message):
# do something with the message
MqttMessage(topic=message["topic"],
payload=message["payload"],
qos=message["qos",
host=message["host"],
port=message["port"]).save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With