MQTT:如何在不调用loop_forever()的情况下发送消息

时间:2017-01-14 17:56:55

标签: python mqtt

我使用MQTT一段时间来监控我订阅的一些频道。现在我想实现发送消息作为对状态的反应。我用下面的代码运行它,我只是在on_message回调中做出反应(最后的代码1)。但是这段代码使用了

loop_forever()

在阻塞的主代码中。

我想做的是向MQTT发送一条消息。当我尝试以下(使用所有不同的循环函数)时,MQTT服务器不会收到任何内容:

import paho.mqtt.client as mqtt

if __name__ == "__main__":

    mqtt_client = mqtt.Client()
    mqtt_client.connect("192.168.178.204", 1883, 60)
    mqtt_client.username_pw_set(username="test", password="test")

    mqtt_client.publish(topic='TEST', payload='CCCCCCCCC', retain=False)
    mqtt_client.loop_write()
    # mqtt_client.loop()
    # mqtt_client.loop_start()    

    mqtt_client.disconnect()

如何向MQTT发送不阻止进程的消息?

代码1:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, rc):
    topic_list = [("TEST_MS", 1)]
    if rc == 0:
        print("Successful connected and subscribed to: {}".format(topic_list))
    client.subscribe(topic_list)


def on_message(client, userdata, msg):
    print(msg.payload)
    client.publish(topic='TEST_MS2', payload=msg.payload, retain=False)


def on_publish(client, userdata, mid):
    print("message published")


def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))

if __name__ == "__main__":

    mqtt_client = mqtt.Client()

    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.on_publish = on_publish
    mqtt_client.on_subscribe = on_subscribe

    mqtt_client.connect("192.168.178.204", 1883, 60)
    mqtt_client.username_pw_set(username="test", password="test")

    # mqtt_client.publish(topic='TEST_MS', payload='CCCCCCCCC', retain=False)
    mqtt_client.loop_forever()

    mqtt_client.disconnect()

1 个答案:

答案 0 :(得分:1)

如果您只想发送一条消息,然后退出,请专门为此使用API​​。 Docs here

import paho.mqtt.publish as publish

publish.single("paho/test/single", "payload", hostname="iot.eclipse.org")