B4J Question [Solved]MQTT reconnect

Peter Lewis

Active Member
Licensed User
Longtime User
Hi All

I have an app that connects to 2 different Brokers which do multiple SQL transactions. The problem I am having is the server apps and the main app, I have written sometimes loses connection with the brokers.

I was hoping that there is a function that i could put on a timer that could at asay a 30 second interval check if the broker is alive and reconnect.

I found this code done by Erel but I do not understand of how to use it. My understanding of the code is that if it is "Working" but not connected it will close the connection and reconnect again. . Would this be a sub that I call before doing any MQTT calls ?

I did try to use this and I could not get the 'working' parameter to disappear as an error. Is the "Working" a reserved word or does it need a lib

Does anyone have a good way of reconnecting and/or testing if it is connected at a set interval ?


This is Erel's code
B4X:
Sub ConnectAndReconnect
   Do While working
     If mqtt.IsInitialized Then mqtt.Close
     mqtt.Initialize("mqtt", "ssl://io.adafruit.com:8883", "B4X" & Rnd(0, 999999999))
     Dim mo As MqttConnectOptions
     mo.Initialize(username, password)
     Log("Trying to connect")
     mqtt.Connect2(mo)
     Wait For Mqtt_Connected (Success As Boolean)
     If Success Then
       Log("Mqtt connected")
       Do While working And mqtt.Connected
         mqtt.Publish2("ping", Array As Byte(0), 1, False) 'change the ping topic as needed
         Sleep(5000)
       Loop
       Log("Disconnected")
     Else
       Log("Error connecting.")
     End If
     Sleep(5000)
   Loop
End Sub
 
Top