Search code examples
mqttarduino-esp8266

pubsubclient can not connect to broker when using JWT authentication


I'm using pubsubclient library.
I used this function to connect to mosquitto broker which using mosquitto-auth-plug with JWT authentication.

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    String red_token = "eyJhbGciOiJIUzUxMiJ9.*****";
    String deviceTopic = "outTopic";
    //My token length is 205 characters
    //client.connect(strDeviceId.c_str(), red_token.c_str(),"pass", deviceTopic.c_str(), 0, false, CMD_OFF_LINE)
    bool result = client.connect("newClientIdMCU",token,"pass", deviceTopic.c_str(), 0, 0, "offline");
    delay(2000);
    if (result) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish(deviceTopic.c_str(), "hello world");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

This exception occurs when client.connect called:

Attempting MQTT connection...
Exception (9):
epc1=0x40202c6d epc2=0x00000000 epc3=0x00000000 excvaddr=0x445a5a51 depc=0x00000000

ctx: cont 
sp: 3ffef490 end: 3ffef720 offset: 01a0

>>>stack>>>
3ffef630:  3ffe848e 0000075b 3ffee5b8 402023e1  
3ffef640:  3ffe01dc 0afed47d 3ffe8788 0afed47d  
3ffef650:  3ffe85ae 3ffef6c0 3ffef6c0 3ffeffec  
3ffef660:  3ffe848e 3ffee4fc 3ffee500 40202db0  
3ffef670:  514d0400 3f045454 3ffef6c0 402036cd  
3ffef680:  3ffe854e 3ffe853f 00000000 4020371e  
3ffef690:  3ffe8536 3ffee5d0 3ffee6c0 3ffe848e  
3ffef6a0:  00000000 3ffee4fc 3ffee6c0 40201e02  
3ffef6b0:  00000000 3ffe8553 00000000 00000000  
3ffef6c0:  3ffeffec 0000000f 00000008 3fff056c  
3ffef6d0:  000000af 000000a7 3ffee4fc 40203114  
3ffef6e0:  3fffdad0 00000000 3ffee4fc 3ffee6ec  
3ffef6f0:  3fffdad0 3ffee4fc 3ffee6e4 40201eaa  
3ffef700:  3fffdad0 00000000 3ffee6e4 40203834  
3ffef710:  feefeffe feefeffe 3ffee700 40100718  
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,7)


 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

On broker log "New connection...." but Sending CONNACK to clientId (0, 0) can't send. What could be problem?


Solution

  • I change pubsubclient.h file lib from:

    // MQTT_MAX_PACKET_SIZE : Maximum packet size
    #ifndef MQTT_MAX_PACKET_SIZE
    #define MQTT_MAX_PACKET_SIZE 128
    

    to

    // MQTT_MAX_PACKET_SIZE : Maximum packet size
    #ifndef MQTT_MAX_PACKET_SIZE
    #define MQTT_MAX_PACKET_SIZE 256
    

    it works.