Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Django Channels to display MQTT messages in realtime?

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?

like image 714
Haike Zegwaard Avatar asked May 05 '16 09:05

Haike Zegwaard


1 Answers

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()
like image 67
Emanuele Di Giacomo Avatar answered Nov 17 '22 04:11

Emanuele Di Giacomo