无法连接到 MQTT 代理

无法连接到 MQTT 代理

我尝试使用 MQTT 将 esp32(客户端)连接到 raspberry pi(代理),但遇到了困难。

在代理端,我运行的是 mosquitto (2.0.11)。从 pi,我可以毫无问题地发布和订阅。在三个终端中,我可以:

#Terminal 1:
systemctl stop mosquitto #to stop the daemon
mosquitto #to see a live instance

#Terminal 2:
mosquitto_sub -t 'new' #Term 1 shows new connection

#Terminal 3: 
mosquitto_pub -t 'new' -m 'Test message' #Term 2 shows 'new message'; Term 1 shows new connection and disconnect.

所以我相信代理运行良好。我尝试从 esp32 连接,首先我编辑并/etc/mosquitto/mosquitto.conf添加行anonymous truelistener 1883

然后我加载wifi在boot.py

def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('bubble', 'Littleenginethatcould!')
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())
    
do_connect() #returns the correct IP address, i can ping from my pi and shows on my router

然后我尝试从以下位置建立连接main.py

from umqtt.simple import MQTTClient
from machine import Pin
from time import sleep

CLIENT_NAME = 'esp'
BROKER_ADDR = '192.168.0.10' #static address on the pi
mqttc = MQTTClient(CLIENT_NAME, BROKER_ADDR, keepalive=60)
mqttc.connect()

最后一行引发错误:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "umqtt/simple.py", line 68, in connect
OSError: [Errno 104] ECONNRESET

在线搜索此错误只会得到两个结果,说明某人没有为其代理使用正确的 IP。我确信我的 IP 是正确的。我一直通过 SSH 进入它。

我仍在思考 esp32,所以我尝试将笔记本电脑连接到 pi。我paho-mqtt使用进行安装pip。然后我尝试运行以下命令:

import paho.mqtt.client as mqtt
client = mqtt.Client('Inspiron')
client.connect('192.168.0.10') #static address on the pi

现在最后一行抛出错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/<user>/esp/micropython/lib/python3.10/site-packages/paho/mqtt/client.py", line 914, in connect
    return self.reconnect()
  File "/home/<user>/esp/micropython/lib/python3.10/site-packages/paho/mqtt/client.py", line 1044, in reconnect
    sock = self._create_socket_connection()
  File "/home/<user>/esp/micropython/lib/python3.10/site-packages/paho/mqtt/client.py", line 3685, in _create_socket_connection
    return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source)
  File "/usr/lib/python3.10/socket.py", line 845, in create_connection
    raise err
  File "/usr/lib/python3.10/socket.py", line 833, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

因此,我似乎无法从运行代理的机器以外的任何机器访问代理。我想我已经正确编辑了配置文件,但仍然无法连接。

答案1

答案是,当直接从命令行运行 mosquitto 而不是作为守护进程时,您必须使用标志来调用它-c,并指定修改后的 conf 文件。所以:

mosquitto -c /etc/mosquitto/mosquitto.conf

如果不这样做,它将恢复为不允许匿名客户端的标准配置文件。当作为守护进程运行时,它将自动调用配置文件,因此文件更新可以正常工作。感谢@hardillb(https://stackoverflow.com/users/504554/hardillb

答案2

嗨,今天在 Raspberry Zero 上重新安装 mosquitto 后,我遇到了同样的问题。编辑您的配置文件“/etc/mosquitto/mosquitto.conf”,然后添加以下行:listener 1883

相关内容