Android Tutorial [B4X] MQTT - Connect & Reconnect

Erel

Administrator
Staff member
Licensed User
The ConnectAndReconnect sub takes care of connecting to the broker and reconnecting if the connection has broken.
It sends a "ping" request every 5 seconds to help the MQTT client recognize network failures.

It is a nice example of how Wait For and Sleep can help to manage the network state which is completely asynchronous.
The ConnectAndReconnect sub will keep running until you set the working variable to False.

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
In B4A it is recommended to put it in the starter service:
B4X:
Sub Process_Globals
   Private working As Boolean = True
   Private mqtt As MqttClient
End Sub

Sub Service_Create
   working = True
   ConnectAndReconnect
End Sub
Set working to False before you close the connection when you want to close it.

This code is compatible with B4A, B4i and B4J.
 
Last edited:

janderkan

Active Member
Licensed User
Info

If you set a LastWill then you should not use RND() in the initialize command.

If phone disconnects and reconnects, then the LastWill will be sent after 1 minute, even if the phone is connected again.

Use something unique like MAC address and the LastWill will only be sent if the phone is disconnected.
 

avalle

Active Member
Licensed User
I'm not clear if using this means that the code in existing sub

B4X:
Private Sub Mqtt_Connected (Success As Boolean)
in the Starter service should now be moved to Sub ConnectAndReconnect after

B4X:
Wait For Mqtt_Connected (Success As Boolean)
Specifically I'm trying to make this work with the MQTT Chat and I'm not sure I'm doing it right.

Thanks
Andrea
 

Johan Hormaza

Well-Known Member
Licensed User
B4X:
    Wait For mqtt_Connected (Success As Boolean)
    If Success Then
        Log("Connect")
    Else
        Log("Fail connection")
    End If
so is
 
Top