2. Create a client and connect to a MQTT broker

Let's extend the code from the previous entry and connect the ESP32 to a broker.

Info

The ESP32 is a simulated device in wokwi, so you won't be able to use your own broker (see 1. Install Mosquitto) unless you have allowed access to your network over the internet (this wasn't explained in thi course). Hence, let's use use a third party broker: the broker test.mosquitto.org.

Public MQTT Broker

Be aware that you're going to use a third party broker which is completely open. This implies that, first, you should not share relevant or sensitive information through that broker and use it only to test your MQTT application.

Client and Topic names

This broker is used by many people simultaneously. Hence, you must choose the clients and topics name with this in mind. I.e., avoid using generic names as a test or example. Also, emember that the client name is unique.

  1. Open a new project in wokwi and load the following diagram.json.

    Show diagram.json
    diagram.json
    {
      "version": 1,
      "author": "Juan M. Gandarias",
      "editor": "wokwi",
      "parts": [
        {
          "type": "board-esp32-devkit-c-v4",
          "id": "esp",
          "top": 0,
          "left": 0,
          "attrs": {}
        }
      ],
      "connections": [
        [
          "esp:TX",
          "$serialMonitor:RX",
          "",
          []
        ],
        [
          "esp:RX",
          "$serialMonitor:TX",
          "",
          []
        ]
      ],
      "dependencies": {}
    }
    

  2. Run the following code

    client_connect.ino
    #include <WiFi.h>
    #include <WiFiClient.h> // (1)!
    #include <PubSubClient.h> // (2)!
    
    #define WIFI_SSID "Wokwi-GUEST"
    #define WIFI_PASSWORD ""
    #define WIFI_CHANNEL 6
    
    const char *MQTT_BROKER_ADRESS = "test.mosquitto.org"; // (3)!
    const uint16_t MQTT_PORT = 1883;
    const char *MQTT_CLIENT_NAME = "ESP32_test"; // (4)!
    
    WiFiClient espClient; // (5)!
    PubSubClient mqttClient(espClient); // (6)!
    
    void ConnectWiFi() // (7)!
    {
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
      Serial.print("Connecting to WiFi ");
      Serial.print(WIFI_SSID);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(100);
        Serial.print(".");
      }
      Serial.println(" Connected!");
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
    }
    
    void InitMqtt() // (8)!
    {
      mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT); 
    }
    
    void ConnectMqtt() // (9)!
    {
      while (!mqttClient.connected())
      {
        Serial.print("Starting MQTT connection...");
        if (mqttClient.connect(MQTT_CLIENT_NAME))
        {
          Serial.println("Client connected!");
        }
        else
        {
          Serial.print("Failed MQTT connection, rc=");
          Serial.print(mqttClient.state());
          Serial.println("try again in 5 seconds");
          delay(5000);
        }
      }
    }
    
    void HandleMqtt() // (10)!
    {
      if (!mqttClient.connected())
      {
        ConnectMqtt();
      }
      mqttClient.loop();
    }
    
    void setup(void)
    {
      Serial.begin(115200);
      ConnectWiFi();
      InitMqtt(); // (11)!
    }
    
    void loop()
    {
      HandleMqtt(); // (12)!
      delay(10);
    }
    
    1. WiFiClient allows the creation of a client that can connect to to a specified internet IP address and port. In this case, you will use it to create a client connected to the test.mosquitto.org broker (server).
    2. PubSubClient allows a client for doing simple publish/subscribe messaging with a server that supports MQTT.
    3. You need to specify the broker address (test.mosquitto.org). If you want to use it with another broker, you need to specify the IP of the broker here (e.g., 192.168.0.12). You need to specify the broker port (by default, 1883 in MQTT). NOTE THE * !!
    4. You need to specify the client name. Don't use a generic name, this name is the one that will be use the broker and other devices of the MQTT network. NOTE THE * !!
    5. Create the client. This name is not the client name in the network, but the name of the object in the script. I.e., you can choose the name freely as it won't be seen by anyone.
    6. Create the MQTT client.
    7. This functions is the same as the one in connect_wifi.
    8. This function initializes the client in the MQTT broker (you need to specify the IP address and port of the broker=server). I know there's only one line of code inside the function, it's been done on purpose. You'll see the reason in subscriber.
    9. This function connects the client to the broker. If the client isn't connected, it will try to connect every 5 seconds. If the client connects, it'l display it through the serial port.
    10. This function handles the connection to the broker. If the connection is lost, it calls the ConnectMqtt() function. If the client is connected, it uses the mqtt.loop() to check for new messages.
    11. The function InitMqtt() is called in the setup().
    12. The funcion HandleMqtt() is called in the loop to keep the client connected and constantly check for new messages.
  3. If you have done it correctly, you should see the following

    Cannot connect to broker

    It is possible that you've found problems when connecting to the broker test.mosquitto.org. Keep in mind that this server is public and is used by thousands of people simultaneously, so sometimes it doesn't work properly. Alternatively, you can use other free public brokers (e.g., the one used in the image above: mqtt.eclipseprojects.io).

CONGRATULATIONS!

Now you're able to connect a MQTT client with an ESP32 and connect it to a broker