B4R Tutorial MQTT

MQTT is an excellent solution for connection of multiple devices.

Tutorial about MQTT: [IoT] MQTT Protocol

The rMQTT library, which is based on PubSubClient open source project, makes it simple to connect to a MQTT broker.

The first step is to connect to the network (not server) as described in this tutorial: https://www.b4x.com/android/forum/threads/ethernet-network-tutorial.65664/

The next step is to initialize MqttClient and call Connect:
B4X:
'ethClient is an unconnected EthernetSocket object.
mqtt.Initialize(ethClient.Stream, serverIp, serverPort, "arduino", "Mqtt_MessageArrived", "Mqtt_Disconnected")

Sub Connect(unused As Byte)
   If mqtt.Connect = False Then
     Log("trying to connect again")
     CallSubPlus("Connect", 1000, 0)
     Return
   End If
   Log("Connected to broker")
   mqtt.Subscribe("arduino", 0)
End Sub

Sub Mqtt_MessageArrived (Topic As String, Payload() As Byte)
   Log("Message arrived. Topic=", Topic, " payload: ", Payload)
End Sub

Sub Mqtt_Disconnected
   Log("Disconnected")
   mqtt.Close
   Connect(0)
End Sub

The above code will reconnect automatically if the connection has broken.

The B4J code with the broker:
B4X:
Sub Process_Globals
   Private broker As MqttBroker
   Private client As MqttClient
End Sub

Sub AppStart (Args() As String)
   broker.Initialize("", 51042)
   broker.DebugLog = False
   broker.Start
   client.Initialize("client", "tcp://127.0.0.1:51042", "pc")
   client.Connect   
   StartMessageLoop
End Sub

Sub Client_Connected (Success As Boolean)
   If Success Then
     client.Subscribe("pc", 0)
   End If
End Sub

Sub Client_MessageArrived (Topic As String, Payload() As Byte)
   If Topic = "pc" Then
     If Payload(0) = 0 Then
       Log("Button is down")
     Else
       Log("Button is up")
     End If
     client.Publish("arduino", "thank you for your message".GetBytes("utf8"))
   End If
End Sub
 

soltypio

Member
Licensed User
Longtime User
is it possible to acces state property of the mqqt client which (as described in PubSubClient docs) contains the error code returned after running connect method?
This would allow to track the nature of connection failures .
 
Top