Private working As Boolean = True
Public mqtt As MqttClient
Private username As String = ""
Private password As String = ""
Public temperature As Float
Private ServerURI As String = "tcp://xxx.xxx.xxx.xxx:1883" 'my server VPS (Mosuqaitto)
Public tekst As String
Private ser As ByteConverter
End Sub
Sub Service_Create
working = True
ConnectAndReconnect
End Sub
Sub ConnectAndReconnect
Do While working
If mqtt.IsInitialized Then mqtt.Close
' mqtt.Initialize("mqtt", ServerURI, "B4X" & Rnd(0, 999999999))
mqtt.Initialize("mqtt", ServerURI, 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")
AfterConnect
Do While working And mqtt.Connected
mqtt.Publish2($"${username}/f/ping"$, Array As Byte(0), 1, False)
Sleep(5000)
Loop
Log("Disconnected")
Else
Log("Error connecting.")
End If
UpdateState
Sleep(5000)
Loop
End Sub
Private Sub AfterConnect
mqtt.Subscribe($"${username}test"$, 0)
UpdateState
End Sub
Sub mqtt_MessageArrived (Topic As String, Payload() As Byte)
If Topic.EndsWith("test") Then
Dim temp As String = BytesToString(Payload, 0, Payload.Length, "ascii")
tekst = temp
UpdateState
End If
End Sub
Sub UpdateState
CallSub(Main, "SetState")
End Sub
Sub Service_Start (StartingIntent As Intent)
End Sub
Sub publikacja
mqtt.Publish("test", ser.StringToBytes("tester", "utf8"))
End Sub
Sub publikacja2
mqtt.Publish("test", ser.StringToBytes("zero", "utf8"))
End Sub
Sub Service_TaskRemoved
'This event will be raised when the user removes the app from the recent apps list.
End Sub
'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub
Sub Service_Destroy
End Sub