You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32 MQTT发布端发送成功但Python订阅端收不到消息

ESP32 MQTT发布成功但Python订阅端无消息接收

ESP32上的MQTT发布端运行时终端输出"success sent a data",但Python订阅端无法接收到任何消息,已确认两端token一致。

ESP32发布端原代码

import network 
import json
import time
from umqtt.simple import MQTTClient

net = network.WLAN(network.STA_IF)
net.active(True)

while True:
    try:
        net.connect('Office_CWG', 'Unais2020')
    except OSError as e:
        print(e)
    time.sleep(1)
    if net.isconnected():
        print('Connected') 
        break
    
broker = 'broker.hivemq.com' 
client = MQTTClient('vito', broker)
client.connect()

def send(topic, pesan):
  client.publish(topic, data)
  print ('success sent a data')
  
sensor = {
    'topic': 'active_1',
    'current': '25',
    'volt': '220',
    'frekuensi': '50',
    'activePower': '100',
    'energy': '90',
    'ambienceTemperature': '36',
    'jointTemperature': '36'
}
data = json.dumps(sensor)
topic = 'vito'
send(data, topic)

Python订阅端原代码

import paho.mqtt.client as mqtt
import json


def connect(client, userdata, flags, rc):  # rc = return code if 1 = error
    if rc == 0:
        rc = "success"
    else:
        rc = "error"
    print("Connected to mqtt "+str(rc))
    client.subscribe("vito")


def message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    # pesan = json.loads(str(msg.payload.decode("utf-8")))
    # print(pesan['data'])
    # # print(pesan['message']['alertJoint'])


client = mqtt.Client()
client.on_connect = connect
client.on_message = message

client.connect("broker.hivemq.com")
client.loop_forever()

问题分析与修正

核心错误

  1. send函数参数顺序颠倒:
    定义send(topic, pesan)时,第一个参数是主题,第二个是消息,但调用时写成了send(data, topic),把消息和主题的位置搞反了,导致实际发布的主题是JSON格式的消息内容,而非你预期的vito。

  2. send函数内部变量误用:
    函数内调用client.publish(topic, data),但data是全局变量,不是传入的pesan参数,既降低了函数通用性,也可能引发后续逻辑错误。

修正后的ESP32发布端代码

import network 
import json
import time
from umqtt.simple import MQTTClient

net = network.WLAN(network.STA_IF)
net.active(True)

while True:
    try:
        net.connect('Office_CWG', 'Unais2020')
    except OSError as e:
        print(e)
    time.sleep(1)
    if net.isconnected():
        print('Connected') 
        break
    
broker = 'broker.hivemq.com' 
client = MQTTClient('vito', broker)
# 添加MQTT连接错误排查
try:
    client.connect()
    print("Connected to MQTT broker")
except Exception as e:
    print(f"MQTT connect failed: {e}")

def send(topic, pesan):
  client.publish(topic, pesan)  # 使用传入的消息参数
  print ('success sent a data')
  
sensor = {
    'topic': 'active_1',
    'current': '25',
    'volt': '220',
    'frekuensi': '50',
    'activePower': '100',
    'energy': '90',
    'ambienceTemperature': '36',
    'jointTemperature': '36'
}
data = json.dumps(sensor)
topic = 'vito'
send(topic, data)  # 修正参数顺序:先主题,后消息

补充检查建议

  • 确认ESP32与MQTT broker的连接状态:添加的try-except块可快速排查连接失败问题。
  • 若仍有问题,可在Python订阅端临时订阅#(通配符),查看ESP32实际发布的主题和内容,进一步定位问题。

内容的提问来源于stack exchange,提问作者Vito Jihad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 17:58:24