Disconnected by Server

Hello!

I can connect properly to the broker without any issues.
The problem apparently happens after i send a disconnect and then try to connect.
Sometimes it happens allways and sometimes it happens after a few tries.

The Server sends me a disconnect and as i have automatic reconnect the server spams me with the same message.
“Server sent DISCONNECT.”

This is the code that i use for the connection and disconnect:

fun connectToBroker(b: Broker) {

    viewModelScope.launch {
        broker = b
        try {
            mqttClient = MqttClient.builder()
                .identifier(broker.clientId)
                .serverHost(broker.url)
                .serverPort(broker.port)
                .useMqttVersion5()
                .addConnectedListener{
                    Log.d("MQTT - Builder","Connected: $connectionStatus")
                    updateConnectionStatus(true)
                }
                .addDisconnectedListener{
                    viewModelScope.launch (Dispatchers.IO) {
                        try {
                           val response = apiService?.postData(PostRequestData(
                               49,
                               cause = "${it.cause.message}",
                               source = "${it.source}",
                               error = "",
                           ))
                            var asd = response
                        }catch (e: Exception){
                            Log.d("MQTT - API - Failed", e.message.toString())
                        }
                    }
                    Log.d("MQTT - Builder","Disconnected: ${it.cause.message}")
                    Log.d("MQTT - Builder","Disconnected: ${it.source}")
                    updateConnectionStatus(false)

                }.automaticReconnect().applyAutomaticReconnect().build().toAsync()

            mqttClient.connectWith()
                .cleanStart(true)
                .simpleAuth()
                .username(broker.username)
                .password(broker.password.toByteArray())
                .applySimpleAuth()
                .send()
                .whenComplete { connAck, throwable ->
                    if (throwable != null) {
                        viewModelScope.launch (Dispatchers.IO) {
                            try {
                                var message = ""
                                if(throwable.localizedMessage != null){
                                    message = throwable.localizedMessage!!
                                }
                                val requestData = PostRequestData(
                                    80,
                                    cause = "${throwable.cause}",
                                    source = "${throwable.message}",
                                    error = message,
                                )
                                if(apiService != null){
                                    val apiResponse = apiService.postData(requestData = requestData)
                                }
                                Log.d("MQTT - API - Success", "success")
                            }catch (e: Exception){
                                Log.d("MQTT - API - Failed", e.message.toString())
                            }
                        }
                        Log.d("MQTT - Broker","Connection failed: ${throwable.message}")
                        Log.d("MQTT - Broker","Connection failed: ${throwable.cause}")
                        Log.d("MQTT - Broker","Connection failed: ${throwable.localizedMessage}")

                        updateConnectionStatus(false)
                    } else {
                        Log.d("MQTT - Broker","Connection successful: $connAck")
                        updateConnectionStatus(true)
                    }
                }
        } catch (e: Throwable) {
            println("Connection failed: ${e.message}")
            try {

                val requestData = PostRequestData(
                    106,
                    cause = "",
                    source = "",
                    error = e.message.toString(),
                )
                if(apiService != null){
                    val apiResponse = apiService.postData(requestData = requestData)
                }
                Log.d("MQTT - API - Success", "success")
            }catch (e: Exception){
                Log.d("MQTT - API - Failed", e.message.toString())
            }
        }
    }
}

fun disconnect(){
    if (mqttClient.state.isConnected){
        Log.d("MQTT - ","Disconnect")
        val asd = Mqtt5Disconnect.builder().reasonCode(Mqtt5DisconnectReasonCode.NORMAL_DISCONNECTION)
        val disconnectFuture = mqttClient.disconnect(asd.build())

        // Handle the completion of disconnection
        disconnectFuture.thenAccept { void ->
            Log.d("MQTT - ","Disconnected successfully")
        }.exceptionally { throwable ->
            Log.d("MQTT - ","Disconnected failed - ${throwable.message} - ${throwable.cause} - ${throwable.localizedMessage}")
            null
        }
    }
}

I have some logs and some calls to an external API so that i can catch the errors if i am using the app on the phone.

I am really troubled by this as i cannot understand what it is happening.

In the logs i can see the disconnect before trying to connect.

Any clue how can i tackle this?

Hi @birmsi

Hello and a hearty welcome to the HiveMQ Community! Your interest in MQTT and the HiveMQ broker is much appreciated. We’re always happy to see new users like you.

Try to move authentication code from the “connect” statement to the client builder:

viewModelScope.launch {
        broker = b
        try {
            mqttClient = MqttClient.builder()
                .identifier(broker.clientId)
                .serverHost(broker.url)
                .serverPort(broker.port)
                .useMqttVersion5()
// from the mqttClient.connectWith() move the auth here:
                .simpleAuth() //authentication
                .username(broker.username) //with uesrname
                .password(broker.password.toByteArray()) //and password
                .applySimpleAuth()

                .addConnectedListener{...}
                .addDisconnectedListener{...}
...

I hope it helps
Kind regards
Dasha from HiveMQ Team