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

ESP32通过MicroPython连接本地MQTT Broker失败求助

ESP32 MicroPython连接本地MQTT Broker报错OSError: [Errno 104] ECONNRESET

问题描述

使用以下MicroPython代码让ESP32连接本地MQTT Broker时,出现OSError: [Errno 104] ECONNRESET错误,但切换到公共Broker(如broker.mqttdashboard.com)时代码可正常运行。已尝试在Broker配置中添加listener 1883和Allow anonymous True,但问题未解决。

代码片段

from umqtt.simple import MQTTClient
import network
import utime as time

# Device Setup
DEVICE_ID = "wokwi001"

MQTT_CONTROL_TOPIC      = "iot/control"

# WiFi Setup
WIFI_SSID       = "####"
WIFI_PASSWORD   = "######"

# MQTT Setup
#MQTT_BROKER             = "broker.mqttdashboard.com"
MQTT_BROKER             = "localhost"
#MQTT_BROKER             = "192.168.1.105"
MQTT_CLIENT             = DEVICE_ID

def did_recieve_callback(topic, message):
    print('\n\nData Recieved! \ntopic = {0}, message = {1}'.format(topic, message))

    # device_id/lamp/color/state
    # device_id/lamp/state
    # lamp/state
    if topic == MQTT_CONTROL_TOPIC.encode():
        #if message == ('{0}/lamp/red/on'.format(DEVICE_ID)).encode():
        #    RED_LED.on()
        #elif message == ('{0}/lamp/red/off'.format(DEVICE_ID)).encode():
        #    RED_LED.off()
        if message == ('{0}/lamp/blue/on'.format(DEVICE_ID)).encode():
            BLUE_LED.on()
        elif message == ('{0}/lamp/blue/off'.format(DEVICE_ID)).encode():
            BLUE_LED.off()
        elif message == ('{0}/lamp/on'.format(DEVICE_ID)).encode() or message == b'lamp/on':
            #RED_LED.on()
            BLUE_LED.on()
        elif message == ('{0}/lamp/off'.format(DEVICE_ID)).encode() or message == b'lamp/off':
            #RED_LED.off()
            BLUE_LED.off()
        else:
            return

        send_led_status()

def mqtt_connect():
    print("Connecting to MQTT broker ...", end="")
    mqtt_client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, user="", password="")
    mqtt_client.set_callback(did_recieve_callback)
    mqtt_client.connect()
    print("Connected.")
    mqtt_client.subscribe(MQTT_CONTROL_TOPIC)
    return mqtt_client

# Connecting to Wifi
wifi_client = network.WLAN(network.STA_IF)
wifi_client.active(True)
print("Connecting device to WiFi")
wifi_client.connect(WIFI_SSID, WIFI_PASSWORD)

# Wait until WiFi is Connected
while not wifi_client.isconnected():
    print("Connecting")
    time.sleep(0.1)
print("WiFi Connected!")
print(wifi_client.ifconfig())

# Connect to MQTT
mqtt_client = mqtt_connect()

#waiting until MQTT is connected
#while not mqtt_client.isconnected():
#    print("Connecting")
#    time.sleep(0.1)
print("Mqtt Connected!")

错误信息

Connecting to MQTT broker ...Traceback (most recent call last):
  File "<stdin>", line 67, in <module>
  File "<stdin>", line 48, in mqtt_connect
  File "umqtt/simple.py", line 68, in connect
OSError: [Errno 104] ECONNRESET

解决建议

1. 修正localhost的使用问题

ESP32上的localhost指向设备自身,而非你的本地Broker主机。必须替换为Broker所在主机的局域网IP地址(比如你注释掉的192.168.1.105),确保ESP32和Broker在同一WiFi局域网内。

2. 验证Broker的监听地址

检查MQTT Broker的配置,确保listener 1883绑定的是0.0.0.0或局域网IP,而非仅127.0.0.1。如果Broker只监听本地回环地址,ESP32无法从局域网访问它。

  • 以Mosquitto为例,正确配置应为:
    listener 1883 0.0.0.0
    allow_anonymous true
    
    注意:部分Broker对配置项大小写敏感,Allow需改为小写allow。

3. 测试网络连通性

在ESP32上添加代码,测试与Broker IP的端口连通性:

import socket
s = socket.socket()
try:
    s.connect(("192.168.1.105", 1883))
    print("Port 1883 is reachable")
    s.close()
except OSError as e:
    print(f"Connection failed: {e}")

如果连接失败,排查:

  • 主机防火墙是否开放1883端口
  • ESP32和Broker是否在同一WiFi网段
  • Broker服务是否正常运行(用本地MQTT客户端测试连接)

4. 检查MQTT客户端参数

确保MQTTClient初始化时端口参数正确(默认1883,若Broker修改了端口需手动指定):

mqtt_client = MQTTClient(MQTT_CLIENT, MQTT_BROKER, port=1883, user="", password="")

5. 查看Broker日志

查看MQTT Broker的日志文件,获取连接失败的具体原因(比如认证失败、拒绝连接等),这能快速定位问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:57:44