# Connect to the Deployment with ESP8266

This article mainly introduces how to use PubSubClient in the ESP8266 project, and implement the connection, subscription, messaging, unsubscribing and other functions between the client and MQTT broker.

ESP8266 (opens new window) provides a highly integrated Wi-Fi SoC solution. Its low-power, compact design, and high stability can meet user's requirements. ESP8266 has a complete and self-contained Wi-Fi network function, which can be applied independently or can run as a slave at another host MCU.

MQTT (opens new window) is a kind of lightweight IoT messaging protocol based on the publish/subscribe model. This protocol provides one-to-many message distribution and decoupling of applications. It has several advantages which are low transmission consumption and protocol data exchange, minimized network traffic, three different service quality levels of message which can meet different delivery needs.

# Preconditions

  1. The deployment has been created. You can view connection-related information under Deployment Overview. Please make sure that the deployment status is running. At the same time, you can use WebSocket to test the connection to the MQTT server.
  2. Set the user name and password in Authentication & ACL > Authentication for connection verification.

This article uses the Arduino IDE (opens new window) as the code editor and uploader. The open-source Arduino Software (IDE) makes it easy to write code and upload it to the board. This software can be used with any Arduino board.

# Install dependencies

  1. Install ESP8266 development board Click Tools -> Development Board -> Development Board Management -> Search ESP8266 -> Install
  2. Install PubSub client Project -> Load library -> Library manager... -> Search PubSubClient -> Install PubSubClient by Nick O’Leary

# Connection

Please find the relevant address and port information in the Deployment Overview of the Console. Please note that if it is the basic edition, the port is not 1883 or 8883, please confirm the port.

# Connection settings

This article will use the free public MQTT broker (opens new window) provided by EMQX. This service was created based on the EMQX Cloud (opens new window). The information about broker access is as follows:

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • WebSocket Port: 8083

# Firstly, we import libraries ESP8266WiFi and PubSubClient.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
1
2

# Set Wi-Fi name and password, and connection address and port of MQTT broker

// WiFi
const char *ssid = "mousse"; // Enter your WiFi name
const char *password = "qweqweqwe";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp8266/test";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
1
2
3
4
5
6
7
8
9
10

# Open a serial connection for facilitating to output of the result of the program and connecting to the Wi-Fi network.

// Set software serial baud to 115200;
Serial.begin(115200);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
}
1
2
3
4
5
6
7
8

# Set MQTT broker, write callback function, and print connection information on the serial monitor at the same time.

client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
    String client_id = "esp8266-client-";
    client_id += String(WiFi.macAddress());
    Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
    } else {
        Serial.print("failed with state ");
        Serial.print(client.state());
        delay(2000);
    }
}

void callback(char *topic, byte *payload, unsigned int length) {
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message:");
    for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
    }
    Serial.println();
    Serial.println("-----------------------");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# After successfully connecting to the MQTT broker, ESP8266 will publish messages and subscribe to the MQTT broker.

// publish and subscribe
client.publish(topic, "hello emqx");
client.subscribe(topic);
1
2
3

# Printing the topic name to the serial port and then print every byte of received messages.

void callback(char *topic, byte *payload, unsigned int length) {
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message:");
    for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
    }
    Serial.println();
    Serial.println("-----------------------");
}
1
2
3
4
5
6
7
8
9
10

# The full code

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WiFi
const char *ssid = "mousse"; // Enter your WiFi name
const char *password = "qweqweqwe";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp8266/test";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  // Set software serial baud to 115200;
  Serial.begin(115200);
  // connecting to a WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
  //connecting to a mqtt broker
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
      String client_id = "esp8266-client-";
      client_id += String(WiFi.macAddress());
      Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
      if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
          Serial.println("Public emqx mqtt broker connected");
      } else {
          Serial.print("failed with state ");
          Serial.print(client.state());
          delay(2000);
      }
  }
  // publish and subscribe
  client.publish(topic, "hello emqx");
  client.subscribe(topic);
}

void callback(char *topic, byte *payload, unsigned int length) {
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
      Serial.print((char) payload[i]);
  }
  Serial.println();
  Serial.println("-----------------------");
}

void loop() {
  client.loop();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

# Test

  1. Please use Arduino IDE to upload the complete code to ESP8266 and open the serial monitor esp8266_connection
  2. Establish the connection between MQTT X client and MQTT broker, and send messages to ESP8266 esp8266_mqttx
  3. View the messages ESP8266 received in the serial monitor esp8266_receive

# More

In summary, we have implemented the creation of an MQTT connection in a ESP8266 project, simulated subscribing, sending and receiving messages, unsubscribing, and disconnecting between the client and MQTT broker. You can download the source code of the example here (opens new window), and you can also find more demo examples in other languages on GitHub (opens new window).