'Code module
#Region Project Attributes
#ApplicationLabel: MQTT Example
#Version: 1.0.0
'Orientation possible values: Portrait, LandscapeLeft, LandscapeRight and PortraitUpsideDown
#iPhoneOrientations: Portrait, LandscapeLeft, LandscapeRight
#iPadOrientations: Portrait, LandscapeLeft, LandscapeRight, PortraitUpsideDown
#ProvisionFile: DescartexGeneral.mobileprovision
#End Region
Sub Process_Globals
'These global variables will be declared once when the application starts.
'Public variables can be accessed from all modules.
Public App As Application
Public NavControl As NavigationController
Private Page1 As Page
Private mqtt As MqttClient
Private mytopic As String
Private serializator As B4XSerializator
Type CircleData (x As Double, y As Double, clr As Int)
Private serverURI As String = "tcp://***.cloudmqtt.com:*****"
Private canvas1 As Canvas
Private lblStatus As Label
Private Panel1 As Panel
End Sub
Private Sub Application_Start (Nav As NavigationController)
NavControl = Nav
Page1.Initialize("Page1")
Page1.RootPanel.LoadLayout("1")
NavControl.ShowPage(Page1)
canvas1.Initialize(Panel1)
mqtt.Initialize("mqtt", serverURI, Rnd(0, 999999999) & DateTime.Now)
Dim mo As MqttConnectOptions
mo.Initialize("myuser", "mypass") 'set user name and password!!!
' mo.SetLastWill("last", "test iohui".GetBytes("utf8"), 1, False)
mqtt.Connect2(mo)
mytopic = "mytopic/" & mqtt.ClientId
End Sub
Private Sub Page1_Resize(Width As Int, Height As Int)
canvas1.Initialize(Panel1)
End Sub
Sub mqtt_Connected (Success As Boolean)
If Success = False Then
Log(LastException)
lblStatus.Text = "Error connecting"
Else
lblStatus.Text = "Connected"
mqtt.Subscribe("mytopic/#", 0)
End If
End Sub
Private Sub mqtt_Disconnected
lblStatus.Text = "Disconnected"
mqtt.Connect
End Sub
Private Sub mqtt_MessageArrived (Topic As String, Payload() As Byte)
Dim obj As Object = serializator.ConvertBytesToObject(Payload)
If obj Is CircleData Then
If Topic = mytopic Then Return 'the circle was already drawn
Dim cd As CircleData = obj
DrawCircleData(cd)
Else 'obj is string
Dim s As String = obj
Select s
Case "clear"
canvas1.DrawColor(Colors.White)
canvas1.Refresh
Case "close"
'no closing in iOS...
End Select
End If
End Sub
Private Sub DrawCircleData(cd As CircleData)
canvas1.DrawCircle(cd.X * (100dip / 100), cd.Y * (100dip / 100), 20dip, cd.clr, True, 0)
canvas1.Refresh
End Sub
Private Sub Page1_Touch(Action As Int, X As Float, Y As Float)
If mqtt.Connected = False Then Return
Dim cd As CircleData
cd.x = x * (100 / 100dip)
cd.y = y * (100 / 100dip)
cd.clr = Rnd(0x80000000, -1)
DrawCircleData(cd)
mqtt.Publish2(mytopic, serializator.ConvertObjectToBytes(cd), mqtt.QOS_2_EXACTLY_ONCE, True)
End Sub
Private Sub Application_Background
End Sub