Go Down

Topic: Connection problem to MQTT broker (Read 249 times) previous topic - next topic

Ramzi19

Hi
my arduino client can't connect to the public broker test.mosquitto.com.

The Serial Monitor output: Connecting to MQTT... failed state : -2

Here is the code, where is the problem?I don't find it :

#include <PubSubClient.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01};

const char* mqttServer = "test.mosquitto.com";
const int mqttPort = 1883;
//const char* mqttUser = "YourMQTTUsername";
//const char* mqttPassword = "YourMQTTPassword";
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

void setup_Ethernet(){
  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    //delay to let Etnernet shield initialize
    delay(1000);
  }
    //connection succesful
    Serial.println("Connection Successful");
    Serial.println("--------------------");



void callback(char* topic, byte* payload, unsigned int length)
{
  Serial.print("Messageved in topic: ");
  Serial.println(topic);
  Serial.print("Message :");
  for(int i = 0; i < length; i++) {
    Serial.print((char)payload);
  }
  Serial.println();
}

void setup() {
  Serial.begin(9600);
  setup_Ethernet();
  mqttClient.setServer(mqttServer,mqttPort);
  mqttClient.setCallback(callback);
  while(!mqttClient.connected()) {
      Serial.println("Connecting to MQTT...");
      if (mqttClient.connect("arduinoClient")) {
          Serial.println("connected");
      }else{
          Serial.print("failed state : ");
          Serial.println(mqttClient.state());
          delay(2000);
           }
      }
   mqttClient.publish("test/arduino","Hello Arduino world");
   mqttClient.subscribe("test/arduino");
}

void loop()
{
  mqttClient.loop();
}

Go Up