1

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?.

8
  • 1
    What is in the logs of the MQTT broker?
    – StarCat
    Commented Dec 22, 2022 at 11:40
  • @StarCat how do I check the log file? I am not able to find it.
    – bardulia
    Commented Dec 22, 2022 at 11:50
  • @StarCat maybe I can't find it because I am executing mosquitto as a service? also I am not able to modify conf file
    – bardulia
    Commented Dec 22, 2022 at 12:11
  • 2
    @timemage I have installed MQTT Explorer on the PC, it is very useful to check the traffic. Thanks!
    – bardulia
    Commented Dec 25, 2022 at 12:34
  • 2
    @StarCat I was finally able to run mosquitto correctly, also I am writing now the log into a text file. In my answer I have put all the code. Thanks.
    – bardulia
    Commented Dec 25, 2022 at 17:53

2 Answers 2

3

The issue was coming from mosquitto local broker, which was being blocked by windows 10 firewall. When I executed mosquitto with the correct permissions on its folder (read and write for "all users") and with correct mosquitto configuration file, the following window popped up and I clicked on to allow both private and public connections:

n

I also use the following batch file to load mosquitto and it works all the time:

cd "C:\Program Files\mosquitto"
del mosquitto.log
mosquitto -v -c mosquitto.conf

This is the content of my mosquitto configuration file:

listener 1883
allow_anonymous true
log_type error
log_type warning
log_type notice
log_type information
connection_messages true
log_timestamp true
log_dest file C:\Program Files\mosquitto\mosquitto.log

Now I am able to use MQTT from Arduino connected to a router.

-1

With a bit of research you can see that return code two is:

2 Connection refused: client identifier not allowed by server.

My guess is that you forgot to add the login details in the code, or the code fails because the client ID is not a c-string. Try something like this (replace with appropriate values):

if (client.connect(clientId.c_str(), mqttUsername, mqttPassword)){

1
  • It was a firewall isse when executing mosquitto, but thanks anyway!
    – bardulia
    Commented Dec 25, 2022 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.