From 56cf63bb0a28d7e8e64634790c38ddca3d6449cf Mon Sep 17 00:00:00 2001 From: Torma Date: Wed, 21 Oct 2020 18:34:52 +0200 Subject: [PATCH] something is fucked --- src/main/kotlin/MQTTSubscriber.kt | 37 ++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/main/kotlin/MQTTSubscriber.kt b/src/main/kotlin/MQTTSubscriber.kt index 32d85b6..8cda5d4 100644 --- a/src/main/kotlin/MQTTSubscriber.kt +++ b/src/main/kotlin/MQTTSubscriber.kt @@ -2,16 +2,24 @@ import org.eclipse.paho.client.mqttv3.* import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence import java.time.Instant -class MqttSubscriber : MqttCallbackExtended { +class MqttSubscriber() : MqttCallbackExtended { private val broker = "tcp://mqtt.k8s.kmlabz.com:1883" private val clientId = MqttClient.generateClientId() private val persistence = MemoryPersistence() - private val mqttClient = MqttAsyncClient(broker, clientId, persistence) + private val mqttClient = MqttClient(broker, clientId, persistence) private val benchValues = HashMap() + private val connOpts = MqttConnectOptions() + + init { + connOpts.isCleanSession = true + connOpts.userName = "birbnetes" + connOpts.password = "de4d2182".toCharArray() + connOpts.isAutomaticReconnect = true + mqttClient.setCallback(MqttSubscriber()) + } override fun connectionLost(arg0: Throwable) { System.err.println("connection lost") - mqttClient.reconnect() } override fun deliveryComplete(arg0: IMqttDeliveryToken) { @@ -26,22 +34,29 @@ class MqttSubscriber : MqttCallbackExtended { override fun connectComplete(reconnect: Boolean, serverURI: String?) { println("Subscribing to all topics") - mqttClient.subscribe("#", 0) + try { + mqttClient.subscribe("#", 0) + }catch (e: MqttException) { + e.printStackTrace(); + } } fun connect() { println("Connecting to broker") - val connOpts = MqttConnectOptions() - connOpts.isCleanSession = true - connOpts.userName = "birbnetes" - connOpts.password = "de4d2182".toCharArray() - mqttClient.setCallback(MqttSubscriber()) - mqttClient.connect(connOpts) + try { + mqttClient.connect(connOpts) + }catch (e: MqttException) { + e.printStackTrace(); + } } fun disconnect(): HashMap { println("Disconnecting from broker") - mqttClient.disconnect() + try { + mqttClient.disconnect() + }catch (e: MqttException) { + e.printStackTrace(); + } mqttClient.close() return benchValues }