Search code examples
djangomqttmosquittopaho

How to publish messages to mqtt from views [django]?


I am trying to integrate paho.mqtt into django to publish msgs to mosquitto broker, I have searched but I havent found much tutorials on how I can achieve it.

Well i tried to put this code into mqtt.py:

from paho.mqtt import client as mqtt_client

topic = "#topic#"

def connect_mqtt()  -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    client = mqtt_client.Client(topic)
    client.username_pw_set('#username#', '#psswd#')
    client.on_connect = on_connect
    client.connect('####the host##', 1883)
    return client


def publish(client):
    msg = 'test test'
    result = client.publish(topic, msg)



def run():
    client = connect_mqtt()
    publish(client)
    client.loop_forever()

and in init.py

from . import mqtt

client.loop_start()

and when I call run() on views it doesn't work, and runserver it doesn't seem like the right way to do it.

Can somebody explain to me how should I structure my files and system to do it right.

Please any help would be much appreciated.


Solution

  • If someone wants to publish a message from a views function. Use paho-mqtt

    # inside views.py
    # you can modify whether to publish from get/post method.
    from django.http import HttpResponse
    import paho.mqtt.publish as publish
    def publish(request):
        
        publish.single("your pub topic", payload="Your message", hostname="broker url", port=1883)
    
        return HttpResponse("Published")
    

    .

    # inside urls.py
    from . import views
    from django.urls import path
    urlpatterns = [
        path("publish", views.publish, name="mqtt_publish"),
    ]
    

    This one will publish to the topic when you go to host/publish