I have an Arduino Mega with Ethernet connected to a router by cable. Also I have a PC connected to the router (by Wifi) where also the local MQTT broker is installed (mosquitto). Althought the Arduino Ethernet connection seems ok, the MQTT connection does not: I get the return code -2
This is the full code, there are several functions but the MQTT init is the one that fails:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h> // Librería para MQTT
byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x3A, 0xC4 };
byte ip[] = { 192, 168, 1, 100 };
byte gateway[] = { 192, 168, 1, 2 };
byte subnet[] = { 255, 255, 255, 0 };
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
const char *MQTT_BROKER_ADRESS = "192.168.1.101";
const uint16_t MQTT_PORT = 1883;
const char *MQTT_CLIENT_NAME = "mqttx_7c0a0ed3";
void SuscribeMqtt()
{
mqttClient.subscribe("hello/world");
}
void OnMqttReceived(char *topic, byte *payload, unsigned int length)
{
Serial.print("Received on ");
Serial.print(topic);
Serial.print(": ");
String content = "";
for (size_t i = 0; i < length; i++)
{
content.concat((char)payload[i]);
}
Serial.print(content);
Serial.println();
}
void InitMqtt()
{
mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT);
mqttClient.setCallback(OnMqttReceived);
}
void ConnectMqtt()
{
Serial.print("Starting MQTT connection...");
if (mqttClient.connect(MQTT_CLIENT_NAME))
{
SuscribeMqtt();
mqttClient.publish("connected","hello/world");
}
else
{
Serial.print("Failed MQTT connection, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
void HandleMqtt()
{
if (!mqttClient.connected())
{
ConnectMqtt();
}
mqttClient.loop();
}
void CheckLinkStatus() {
auto link = Ethernet.linkStatus();
Serial.print("Link status: ");
switch (link) {
case Unknown:
Serial.println("Unknown");
break;
case LinkON:
Serial.println("ON");
break;
case LinkOFF:
Serial.println("OFF");
break;
}
delay(1000);
}
void setup() {
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
Serial.begin(9600);
Ethernet.begin(mac, ip, gateway, subnet);
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
delay(1500);
InitMqtt();
}
// put your main code here, to run repeatedly:
void loop() {
CheckLinkStatus();
HandleMqtt();
}
I have done ping from the PC IP (192.168.1.101) to the Arduino IP (192.168.1.100) and it is ok. What could be the issue?.