Anroid, MQTT

이도현·2023년 8월 11일
0

Android 공부

목록 보기
11/30

1. implementation

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

2. mqtt establish

import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.*

// MQTT broker URL and client ID
val brokerUrl = "tcp://your-mqtt-broker-url"
val clientId = MqttClient.generateClientId()

// Create an MQTT client
val mqttClient = MqttAndroidClient(applicationContext, brokerUrl, clientId)

// Set MQTT options (optional)
val mqttOptions = MqttConnectOptions()
mqttOptions.isCleanSession = true

// Connect to the MQTT broker
mqttClient.connect(mqttOptions, null, object : IMqttActionListener {
    override fun onSuccess(asyncActionToken: IMqttToken?) {
        // Connection successful
        // You can subscribe to topics here if needed
    }

    override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
        // Connection failed
    }
})

3. publish

// Location data
val latitude = 37.1234
val longitude = -122.5678

// MQTT topic to publish to
val topic = "location/topic"

// Create a JSON payload with location data
val payload = "{\"latitude\": $latitude, \"longitude\": $longitude}"

// Create an MQTT message
val message = MqttMessage(payload.toByteArray())

// Set the quality of service (QoS)
message.qos = 1

// Publish the message to the topic
mqttClient.publish(topic, message)

4. disconnect

mqttClient.disconnect()
profile
좋은 지식 나누어요

0개의 댓글