Android Question newbie with MQTT


I'm trying to control a relay connected to a ESP8266 from my phone, I've put the code in the ESP and I need to publish just "on" and "off" to control the relay, I've searched for a while to find a similar example here without success.
Any help is appreciated

MQTT publish:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    Private mqtt As MqttClient
    Private mytopic As String
    Private serializator As B4XSerializator
    Private serverURI As String = "tcp://"
    Private bc As ByteConverter
End Sub

Sub Globals
    Dim b As Beeper
    Private But1 As Button
    Private But2 As Button
    Private But3 As Button
    Private But4 As Button
    Private Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        mqtt.Initialize("mqtt", serverURI, Rnd(0, 999999999) & DateTime.Now)
        Dim mo As MqttConnectOptions
        mo.Initialize("yyyyyy", "xxxx")
        'mytopic = "drawers/" & mqtt.ClientId
        mytopic = "morosh_test"
    End If
End Sub

Sub mqtt_Connected (Success As Boolean)
    If Success = False Then
        Label1.Text = "Error connecting"
        Label1.Text = "Connected"
        mqtt.Subscribe("morosh_test", 0)
    End If
End Sub

Private Sub mqtt_Disconnected
    Label1.Text = "Disconnected"
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub But1_Click
End Sub

Sub But2_Click
    mqtt.Publish("morosh_test", "off")
End Sub

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
1- Where is B4R code that you publish it to ESP?
2- In your B4A code when you run it on phone, what did you get for mqtt connection: "connected", "error connecting" or nothing?
Upvote 0


Thanks for reply
I've error in compilation:
Compiling code. Error
Error compiling program.
Error description: Cannot cast type: {Type=String,Rank=0, RemoteObject=True} to: {Type=Byte,Rank=1, RemoteObject=True}
Error occurred on line: 68
Word: on
there is error at: mqtt.Publish("morosh_test","on")
Otherwise, commenting this line (and the second one), I get "connected" in Label1
Upvote 0