如何使用MOSQUITO测试python paho mqtt?

2024-03-28 06:10:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想测试MOSQUITO MQTT Python客户端端口

import json

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    """Called when connected to MQTT broker."""
    client.subscribe("hermes/intent/#")
    client.subscribe("hermes/nlu/intentNotRecognized")
    print("Connected. Waiting for intents.")

def on_disconnect(client, userdata, flags, rc):
    """Called when disconnected from MQTT broker."""
    client.reconnect()

def on_message(client, userdata, msg):
    """Called each time a message is received on a subscribed topic."""
    nlu_payload = json.loads(msg.payload)
    if msg.topic == "hermes/nlu/intentNotRecognized":
        sentence = "Unrecognized command!"
        print("Recognition failure")
    else:
        # Intent
        print("Got intent:", nlu_payload["intent"]["intentName"])

        # Speak the text from the intent
        sentence = nlu_payload["input"]

    site_id = nlu_payload["siteId"]
    client.publish("hermes/tts/say", json.dumps({"text": sentence, "siteId": site_id}))


# Create MQTT client and connect to broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message

client.connect("localhost", 1883)
client.loop_forever()

我用命令运行它

$ python script.py` 
Connected. Waiting for intents.

mosquitto是否发送POST请求?还是我必须向莫斯奎托提出请求?我应该如何创建请求以便获得

Got intent: SetTimer

Tags: clientjsonmessageondefconnecthermesbroker
1条回答
网友
1楼 · 发布于 2024-03-28 06:10:45

MQTT不是HTTP,POST是在MQTT上下文中没有意义的HTTP动词

MQTT是一种发布/订阅协议,其中as HTTP是一种请求/响应协议

您发布的代码只订阅了2个主题,它不会发布任何内容(直到收到消息)。因此,除非您有另一个应用程序将消息发布到python代码订阅的2个主题中的1个,否则它将坐在那里等待消息

如果需要,可以使用MOSQUITO命令行工具发送消息。e、 g

mosquitto_pub -t hermes/intent/foo -m '{"intent": { "intentName": "SetTimer"}}'

相关问题 更多 >