Android Question newbie with MQTT

morosh

Member
Hello:
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
    #VersionName:
    '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://broker.emqx.io:1883"
    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")
        mqtt.Connect2(mo)
        'mytopic = "drawers/" & mqtt.ClientId
        mytopic = "morosh_test"
    End If
    Activity.LoadLayout("layout1")
End Sub

Sub mqtt_Connected (Success As Boolean)
    If Success = False Then
        Log(LastException)   
        Label1.Text = "Error connecting"
    Else
        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
    b.Beep
    mqtt.Publish("morosh_test","on")
End Sub

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

Hamied Abou Hulaikah

Well-Known Member
Licensed 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

morosh

Member
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
mqtt.Publish("morosh_test","on")
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
Top