Home:ALL Converter>Django Channels with MQTT

Django Channels with MQTT

Ask Time:2021-09-23T21:05:00         Author:Vimalan E

Json Formatter

Am trying to create websocket using django channels and integrate mqtt with channels and mqtt publish message should be received by the function inside consumer.py should be sent to websocket client. I have consumer channel like below

consumer.py

from channels.consumer import AsyncConsumer
from paho.mqtt import client as Mqtt

class Testing(AsyncConsumer):
    async def websocket_connect(self, event):
        obj = Mqtt.Client()  
        obj.connect("localhost", 1883, 60)
        obj.on_message = self.updater
        obj.subscribe("Testing")
        obj.loop_start()


    async def updater(self, arg1, arg2, message):
           print(message)
           await self.send({
                "type": "websocket.send",
                "text": message})

    async def websocket_receive(self, text_data):
        pass

In the above mqtt connection has happened but if I publish a message to the topic its not working. updater function inside consumer.py is not being called. How to achieve this ?

Author:Vimalan E,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69300636/django-channels-with-mqtt
yy