arduino-libraries / ArduinoMqttClient

ArduinoMqttClient Library for Arduino
GNU Lesser General Public License v2.1
186 stars 73 forks source link

Failure to connect to 127.0.0.1 (localhost) using Mosquitto Broker #87

Closed Rhyzhang closed 1 year ago

Rhyzhang commented 1 year ago

Hi,

I am following this guide for my school project: [https://docs.arduino.cc/tutorials/uno-wifi-rev2/uno-wifi-r2-mqtt-device-to-device]

The receiver code is basically the same as the one given in the example folder of this library.

When code works perfectly fine when using the broker "test.mosquitto.org" as shown below: image

However, it fails when I try to connect to my local host. image

I attempted to figure out if it was my localhost bugging out but it was working fine as I was able to publish. image image

I can't figure out why it can't connect to localhost.

Thank you, Ryan

imatrisciano commented 1 year ago

By using localhost on arduino you are telling it that the MQTT broker is located on arduino itself. This is not the case, the broker is located on your computer.

You should open a terminal on you computer and launch ipconfig. This will show you a bunch of information, but the only line you are interested in is IPv4 Address, this will look like 192.168.0.147 . This is the IP address of your computer.

By connecting the arduino and the computer to the same network, you can access the broker on arduino by using that IP instead of localhost. Note that the IP address is chosen by the DHCP server in your network and it can change. To prevent that you can disable DHCP on your computer, setting a custom IPv4, or you can configure your router to always assign the same IP to your computer