Android Question B4A, JRDC2, MQTT

kisoft

Well-Known Member
Licensed User
Longtime User
HI
https://www.b4x.com/android/forum/threads/rdc-based-on-mqtt.72416/#content

1.Is there an example of how to use this solution for b4a?
2.Is it possible to publish and subscribe topics to the MQTT server using the JRDC2 server?

I started something like that and it works, but the service is separate for each server.

Actv. Main:
B4X:
Type DBResult (Tag As Object, Columns As Map, Rows As List)
    Type DBCommand (Name As String, Parameters() As Object)
    Private const rdcLink As String = "http://xxx.xxx.xxx.xxxx:17178/rdc" 'my server VPS
    Dim a As Int
End Sub

Sub Globals
    
    Private Label1 As Label
    Private Label2 As Label
    Private Label3 As Label
    Private Label4 As Label
    Private Label5 As Label
    Private Label6 As Label
    Private Button1 As Button
    Private mqtt As MqttClient
    
    Private Label7 As Label
    Private mytopic As String
    Private Label8 As Label
    Private Button3 As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
       Activity.LoadLayout("1")   
End Sub

Sub CreateRequest As DBRequestManager
    Dim req As DBRequestManager
    req.Initialize(Me, rdcLink)
    Return req
End Sub

Sub CreateCommand(Name As String, Parameters() As Object) As DBCommand
    Dim cmd As DBCommand
    cmd.Initialize
    cmd.Name = Name
    If Parameters <> Null Then cmd.Parameters = Parameters
    Return cmd
End Sub

Sub GetRecord
    Dim req As DBRequestManager = CreateRequest
    Dim cmd As DBCommand = CreateCommand("czytaj2", Null)
    Wait For (req.ExecuteQuery(cmd, 0, Null)) JobDone(j As HttpJob)
    If j.Success Then
        
        req.HandleJobAsync(j, "req")
        Wait For (req) req_Result(res As DBResult)
          
        If res.Rows.Size > 0 Then
      
            Dim row() As Object = res.Rows.Get(a)
          
            Label4.Text = row(res.Columns.Get("adresemail"))
            Label5.Text = row(res.Columns.Get("prefix"))
            Label6.Text = row(res.Columns.Get("haslo"))
            Log(row(res.Columns.Get("adresemail")))
            Log(a)
        Else
            Log("ERROR: " & j.ErrorMessage)
            
        End If
    End If
    j.Release
End Sub

Sub Activity_Resume
    SetState
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Button1_Click
      a=a+1
    If a>1 Then a=0
    GetRecord
    
End Sub

Public Sub SetState
    
    If Starter.mqtt.Connected Then
        Label8.Text = "Connected to the Server"
        Label7.Text = Starter.tekst
    Else
        Label8.Text = "No Connection to the Server"
        Label7.Text= ""
    End If
    
End Sub

Sub Button2_Click
    CallSub(Starter,"publikacja")
End Sub

Sub Button3_Click
    CallSub(Starter,"publikacja2")
End Sub

mod starter
B4X:
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
 
Top