0

I am trying to connect my raspberry pi Pico W to a virtual machine which has a mqtt broker in it and a node red server. My MQTT broker is password protected. I have added the MQTT broker IP in the MQTT node on node red and the connection runs fine on node red. Now I am trying to write a micro-python code using thonny in the pi chip to publish a message to the server. I have been trying for day but my code is not able to connect my device to the mosquitto broker it is not able to get the CONNACK signal from the broker.

this is my main code

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

the mqtt_as python code I have downloaded from a website. the code is big, so here is the link

https://github.com/peterhinch/micropython-mqtt/blob/master/mqtt_as/mqtt_as.py

and I am getting this error

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')

I have followed every instruction from the above link and every other website I can find. please help me. I know there might be a silly mistake but please help I have spend a lot of time in it.

  • Please be clear here, are you using a Raspberry Pi Zero w or a Raspberry Pi Pico W? The micro python implies the Pico W – hardillb Jul 08 '23 at 18:45
  • Also [edit](https://stackoverflow.com/posts/76643874/edit) the question to include the MQTT (mosquitto) broker logs. Best guess is that the broker is running in local only mode. – hardillb Jul 08 '23 at 18:47
  • Have you verified that you can successfully connect to the MQTT broker using an existing client like `mosquitto_pub`/`mosquitto_sub`? – larsks Jul 08 '23 at 19:34
  • yes the broker is working because when send message on node red using one publisher mqtt node and one subscriber mqtt node the messages were successfully sent. – Magnus Bane Jul 10 '23 at 08:44
  • I also have a user and password saved with my mosquitto broker where where should I add the details of that in the code. I did tried to add them in the mqtt_as file but still didn't got any result. Can you tell me where i should put the user and password. I think that may solve the problem. – Magnus Bane Jul 10 '23 at 09:37
  • Just because Node-RED can connect doesn't mean that broker is configured correctly, if the broker and Node-RED are on the same VM it would still be able to connect. Without seeing the `mosquitto.conf` file we can't say for sure. The timeout also implies it's not user/password but a routing problem, see my answer. – hardillb Jul 10 '23 at 13:07

1 Answers1

0

This is probably a routing a problem.

You have said that the broker is running in a VM and 192.168.122.x is the default IP address range assigned to VMs by Linux/LibVirt.

Given this the most likely cause is that the Pico W doesn't know how to read the VM. It will be getting an IP address from your local LAN, assuming this is a home network then this will be from the DHCP server on your router.

As part of the DHCP setup it will also be given a default route which again will be the router.

The problem is that the router doesn't know how to reach the VM because it only knows about the subnet it's assigned to the LAN, and all other traffic it will send out over the internet via your ISP.

You have 2 choices

  1. Setup a route on the router that sends all traffic to 192.168.122.x to the machine hosting the VM. You may also have to mess with the firewall/routes on the host machine to have it allow traffic
  2. Configure the VM to use a "bridged" network adaptor rather than "NAT" interface, this should mean that the VM will get a IP address from the router via DHCP and appear to be directly connected to the LAN.

Option 2 is probably best for this.

hardillb
  • 54,545
  • 11
  • 67
  • 105