5- Publish ESP32 data with timestamp over MQTT

The ESP32 board has access to the NTP server (Network Time Protocol) through Internet which can be used to get timestamps (UNIX timestamp) with a precision within a few milliseconds. This guide explains how to run the AskSensors API on ESP32 to publish data with timestamp to the cloud over MQTT.

Following the below steps you’ll be able to send data with NTP timestamp to AskSensors through MQTT.

AskSensors : ESP32

a) Prerequisites :

  • Create an AskSensors account
  • Setup a new sensor. For additional details on how to create a sensor, simply click here and follow the simple process.
  • Follow these steps to get familiar with AskSensors.

b) Required Hardwares :

  • Computer running Arduino software (version 1.8.7 or higher).
  • ESP32 board.
  • USB micro cable to connect the ESP32 board to the computer.

c) Install ESP32 in Arduino IDE:

Follow the instructions below to install the ESP32 board in your Arduino IDE:

– Install the latest version of Arduino IDE software (1.8.7 or higher).

– Open the preferences window from the Arduino IDE : File> Preferences.

– Go to the “Additional Board Manager URLs” field, Enter the following URL:
https://dl.espressif.com/dl/package_esp32_index.json

If you already have the ESP8266 boards URL, separate the URLs with a comma as show below:

https://dl.espressif.com/dl/package_esp32_index.json, http://arduino.esp8266.com/stable/package_esp8266com_index.json

Now, open boards manager (Tools > Board > Boards Manager), search for ESP32 and click the install button for the “ESP32 by Espressif Systems”.

d) Software :

  • Install the MQTT PubSubClient Library for the Arduino IDE.
  • Install the NTP Client library for the Arduino IDE: Navigate to the Sketch > Include Library > Manage Libraries.
    Wait for Library Manager to download libraries index and updated list of installed libraries.
    Filter your search by typing ‘ntpclient’. There should be a couple entries. Look for NTPClient by Fabrice Weinberg. Click on that entry, and then select Install.
  • Download this demo from the AskSensors Github page.

The provided code includes the libraries for both connecting to a WiFi network and to publish data with NTP timestamp to AskSensors using MQTT.
You need to to modify the following variables:

    • Your WIFI SSID and password.
    • The Api Key In and username to set the MQTT Topic:publish/username/apiKeyIn

const char* ssid = "....."; // Wifi SSID
const char* password = ".....";// Wifi Password
const char* username = "................."; // my AskSensors username
const char* pubTopic = "publish/..../....."; // publish/username/apiKeyIn
const char* mqtt_server = "mqtt.asksensors.com";

e) Flash the code to your ESP32

  • Connect your ESP32 board to the computer via serial/USB and upload the code using the Arduino IDE.
  • Check your Sensor data stream on your AskSensors workspace.
  • Open a serial terminal. You can cross-check the AskSensors graph readings with the values being printed on your ESP32 Terminal.

f) Source Code :

A basic source code is shown below. Please refer to the AskSensors Github page to get the latest version and updates.


/*
* MQTT and AskSensors IoT Platform
* Description: ESP32 publishes NTP timestamps data to AskSensors using MQTT
* Author: https://asksensors.com, 2020
* github: https://github.com/asksensors
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
// TODO: ESP32 MQTT user config
const char* ssid = ".................."; // Wifi SSID
const char* password = ".................."; // Wifi Password
const char* username = "................."; // my AskSensors username
const char* pubTopic = "publish/..../....."; // publish/username/apiKeyIn
const unsigned int writeInterval = 25000; // write interval (in ms)
// Asksensors MQTT host config
const char* mqtt_server = "mqtt.asksensors.com";
unsigned int mqtt_port = 1883;
WiFiClient askClient; // WiFi client
PubSubClient client(askClient); // MQTT client
WiFiUDP ntpUDP; // UDP client
NTPClient timeClient(ntpUDP); // NTP client
void setup() {
Serial.begin(115200);
Serial.println("*****************************************************");
Serial.println("********** Program Start : ESP32 publishes NTP timestamps data to AskSensors over MQTT");
Serial.print("********** connecting to WIFI : ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("->WiFi connected");
Serial.println("->IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
timeClient.begin(); // init NTP
timeClient.setTimeOffset(0); // 0= GMT, 3600 = GMT+1
}
void loop() {
if (!client.connected())
reconnect();
client.loop();
Serial.println("********** Publish MQTT data to ASKSENSORS");
// timestamp
while(!timeClient.update()) {
timeClient.forceUpdate();
}
// get Epoch time
Serial.print("> NTP Time:");
Serial.println(timeClient.getFormattedTime());
long unsigned int timestamp = timeClient.getEpochTime();
char mqtt_payload[100] = "";
snprintf (mqtt_payload, 100, "module1=%ld&module2=%ld&t=%ld", random(10,100), random(10,100),timestamp);
Serial.print("Publish message: ");
Serial.println(mqtt_payload);
client.publish(pubTopic, mqtt_payload);
Serial.println("> MQTT data published");
Serial.println("********** End ");
Serial.println("*****************************************************");
delay(writeInterval);// delay
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("********** Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client",username, "")) {
Serial.println("-> MQTT client connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println("-> try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

Was this article helpful to you? Yes No

How can we help?