2020-10-21 16:57:36 +02:00
|
|
|
import org.eclipse.paho.client.mqttv3.*
|
|
|
|
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
|
2020-10-21 17:53:07 +02:00
|
|
|
import java.time.Instant
|
2020-10-21 16:57:36 +02:00
|
|
|
|
|
|
|
class MqttSubscriber : MqttCallbackExtended {
|
|
|
|
private val broker = "tcp://mqtt.k8s.kmlabz.com:1883"
|
|
|
|
private val clientId = MqttClient.generateClientId()
|
|
|
|
private val persistence = MemoryPersistence()
|
2020-10-21 18:13:27 +02:00
|
|
|
private val mqttClient = MqttAsyncClient(broker, clientId, persistence)
|
2020-10-21 17:53:07 +02:00
|
|
|
private val benchValues = HashMap<Int, Instant>()
|
2020-10-21 16:57:36 +02:00
|
|
|
|
|
|
|
override fun connectionLost(arg0: Throwable) {
|
|
|
|
System.err.println("connection lost")
|
2020-10-21 18:13:27 +02:00
|
|
|
mqttClient.reconnect()
|
2020-10-21 16:57:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
override fun deliveryComplete(arg0: IMqttDeliveryToken) {
|
|
|
|
}
|
|
|
|
|
|
|
|
@Throws(Exception::class)
|
|
|
|
override fun messageArrived(topic: String, message: MqttMessage) {
|
|
|
|
println("topic: $topic")
|
2020-10-21 17:53:07 +02:00
|
|
|
benchValues.put(topic.split("/")[1].toInt(),Instant.now())
|
2020-10-21 16:57:36 +02:00
|
|
|
println("message: " + String(message.payload))
|
|
|
|
}
|
|
|
|
|
|
|
|
override fun connectComplete(reconnect: Boolean, serverURI: String?) {
|
2020-10-21 18:03:11 +02:00
|
|
|
println("Subscribing to all topics")
|
2020-10-21 16:57:36 +02:00
|
|
|
mqttClient.subscribe("#", 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
fun connect() {
|
2020-10-21 18:03:11 +02:00
|
|
|
println("Connecting to broker")
|
2020-10-21 16:57:36 +02:00
|
|
|
val connOpts = MqttConnectOptions()
|
|
|
|
connOpts.isCleanSession = true
|
2020-10-21 17:30:17 +02:00
|
|
|
connOpts.userName = "birbnetes"
|
|
|
|
connOpts.password = "de4d2182".toCharArray()
|
2020-10-21 16:57:36 +02:00
|
|
|
mqttClient.setCallback(MqttSubscriber())
|
|
|
|
mqttClient.connect(connOpts)
|
|
|
|
}
|
2020-10-21 17:53:07 +02:00
|
|
|
|
|
|
|
fun disconnect(): HashMap<Int, Instant> {
|
2020-10-21 18:03:11 +02:00
|
|
|
println("Disconnecting from broker")
|
2020-10-21 17:53:07 +02:00
|
|
|
mqttClient.disconnect()
|
|
|
|
mqttClient.close()
|
|
|
|
return benchValues
|
|
|
|
}
|
2020-10-21 16:57:36 +02:00
|
|
|
}
|