Skip to content

Instantly share code, notes, and snippets.

@hussanhijazi
Created November 29, 2018 13:02
Show Gist options
  • Save hussanhijazi/4fd7c737ccb4f1006ad2e36f3108ddcc to your computer and use it in GitHub Desktop.
Save hussanhijazi/4fd7c737ccb4f1006ad2e36f3108ddcc to your computer and use it in GitHub Desktop.
Kotlin Mqtt Client
package br.com.hussan.mqttandroid
import android.content.Context
import android.util.Log
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.IMqttActionListener
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.IMqttToken
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttException
import org.eclipse.paho.client.mqttv3.MqttMessage
class MqttClient(private val context: Context) {
val client by lazy {
val clientId = MqttClient.generateClientId()
MqttAndroidClient(context, "tcp://iot.eclipse.org:1883",
clientId)
}
companion object {
const val TAG = "MqttClient"
}
fun connect(topics: Array<String>? = null,
messageCallBack: ((topic: String, message: MqttMessage) -> Unit)? = null) {
try {
client.connect()
client.setCallback(object : MqttCallbackExtended {
override fun connectComplete(reconnect: Boolean, serverURI: String) {
topics?.forEach {
subscribeTopic(it)
}
Log.d(TAG, "Connected to: $serverURI")
}
override fun connectionLost(cause: Throwable) {
Log.d(TAG, "The Connection was lost.")
}
@Throws(Exception::class)
override fun messageArrived(topic: String, message: MqttMessage) {
Log.d(TAG, "Incoming message from $topic: " + message.toString())
messageCallBack?.invoke(topic, message)
}
override fun deliveryComplete(token: IMqttDeliveryToken) {
}
})
} catch (e: MqttException) {
e.printStackTrace()
}
}
fun publishMessage(topic: String, msg: String) {
try {
val message = MqttMessage()
message.payload = msg.toByteArray()
client.publish(topic, message.payload, 0, true)
Log.d(TAG, "$msg published to $topic")
} catch (e: MqttException) {
Log.d(TAG, "Error Publishing to $topic: " + e.message)
e.printStackTrace()
}
}
fun subscribeTopic(topic: String, qos: Int = 0) {
client.subscribe(topic, qos).actionCallback = object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
Log.d(TAG, "Subscribed to $topic")
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
Log.d(TAG, "Failed to subscribe to $topic")
exception.printStackTrace()
}
}
}
fun close() {
client.apply {
unregisterResources()
close()
}
}
}
@Alepazz
Copy link

Alepazz commented Oct 12, 2019

Hi! I have a question for you, if you can help me. How can I instantiate the class MqttClient with a context? I'm not able to understand what is a context and which is the meaning of that parameter.
Thanks you a lot!

@hussanhijazi
Copy link
Author

@abusous2000
Copy link

thx for this class; it helped me to get started
FYI, I don't believe as is it will compile since MqttClient.generateClientId()

I had to create it which is not a big a deal. I had to return any client id

Many thx again; very helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment