Android uses Kotlin to connect to MQTT

Posted by RossC0 on Tue, 09 Jun 2020 08:30:15 +0200

MQTT It is a lightweight and flexible Internet of things message exchange and data transfer protocol, which is dedicated to achieving the balance between flexibility and hardware / network resources for IoT developers.

Kotlin Kotlin is a programming language developed by JetBrains company. Kotlin is based on JVM, so developers can easily use it to develop Android, and support mixed writing of kotlin and Java. As early as 2017, Google announced kotlin as the official development language.

This article mainly introduces the use of MQTT on Android platform with Kotlin language.

New Kotlin project

Open Android Studio to create a new project, select the language as Kotlin, and Android Studio will automatically create Kotlin related configurations. To configure an existing project, refer to Add Kotlin to existing applications.

Add dependency

Open the build.gradle , add Eclipse Paho Java Client and Eclipse Paho Android Service Depends on the dependencies section.

dependencies {
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.4'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1' 
}

to configure AndroidManifest.xml

Android Service is a background service developed by Eclipse based on Android platform. We need to register it to AndroidManifest.xml At the same time, we need to register permissions.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
   ...
   <service android:name="org.eclipse.paho.android.service.MqttService" />
</application>

Create MQTT client

private lateinit var mqttClient: MqttAndroidClient
// TAG
companion object {
    const val TAG = "AndroidMqttClient"
}

Connect to MQTT server

This article will use EMQ X MQTT Cloud Free public for operation and maintenance MQTT server , EMQ X Cloud is created by EMQ The security MQTT Internet of things cloud service platform is launched, which provides MQTT 5.0 access service of one-stop operation and maintenance agent management and unique isolation environment.

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • Websocket Port: 8083
fun connect(context: Context) {
        val serverURI = "tcp://broker.emqx.io:1883"
        mqttClient = MqttAndroidClient(context, serverURI, "kotlin_client")
        mqttClient.setCallback(object : MqttCallback {
            override fun messageArrived(topic: String?, message: MqttMessage?) {
                Log.d(TAG, "Receive message: ${message.toString()} from topic: $topic")
            }

            override fun connectionLost(cause: Throwable?) {
                Log.d(TAG, "Connection lost ${cause.toString()}")
            }

            override fun deliveryComplete(token: IMqttDeliveryToken?) {

            }
        })
        val options = MqttConnectOptions()
        try {
            mqttClient.connect(options, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "Connection success")
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.d(TAG, "Connection failure")
                }
            })
        } catch (e: MqttException) {
            e.printStackTrace()
        }

    }

Among them, the MqttCallback interface contains three methods:

  1. Message arrived: received new message from broker
  2. connectionLost: lost connection with broker
  3. deliveryComplete: message to broker delivery completed

MqttConnectOptions is used to configure connection settings, including user name and password, timeout configuration, etc. for details, you can view its methods.

Create MQTT subscription

Subscribe to topic

fun subscribe(topic: String, qos: Int = 1) {
        try {
            mqttClient.subscribe(topic, qos, null, 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 $topic")
                }
            })
        } catch (e: MqttException) {
            e.printStackTrace()
        }
    }

Unsubscribe

Unsubscribe from topic

fun unsubscribe(topic: String) {
        try {
            mqttClient.unsubscribe(topic, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "Unsubscribed to $topic")
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.d(TAG, "Failed to unsubscribe $topic")
                }
            })
        } catch (e: MqttException) {
            e.printStackTrace()
        }
    }

Publish message

fun publish(topic: String, msg: String, qos: Int = 1, retained: Boolean = false) {
        try {
            val message = MqttMessage()
            message.payload = msg.toByteArray()
            message.qos = qos
            message.isRetained = retained
            mqttClient.publish(topic, message, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "$msg published to $topic")
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.d(TAG, "Failed to publish $msg to $topic")
                }
            })
        } catch (e: MqttException) {
            e.printStackTrace()
        }
    }

Disconnect MQTT

fun disconnect() {
        try {
            mqttClient.disconnect(null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "Disconnected")
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.d(TAG, "Failed to disconnect")
                }
            })
        } catch (e: MqttException) {
            e.printStackTrace()
        }
    }

test

First connect the Android client to the MQTT server, and then subscribe to topic: A / b. you can see the log of successful connection and subscription

And then we use MQTT 5.0 client tools - MQTT X Test and publish the message to topic: a/b. the client can see the log of the received message

We publish a message to topic: a/b on the client side, because we subscribe to the topic and receive a message at the same time. Finally, we disconnect the client from the MQTT server. The log is as follows:

So far, we have completed the construction of MQTT client on Android, and realized the connection between client and MQTT server, topic subscription, message receiving and sending, etc.

MQTT can provide real-time and reliable message services for connecting remote devices with little code and limited bandwidth. As a kind of instant messaging protocol with low cost and low bandwidth, it has a wide range of applications in the Internet of things, small devices, mobile applications and so on.

Kotlin is also an official language of Google, which combines MQTT protocol and MQTT cloud service , we can develop more interesting applications.

Copyright notice: This is EMQ Original, reprint please indicate the source.

Original link: https://www.emqx.io/cn/blog/a...

Topics: Android Eclipse Java Google