首页 > 解决方案 > Django + MQTT 如何在视图中发出请求并等待响应

问题描述

我正在编写一个 django 应用程序,我需要一种方法来请求 MQTT 上的数据并等待响应(或超时)。

考虑到这样的事情:

mqtt.subscribe('response/topic')

mqtt.publish('request/topic', '{my json request message}')
for m in mqtt.on_message():
   if m.payload == '......'
       # OK I have response, render data from response to page, ...

# timeout could be implemented by raising exception in on_message() 

我如何整合 paho mqtt?或者还有其他方法吗?我需要等待视图中几个地方的响应,一个全局on_message回调并不是很有用。

我应该把mqtt.loop_forever()django放在哪里?

谢谢

编辑:我的第一个解决方案是:


import queue
import paho.mqtt.client as mqtt

def mqtt_request(req_topic, resp_topic, payload, timeout=2.0):
    q = queue.Queue()
    def on_message(client, userdata, message):
        q.put(message)

    def on_connect(client, userdata, flags, rc):
        c.subscribe(resp_topic)

    def on_subscribe(client, userdata, mid, granted_qos):
        c.publish(req_topic, payload=payload, qos=0, retain=False)

    c = mqtt.Client()
    c.on_message = on_message
    c.on_connect = on_connect
    c.on_subscribe = on_subscribe
    c.connect_async('127.0.0.1')
    c.loop_start()

    m = None

    # FIXME: it seems that there is some delay between on_message and return
    # of the message...

    try:
        m = q.get(timeout=timeout)
    except queue.Empty:
        pass

    c.loop_stop()
    return m

鉴于用途:

r = mqtt_request('test', 'test2', 'Ahoj')
if r:
    print(r.payload)

标签: python-3.xdjangomqtt

解决方案


推荐阅读