Machinechat JEDI One MQTT Broker Subscribe Example using Arduino / ESP8266

Introduction

machinechat’s JEDI One includes a built-in MQTT broker. External client devices can publish or post to a topic on the JEDI One. In this post an Arduino client device will be set up to subscribe to an existing topic (sensor data) on the JEDI One over WiFi.

Background

MQTT (Message Queuing Telemetry Transport) is an open OASIS and ISO standard which defines a lightweight, publish-subscribe network protocol that transports messages between devices. It includes two types of network entities: a message broker and a number of clients.
macinechat’s JEDI One IoT platform includes a data collector that can be configured as an MQTT message broker. External client devices can be configured to publish data or subscribe to a topic on the JEDI One (topics include all data coming into JEDI One from any source, not just MQTT). JEDI One requires publish messages to be in JSON payload format and provides subscribe messages in JSON payload format. JEDI One topics to subscribe to will be in the format of “datacache/Device ID” (example: “datacache/T960981B2D”).

Implementation

This project uses a Raspberry Pi 4 with JEDI One installed and MQTT data collector enabled. An ESP8266 board running Arduino is used for the MQTT client to subscribe to a sensor data topic on the JEDI One IoT platform running on the Pi.

JEDI One configuration

If you haven’t already set up an MQTT Broker Data Collector on your JEDI One follow below steps.
In the JEDI One “Data Collector” tab, select “Add Collector” and configure. Name the “Data Collector” and select “MQTT Broker” for “Collector Type”. “Listen IP” in the MQTT colector setup screenshot is the JEDI One Raspberry Pi IP address and “Listen Port” is 1883. (note: below shows example unencrypted configuration but TLS encryption can be configured as shown in machinechat Product Guide - How to Generate TLS Certificates and Keys )

For this example an existing JEDI One platform running on a Raspberry Pi collecting sensor data is used to provide an MQTT topic for the Arduino to subscribe to. A related post Machinechat with ESP8266 and Amphenol T9602 sensor details the project providing the sensor data shown below.

Arduino / ESP8266 example code

In this example an ESP8266 is programmed to join a Wifi network, subscribe to a sensor data topic on the JEDI One, decode the JSON encoded subscribe message, and print out the decoded timestamp and sensor data on the serial monitor. The PubSubClient and ArduinoJson libraries are used in the example code and need to be installed.

Wifi and general configuration code…

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "arduino_secrets.h" 

// Update these with values suitable for your network.
char ssid[] = SECRET_SSID;     // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
const char* mqttServer = "192.168.1.11";
const int mqttPort = 1883;

StaticJsonDocument<256> doc;

int data1;  //data1 of MQTT json message
int data2;  //data2 of MQTT json message
int data3;  //data3 of MQTT json message
int msg = 0;
const char* timestamp = "dummy data";  //the is the MQTT message timestamp
//const char* current_ts = "blank";
String recv_payload;

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.mode(WIFI_STA);
  WiFi.begin(ssid, pass);

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

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

MQTT connection and subscribe code…

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a unique client ID using the ESP8266 MAC address
    String MACadd = WiFi.macAddress();
    MACadd = "ESP8266cli" + MACadd;  //add "ESP8266cli" to MAC address
    //Serial.println(MACadd);        // debug print
    String clientID = MACadd;

    // Attempt to connect
    if (client.connect(clientID.c_str())) {
      Serial.println("connected");
      // set up MQTT topic subscription
      client.subscribe("datacache/T960981B2D");  // topic needs to be "datacache/" + Device on JEDI One 
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

MQTT callback message and JSON decode code…

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Subscribe topic: ");
  Serial.println(topic);
  Serial.print("Subscribe JSON payload: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);     // print mqtt payload
  }
  Serial.println();

  msg = 1;  //message flag = 1 when new subscribe message received

  deserializeJson(doc, (const byte*)payload, length);   //parse MQTT message
  data1 = doc["data1"];    // data1 is humidity
  data2 = doc["data2"];    // data2 is temp
  data3 = doc["data3"];    // data3 is empty
  timestamp = doc["timestamp"];    //mqtt message timestamp
  //Serial.println(timestamp);     //debug print
  
  recv_payload = String(( char *) payload);  // put payload in string for future use
  //Serial.println("print recv_payload string");   //debug info
  //Serial.println(recv_payload);                  //debug info
}

example Arduino serial monitor output data…

Software:

Hardware:

Raspberry Pi (note: a Pi 4 is used in this project but any Raspberry Pi could be used)

ESP8266 board

Arduino setup

In Arduino, use this link in the " Additional Boards Managers URLs " field: to add ESP8266 support.

http://arduino.esp8266.com/stable/package_esp8266com_index.json

Add these libraries thru Arduino’s Library Manager:

Arduino sketch and source code located in below Github link.

References

Arduino - How to use ArduinoJson with PubSubClient?
machinechat Product Guide - Built In MQTT Broker - Data Collector
machinechat Product Guide - MQTT Broker - Subscribing to a topic
HIVEMQ - MQTT Essentials

Contact

Comments, feedback, and questions can be sent to eewiki@digikey.com.