Android Question Multiple mqtt clients in the app

Robert Zmrzli

Member
Licensed User
I am trying to maintain 2 separate mqtt clients in my b4a app:

as you can see in snippet below, even though I declare two instances of the mqtt client, events of them connecting or disconnecting are reflected only in:
mqtt_Disconnected and mqtt_Connected.
So how do I find out which of two clients got disconnected inside mqtt_Disconnected sub?


------------------------------------------- code -------------------------------------------

Private Sub mqtt_Disconnected
'we need to find out which one got disconnected
'should I update mqttL_state or mqttG_state (global or local) state here?
End Sub

Sub mqtt_Connected(Sucess As Boolean) As Boolean
'we need to find out which one got connected here
Return Sucess
'End Sub

Sub Process_Globals
Public mqttG As MqttClient
Public mqttL As MqttClient
End Sub

Sub ConnectAndReconnectL

Dim username As String = "userName", password As String = "mypass"

Do While working
If MQTTServerLURL <> "" Then

If mqttL.IsInitialized Then mqttL.Close
mqttL.Initialize("mqtt", MQTTServerLURL, idclient)

Dim mo As MqttConnectOptions
mo.Initialize(username, password)
mqttL_state = "Connecting Local"
Log(mqttL_state)
mqttL.Connect2(mo)
Wait For mqtt_Connected (Success As Boolean)
If Success Then
mqttL_state = "Connected Local"
mytopic = "/gUIde_" & unique_device_id
AfterConnectL 'subscribes to mytopic above
Do While working And mqttL.Connected
mqttL.Publish("/GPS", mytopic.GetBytes("UTF8"))
Sleep(10000)
Loop
mqttL_state = "Unknown"
Else
mqttL_state = "Failed connecting"

End If
End If
Sleep(5000)
Loop
Log("ConnectAndReconnectL Got OUT!")
End Sub

Sub ConnectAndReconnectG

Dim username As String = "userName", password As String = "mypass"

Do While working
If MQTTServerGURL <> "" Then

If mqttG.IsInitialized Then mqttG.Close
mqttG.Initialize("mqtt", MQTTServerGURL, idclient)

Dim mo As MqttConnectOptions
mo.Initialize(username, password)
mqttG_state = "Connecting Global"
Log(mqttG_state)
mqttG.Connect2(mo)
Wait For mqtt_Connected (Success As Boolean) 'I would expect mqttG_Connected to work here but has to be mqtt_ ...
If Success Then
mqttG_state = "Connected Global"
mytopic = "/gUIde_" & unique_device_id
AfterConnectG 'subscribes to mytopic above
Do While working And mqttG.Connected
mqttG.Publish("/GPS", mytopic.GetBytes("UTF8"))
Sleep(10000)
Loop
mqttG_state = "Unknown"
Else
mqttG_state = "Failed connecting"
End If
End If
Sleep(5000)
Loop
Log("ConnectAndReconnectG Got OUT!")
End Sub
 

josejad

Expert
Licensed User
Longtime User
Hi:

Instead -----CODE---- you should use [code ] [/code ] (with no space)

In the line
B4X:
mqttL.Initialize("mqtt", MQTTServerLURL, idclient)
the "mqtt" is the event. If you are declaring both with "mqtt", then the event is the same
You should use
B4X:
mqttL.Initialize("mqttL", MQTTServerLURL, idclient) 
mqttG.Initialize("mqttG", MQTTServerLURL, idclient)
 
Upvote 0
Top