我有一个项目将 MQTT 消息从 ESP 发布到在 Pi 上运行的代理和在 Pi 上运行的客户端。消息从 ESP 可靠地发送到代理,因为我可以使用
mosquitto_sub
观察到它们,但是客户端只是偶尔收到它们。我尝试将 QOS 设置为 1 和 2,但仍未解决。想知道是否有人可以帮助我发现问题。
这里是 ESP(micropython)上的代码——这有效地工作得很好:
from umqtt.simple import MQTTClient
broker_ip = "[IP]"
client_name = "[client]"
user = "[user]"
password = "[password]"
def connect_publish(broker, client, topic, message, user, password):
print("Creating client object...")
client = MQTTClient(client_id=client_name,
server=broker_ip,
user=user,
password=password,
keepalive=60)
print("Connecting to server...")
client.connect()
print("Publishing message")
client.publish(topic = topic, msg = str(message), qos = 1)
print("Published", message, "to", topic)
print("Disconecting from server")
client.disconnect()
[function to connect to wifi]
[initialize sensor]
while True:
if [sensor_trigger]:
connect_publish(broker = broker_ip,
client = client_name,
topic = b"sensor",
message = "on",
user = user,
password = password)
客户端代码 - 在 Pi (python) 上运行:
#!/usr/bin/env python3
import paho.mqtt.client as paho
import time
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected with result code " + str(rc))
else:
print("Failed to subscribe, code:", rc)
client.subscribe("sensor", qos = 1)
def on_message(client, userdata, msg):
print(msg.topic+" "+ msg.payload.decode())
if msg.payload.decode() == "on":
if [some further conditions defined in variables below]:
[do something]
#Initialize the variables for MQTT
BROKER = '[IP]'
#uname and password for mqtt client stored on pi: /etc/mosquitto/passwd
uname = '[user]'
pwd = '[password]'
#Initialize all the paho functions
client = paho.Client('[name]')
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(password = pwd, username = uname)
client.connect(host = BROKER)
client.loop_start()
[initialize some more variables]
while True:
[update some variables]
time.sleep(0.1)
本质上,我在代理上可靠地看到了消息
mosquitto_sub
,但是在客户端上运行的on_message
函数中没有看到打印语句(我也没有看到命令的结果)——即使使用了qos = 1
。我试了 2 次,没什么区别。