Uno R4 Wifi says MQTT "tested" but no example

Here's some code that works for me to get my Arduino R4 Wifi to listen to an MQTT topic published from my HomeAssistant:

.ino file:

#include <WiFiS3.h>
#include <ArduinoMqttClient.h>

#include "arduino_secrets.h" 
#include "config.h" 
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status
const char mqttDevice[] = CONFIG_DEVICE_NAME;
const char mqttUser[] = SECRET_MQTT_USER;
const char mqttPass[] = SECRET_MQTT_PASS;

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "192.168.86.214";
int        port     = 1883;
const char topic[]  = "homeassistant/test";
const char hostTopic[] = "homeassistant/test";

const long interval = 1000;
unsigned long previousMillis = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWifiData();

  // You can provide a unique client ID, if not set the library uses Arduino-millis()
  // Each client must have a unique client ID
  // mqttClient.setId("clientId");

  // You can provide a username and password for authentication
  // mqttClient.setUsernamePassword("username", "password");

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);
  mqttClient.setId(mqttDevice);
  mqttClient.setUsernamePassword(mqttUser, mqttPass);
  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

  // set the message receive callback
  mqttClient.onMessage(onMqttMessage);

  Serial.print("Subscribing to topic: ");
  Serial.println(topic);
  Serial.println();

  // subscribe to a topic
  mqttClient.subscribe(topic);

  // topics can be unsubscribed using:
  // mqttClient.unsubscribe(topic);

  Serial.print("Waiting for messages on topic: ");
  Serial.println(topic);
  Serial.println();

}

void loop() {

  // call poll() regularly to allow the library to receive MQTT messages and
  // send MQTT keep alives which avoids being disconnected by the broker
  mqttClient.poll();

  // Add a delay to avoid constant pinging
  delay(5000);
}

void printWifiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  
  Serial.println(ip);

  // print your MAC address:
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  printMacAddress(mac);
}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to:
  byte bssid[6];
  WiFi.BSSID(bssid);
  Serial.print("BSSID: ");
  printMacAddress(bssid);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}

void printMacAddress(byte mac[]) {
  for (int i = 5; i >= 0; i--) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i > 0) {
      Serial.print(":");
    }
  }
  Serial.println();
}

void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.print("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.println("'");
  Serial.print("Message length: ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  // Read the message contents into a String
  String message = mqttClient.readString();

  // Convert the received message and comparison strings to lowercase
  message.toLowerCase();

  // Check if the contents of the message match for solve or reset
  if(message == "whatYouWantToSee") {
    onCustom();
    Serial.println("Custom Message For Debugging");
  } else if (message == "whatYouWantToSee2") {
    onCustom2();
    Serial.println("Custom Message For Debugging2");
  } else {
    // If it doesn't match either of the key words, print the message contents for debugging
  Serial.print("Message to My ESP32");
  Serial.println(message);
  }
  Serial.println();

}

void onCustom(){
  //Code you want to run when message 1 gets here
}

void onCustom2(){
  //Code you want to run when message 1 gets here
}

my "arduino_secrets.h" file looks like this:

#define SECRET_SSID ""
#define SECRET_PASS ""
#define SECRET_MQTT_USER ""
#define SECRET_MQTT_PASS ""

and my config.h file looks like this:

#define CONFIG_DEVICE_NAME ""
#define CONFIG_MQTT_BROKER IPAddress()
#define CONFIG_MQTT_SENSOR_CHANNEL_NUDGE "homeassistant/test"
#define CONFIG_SENSOR_READING_INTERVAL 300000

Big thanks to tony2feathers for his source code that this is mostly based off!

Your sketch still has the problem that it only tries once to connect to the broker. If that fails then it goes into the perpetual while() loop

See post #18 for a possibly better way to handle the connection to the broker

Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

This block here should be enough to get it connected, though the while statement referenced in post #18 should work as well, and is probably a more elegant way of doing it. As I understand it, the while (1); at the end of this code block is supposed to cause it to infinite loop until it connects. It's essentially the same thing. Also, make sure you've got

// call poll() regularly to allow the library to receive MQTT messages and
  // send MQTT keep alives which avoids being disconnected by the broker
  mqttClient.poll();

in your main loop function to keep the mqtt connection alive.

What I have started doing now (mind you it's with the esp32 I am using, but still part of the same mqtt broker) is breaking out the wifi setup and the mqtt setup into their own functions, and then just calling those in the beginning of the setup function. I may update this example to include something similar and use the while statement provided by UKHeliBob. That is of course unless one of you just want's to branch/fork it/update it... Good collaboration by all imo.

I am sorry, but that is not correct

while(1);

will always be true and the only code that it executes is the semicolon. As a result the code is stuck in that infinite loop doing nothing if the connection to the broker fails the first time that it tries

That is why I changed the code to put the attempt to connect inside the while loop

Serial.print("Attempting to connect to the MQTT broker: ");
    Serial.println(broker);

    while (!mqttClient.connect(broker, port))
    {
        Serial.print(".");
        delay(100);
    }

    Serial.println("\nYou're connected to the MQTT broker!");
    Serial.println();

Thank you for this - I was struggling all day wondering why I couldn't connect to my local mqtt broker with Error code =-2.
Bit of a trap for a new user!

#ifndef _MQTT_CLIENT_H_
#define _MQTT_CLIENT_H_

#include <Arduino.h>
#include <Client.h>

#define MQTT_CONNECTION_REFUSED            -2
#define MQTT_CONNECTION_TIMEOUT            -1
#define MQTT_SUCCESS                        0
#define MQTT_UNACCEPTABLE_PROTOCOL_VERSION  1
#define MQTT_IDENTIFIER_REJECTED            2
#define MQTT_SERVER_UNAVAILABLE             3
#define MQTT_BAD_USER_NAME_OR_PASSWORD      4
#define MQTT_NOT_AUTHORIZED                 5

you can read the arduino/libraries/AdrduinoMqttClient/src/MqttClient.h header file.
it seems like your connection refused by MQTT broker, you may need to adding mqttClient.setUsernamePassword("broker_user_name", "broker_password") ; in your sketch.

and this is mine:

  mqttClient.setId("UNO_R4_WiFi_YOYO");

  mqttClient.setUsernamePassword("jacky", "mypassword");

  Serial.print("Attempting to connect to MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());
  
    while (1) {
      if (!mqttClient.connect(broker, port)) {
         Serial.print("MQTT connection failed! Error code = ");
         Serial.println(mqttClient.connectError());
      }
      delay(1000);
    }
  }
  delay(1000);
  Serial.print("you're connected to the MQTT broker!");
  Serial.println();