Android Question Cant connect MQTT broker to Arduino client

james_sgp

Active Member
Licensed User
Longtime User
Hi, I have an ESP32 running as an MQTT client in Arduino (shown below); it connects to an MQTT broker I downloaded from Play store. But I can`t get it to connect to the B4A app; I suspect its due to the topic not being used in Arduino. The B4A code worked fine between 2 B4A apps, which I used for testing, but now I moved the client to ESP32 it doesn't want to play nice.

Can anyone make any suggestions?

Arduino Code
Code:
#include <WiFi.h>
#include <PubSubClient.h>
#include "Adafruit_SSD1306.h"
#include <SPI.h>
#include <TFT_eSPI.h> // Hardware-specific library
TFT_eSPI tft = TFT_eSPI();       // Invoke custom library
#define TFT_GREY 0x5AEB // New colour

#define PORT_LED 16

const char* SSID = "*********";
const char* PASS = "********";
const char* SERVER = "192.168.1.98";        // Galaxy S8
const int PORT = 51042; //883; //51042 or 1883

Adafruit_SSD1306 display(0x3c, 5, 4);
long lastMsg = 0;
char msg[50];
int value = 0;

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi()
{

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(SSID);

  WiFi.begin(SSID, PASS);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());
  tft.setCursor(0, 0, 2);
  tft.setTextColor(TFT_GREEN,TFT_BLACK);
  tft.setTextFont(4);

  Serial.println("");
  Serial.println("WiFi connected");
  tft.println("WiFi connected");

  Serial.println("IP address: ");
  tft.println("IP address: ");

  Serial.println(WiFi.localIP());
  tft.println(WiFi.localIP());
  tft.println(PORT);


  delay(3000);
}

void callback(char* topic, byte* payload, unsigned int length)

{
    tft.fillScreen(TFT_BLACK);
    tft.setCursor(0, 0, 2);
    tft.setTextFont(4);
    Serial.print("Message arrived [");
    tft.print("Message arrived: ");
    tft.println("");
    Serial.print(topic);
    //tft.setCursor(0, 0, 2);
    Serial.print("] ");

    for (int i=0;i<length;i++)
    {
        //tft.fillScreen(TFT_BLACK);
        Serial.print((char)payload[i]);
        tft.setTextFont(4);
        tft.print((char)payload[i]);
    
    }
    Serial.println();
    tft.println("");

}


void reconnect()
{
  // Loop until we're reconnected
  while (!client.connected())
  {
    tft.fillScreen(TFT_BLACK);
    tft.setCursor(0, 0, 2);
    Serial.print("Attempting MQTT connection...");
    tft.print("Attempting MQTT connection...");
  
    // Create a random client ID
    String clientId = "TTGO";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      tft.println("");
      tft.println("connected");
    
      // Once connected, publish an announcement...
//      client.publish("outTopic", "connect"); //outTopic
      client.publish("all/connect", "connect"); //outTopic
      tft.println("");
      tft.println("Publish: outTopic");
      // ... and resubscribe
      client.subscribe("inTopic");
      tft.println("");
      tft.println("subscribe: inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      tft.println("");
      tft.print("failed, rc=");
      tft.print(client.state());
      Serial.println("try again in 5 seconds");
      tft.println("");
      tft.print("try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup()
{

    tft.init();
    tft.setRotation(3);
    tft.fillScreen(TFT_BLACK);
  
    pinMode(PORT_LED, OUTPUT);
    Serial.begin(115200);
    setup_wifi();
    client.setServer(SERVER, PORT);
    client.setCallback(callback);

  
}

void loop()
{
  if (!client.connected())
  {
    reconnect();
  }

  long now = millis();
  if (now - lastMsg > 2000)
  {
    lastMsg = now;
    ++value;
    snprintf (msg, 50, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    tft.setCursor(0, 0, 4);
    tft.println("Sent:");
    tft.println(msg); 
    client.publish("outTopic", msg); //outTopic
    client.loop();
    tft.setCursor(0, 0, 2);

  }
}

Here is the B4A Code:
B4X:
#Region  Project Attributes
    #ApplicationLabel: Trac-Me Boat, R2
    #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
#BridgeLogger: true
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Type Message (Body As String, From As String)
    Dim boat_tim As Long
    Dim Awake As PhoneWakeState
    Dim diver_msg As String
    Dim working As Boolean = True
    Dim sf As StringFunctions
    Dim my_msg As String
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Private close_btn As Button
    Dim Label1 As Label
    Private btn_server As Button
    Dim Label2 As Label
    Private boat_data As Label
    Private diver_data As Label
    Private data_time As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout1")
    Awake.KeepAlive(True)
    Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
End Sub

Sub Activity_Resume
    StartService(Tracker)
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed Then
        CallSubDelayed(Starter, "Disconnect")
    End If
End Sub

Sub update_gps (location1 As Location)
    boat_tim = location1.time
End Sub

Sub update_screen
    DateTime.DateFormat = "hh:mm:ss"
    data_time.Text = " " & DateTime.Date(DateTime.Now)
End Sub

Sub close_btn_Click
    working = False
    CancelScheduledService("Starter")
    CancelScheduledService("Tracker")
    StopService(Tracker)
    Awake.KeepAlive(False)
    ExitApplication
End Sub

Sub btn_server_Click
    Starter.Name = "AKAMA"
    CallSub2(Starter, "Connect", True)
End Sub

Public Sub NewUsers(Users1 As List)

End Sub

Public Sub NewMessage(msg As Message)
    diver_msg = $"${msg.Body}"$

    Log($"${msg.From}"$)
    Log(diver_msg)

    If $"${msg.From}"$ = "AKAMA" Then
        boat_data.Text = " " & $"${msg.From}: ${msg.Body}"$
    else if $"${msg.From}"$ = "Diver1" Then
        diver_data.Text = " " & $"${msg.From}: ${msg.Body}"$
    End If
  
End Sub

Public Sub Disconnected
    Activity.Finish
End Sub
 

SJQ

Member
Licensed User
Longtime User
For anyone who comes across this post, for ESP32 a better library is the AsyncMQTT_ESP32... I have many ESP32 modules publishing and subscribing to topics that are being published and subscribed from Android apps created in B4A.
 
Upvote 0
Top