Skip to content

Commit

Permalink
Add onConnected and onDisconnected callbacks to MQTT client
Browse files Browse the repository at this point in the history
  • Loading branch information
davidepianca98 committed Feb 9, 2024
1 parent 87b2033 commit c10f27e
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions kmqtt-client/src/commonMain/kotlin/MQTTClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ public class MQTTClient(
private val willRetain: Boolean = false,
private val willQos: Qos = Qos.AT_MOST_ONCE,
private val enhancedAuthCallback: (authenticationData: UByteArray?) -> UByteArray? = { null },
private val onConnected: (connack: MQTTConnack) -> Unit = {},
private val onDisconnected: (disconnect: MQTTDisconnect?) -> Unit = {},
private val publishReceived: (publish: MQTTPublish) -> Unit
) {

Expand Down Expand Up @@ -301,23 +303,27 @@ public class MQTTClient(
e.printStackTrace()
disconnect(e.reasonCode)
close()
onDisconnected(null)
throw e
} catch (e: EOFException) {
lastException = e
println("EOF")
close()
onDisconnected(null)
throw e
} catch (e: IOException) {
lastException = e
println("IOException ${e.message}")
disconnect(ReasonCode.UNSPECIFIED_ERROR)
close()
onDisconnected(null)
throw e
} catch (e: Exception) {
lastException = e
println("Exception ${e.message} ${e.cause?.message}")
disconnect(ReasonCode.IMPLEMENTATION_SPECIFIC_ERROR)
close()
onDisconnected(null)
throw e
}
} else {
Expand Down Expand Up @@ -434,6 +440,7 @@ public class MQTTClient(
send(it.value.toByteArray())
}
}
onConnected(packet)
}

private fun handlePublish(packet: MQTTPublish) {
Expand Down Expand Up @@ -602,6 +609,7 @@ public class MQTTClient(
throw MQTTException(disconnect.reasonCode)
}
}
onDisconnected(disconnect)
}

private fun close() {
Expand Down

0 comments on commit c10f27e

Please sign in to comment.