Search code examples
mqttmosquittohivemq

Hivemq java client on reconnect auth username and password not going it is trying to reconnect with username and password


When wifi off and on then on reconnect it is not sending username and password in auth which give UN_AUTHORIZED error from broker. I'm using Mosquitto with mosquitto-go-auth.

val mqttClient = MqttClient.builder().useMqttVersion5()
            .identifier(UUID.randomUUID().toString())
            .serverHost("10.0.2.2")
            .serverPort(1883)
            .automaticReconnectWithDefaultConfig()
            .addConnectedListener {
                Log.d("MqttHelper", "addConnectedListener => $it")
            }
            .addDisconnectedListener {
                Log.d("MqttHelper", "addDisconnectedListener => ${it.cause}")
            }
            .buildAsync()
        mqttClient.connectWith().simpleAuth().username("guest").password("guest".toByteArray())
            .applySimpleAuth().send()
            .whenComplete { connAck, throwable ->
                if (throwable != null) {
                    Log.e("MqttHelper", "connect error", throwable)
                    // handle failure
                } else {
                    Log.d("MqttHelper", "Connected successfully => connAck: $connAck")
                }
            }

Solution

  • You set the username and password on the connect operation only, so they are used only for the first connect and not for any reconnects.

    Instead you can set the username and password directly on the client, like in the following code snippet:

    val mqttClient = MqttClient.builder().useMqttVersion5()
            ...
            .automaticReconnectWithDefaultConfig()
            .simpleAuth()
                .username("guest")
                .password("guest".toByteArray())
                .applySimpleAuth()
            .buildAsync()