无法将 Raspberry Pi Pico W 连接到 MQTT 代理,未收到 CONNACK

问题描述 投票:0回答:1

我正在尝试将 Raspberry Pi Pico W 连接到运行 MQTT 代理和 Node-RED 服务器的虚拟机。 MQTT 代理受密码保护。我在 Node-RED 上的 MQTT 节点中添加了 MQTT 代理 IP,并且连接在 Node-RED 上运行良好。我正在尝试在 Raspberry Pi Pico 上使用 Thonny 编写一个 MicroPython 脚本来向服务器发布消息。我无法将我的设备连接到 MQTT 代理。它没有从经纪人那里得到 CONNACK 信号:

from mqtt_as import MQTTClient, config
import uasyncio as asyncio
import socket

# Local configuration
config['ssid'] = 'user'
config['wifi_pw'] = 'password'
config['server'] = '192.168.122.1'  # Change to suit e.g. 'iot.eclipse.org'

async def messages(client):  # Respond to incoming messages
    async for topic, msg, retained in client.queue:
        print((topic, msg, retained))

async def up(client):  # Respond to connectivity being (re)established
    while True:
        await client.up.wait()  # Wait on an Event
        client.up.clear()
        await client.subscribe('Nodered', 0)  # renew subscriptions

async def main(client):
    print("Hello")
    await client.connect()
    print("Hello")
    for coroutine in (up, messages):
        asyncio.create_task(coroutine(client))
    n = 0
    while True:
        await asyncio.sleep(5)
        print('publish', n)
        # If WiFi is down the following will pause for the duration.
        await client.publish('Nodered', 'hello there', qos = 0)
        n += 1

config["queue_len"] = 1  # Use event interface with default queue size
MQTTClient.DEBUG = True  # Optional: print diagnostic messages
client = MQTTClient(config)
try:
    asyncio.run(main(client))
finally:
    client.close()  # Prevent LmacRxBlk:1 errors

mqtt_as Python 代码。错误:

MPY: soft reboot
Hello
Checking WiFi integrity.
Got reliable connection
Connecting to broker.
Traceback (most recent call last):
  File "<stdin>", line 38, in <module>
  File "uasyncio/core.py", line 1, in run
  File "uasyncio/core.py", line 1, in run_until_complete
  File "uasyncio/core.py", line 1, in run_until_complete
  File "<stdin>", line 22, in main
  File "/lib/mqtt_as.py", line 645, in connect
  File "/lib/mqtt_as.py", line 314, in _connect
  File "/lib/mqtt_as.py", line 213, in _as_read
OSError: (-1, 'Timeout on socket read')
mqtt mosquitto micropython raspberry-pi-pico
1个回答
0
投票

这可能是路由问题。

您说过代理在虚拟机中运行,192.168.122.x 是 Linux/LibVirt 分配给虚拟机的默认 IP 地址范围。

鉴于此,最可能的原因是 Pico W 不知道如何读取 VM。它将从您的本地 LAN 获取 IP 地址,假设这是家庭网络,那么这将来自您路由器上的 DHCP 服务器。

作为 DHCP 设置的一部分,还将获得一条默认路由,该路由同样是路由器。

问题是路由器不知道如何到达虚拟机,因为它只知道分配给 LAN 的子网,以及它将通过 ISP 通过互联网发送的所有其他流量。

你有2个选择

  1. 在路由器上设置一条路由,将所有到 192.168.122.x 的流量发送到托管虚拟机的计算机。您可能还必须弄乱主机上的防火墙/路由才能允许流量
  2. 将虚拟机配置为使用“桥接”网络适配器而不是“NAT”接口,这意味着虚拟机将通过 DHCP 从路由器获取 IP 地址,并且看起来直接连接到 LAN。

选项 2 可能最适合此目的。

© www.soinside.com 2019 - 2024. All rights reserved.