Django频道-无法将事件发送给使用者

时间:2018-09-24 20:58:45

标签: django websocket mqtt django-channels

我正在使用Django Channels在后台运行MQTT侦听器,并使用Websocket将MQTT事件推送到浏览器。

为此,我编写了一个SyncConsumer,它在Web应用程序启动时在该使用者内触发,我设置了MQTT客户端并注册了on_message处理程序。

问题是当我在on_message处理程序中收到MQTT事件时,无法将任何事件发送到命名通道或Group

请帮助。谢谢

代码:

class MQTTSubscriber(SyncConsumer):

    def subscribe_mqtt(self, message):
        print('starting MQTT listener worker...')

        import paho.mqtt.client as mqtt

        client = mqtt.Client()
        self.client = client
        client.connect(settings.MQTT_HOST)

        def on_connect(client, userdata, flags, rc):
            print('Connected to mqtt broker!')
            client.subscribe('vf/reported/#')

        def on_disconnect(client, userdata, flags, rc):
            print('Disconnected from MQTT broker, reconnecting...')
            client.connect(settings.MQTT_HOST)

        def on_message(client, userdata, msg):
            print('MQTT event received!')
            async_to_sync(get_channel_layer().send)(
                'notify-browser',
                {
                    'type': 'notify.observers',
                }
            )

        client.on_connect = on_connect
        client.on_message = on_message
        client.on_disconnect = on_disconnect
        client.loop_forever()

class NotificationsConsumer(SyncConsumer):

    def notify_observers(self, message):
        print(message)
        ### never called

routing.py

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter([
            url(r'^events/', WebsocketConsumer),
        ])
    ),
    'channel': ChannelNameRouter({
        'subscribe-mqtt': MQTTSubscriber,
        'publish-mqtt': MQTTPublisher,
        'notify-browser': NotificationsConsumer,
    })
})

0 个答案:

没有答案