Nauman Shakir
Nauman Shakir

Reputation: 105

The ESP8266 is not connecting to MQTT broker hivemq

I have a simple code in which I am trying to connect to HiveMQ open broker and subscribe to a topic to listen to incoming messages.

here is the code

        #include <ESP8266WiFi.h>
        #include <PubSubClient.h>

        const char *ssid =  "P9Inct";       // cannot be longer than 32 characters!
        const char *pass =  "P9inct123*";       //
        const char *mqtt_server = "broker.hivemq.com";
        const int mqtt_port = 1883;
        const char *mqtt_user = "testUser";
        const char *mqtt_pass = "abc123";
        const char *mqtt_client_name = "12312312332212";
        #define BUFFER_SIZE 100

        String incoming="";
        String did="";
        String state="";
        // Update these with values suitable for your network.
        //IPAddress server(172, 16, 0, 2);
        String DEVID="8581870006";//"6931108641";//old

        WiFiClient wclient;
        PubSubClient client(wclient, mqtt_server,mqtt_port);

        void callback(const MQTT::Publish& pub) {
          // handle message arrived
          Serial.print(pub.topic());
          Serial.print(" => ");
          if (pub.has_stream()) {
            uint8_t buf[BUFFER_SIZE];
            int read;
            while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
              Serial.write(buf, read);
            }
            pub.payload_stream()->stop();
            Serial.println("");
          } else
            Serial.println(pub.payload_string());

        ////////////////////////////////////////////

        incoming=String(pub.payload_string());
        Serial.println(pub.payload_string());
        Serial.println(incoming);

          }




        void setup() {
          // Setup console
          Serial.begin(115200);
          delay(10);
          Serial.println();
          Serial.println();
        }

        void loop() {
          if (WiFi.status() != WL_CONNECTED) {
            Serial.print("Connecting to ");
            Serial.print(ssid);
            Serial.println("...");
            WiFi.begin(ssid, pass);

            if (WiFi.waitForConnectResult() != WL_CONNECTED)
              return;
            Serial.println("WiFi connected");
          }

          if (WiFi.status() == WL_CONNECTED) {
            if (!client.connected()) {
              Serial.println("Connecting to MQTT server");
              if (client.connect(MQTT::Connect(mqtt_client_name)
                     .set_auth(mqtt_user, mqtt_pass))) {
                Serial.println("Connected to MQTT server");
            client.set_callback(callback);


            client.subscribe("diy/1"+DEVID);
              } else {
                Serial.println("Could not connect to MQTT server");   
              }
            }

            if (client.connected())
              client.loop();
          }

        }

WiFi connection is working fine but, communication via broker is not working and it always gives the message "Could not connect to MQTT server". How to make esp8266 work with HiveMQ broker. The dashboard of borker is http://www.mqtt-dashboard.com/

Upvotes: 2

Views: 1682

Answers (1)

cagdas
cagdas

Reputation: 1644

So, you are connected. You have unnecessary print line in your loop. Try to adapt on this :

/* Incoming data callback. */
void callback(char* topic, byte* payload, unsigned int length)
{
  char payloadStr[length + 1];
  memset(payloadStr, 0, length + 1);
  strncpy(payloadStr, (char*)payload, length);
  Serial.printf("Topic : [%s]\n", topic);
  Serial.printf("Payload : %s\n", payloadStr);
}

void performConnect()
{
  uint16_t connectionDelay = 5000;
  while (!client.connected())
  {
    if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_KEY))
    {
      Serial.printf("Connected to Broker.\n");
      client.subscribe("diy/1"+DEVID);
    }
    else
    {
      Serial.printf("MQTT Connect failed, rc = %d\n", client.state());
      Serial.printf("Trying again in %d msec.\n", connectionDelay);
      delay(connectionDelay);
    }
  }
}

void loop()
{
  if (!client.connected())
  {
    performConnect();
  }
  client.loop();
}

Upvotes: 2

Related Questions