MQTT on the ESP8266, Part 2

Following my success in getting the ESP8266 to publish to the MQTT broker, I think it’s time to get my topics in order.  After a quick bit of research, I found the following sites:

Using these guidelines, I have decided to setup the following topics for the ESP8266 to use:

  • For publishing data
    • home/location/device/measurement
  • For sensor info
    • clientID/status

We’ll start from here and see what happens.  To add the subscribing functionality to our code, we need to include a callback function, and set it during the initial setup.  The callback function is called every time the ESP recieves a message via MQTT.  I’ve added the following three lines are added at the top of the sketch, following the similar statements with the ssid, password, etc.

const char* topic_head = "home/utility/";
const char* topic_status =  "/status";
const char* topic_in = "/incoming";

The next change is to add


just after the client.setServer() call, and we’ll also add the callback() function as well, which looks like:

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

At this point the callback() function forwards the recieved message and topic to the serial port. The remaining changes are in the reconnect() and loop() functions where the publishing and subscribing is done. In all cases, I use an snprintf() statement to build the correct topic string, which I then pass to the appropriate pulish or subscribe command. And example of this is shown below.

snprintf (topic, 75, "%s%s%s",topic_head, clientID , "/temp");
client.publish(topic, msg);

Using this approach, I was able to successfully publish and subscribe to topics.  When a message was recieved in the subscribed topic, in this case clientID/incoming, it was forwarded to the serial port via the callback function.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s