Beginner Tutorial: Your First Mqtt Lua Program On The Esp32

About the project

Learn how to send and receive messages to the HiveMQ MQTT broker on the ESP32 using the Lua Programming language, powered by the Xedge32!

Project info

Items used in this project

Hardware components

ShillehTek Pre-Soldered ESP32C3 ShillehTek Pre-Soldered ESP32C3 x 1

Software apps and online services

Xedge32 Xedge32

Story

Your First MQTT Lua Program with Xedge32

Combining the Lua scripting language with MQTT (Message Queuing Telemetry Transport) and the Xedge32 IoT platform offers an efficient and simplified approach to IoT programming. Lua’s lightweight syntax and flexibility make it an ideal choice for crafting MQTT client code, while Xedge32 enhances the capabilities of the ESP32 microcontroller, enabling seamless integration with sensors and other devices. This tutorial will guide you through setting up your first MQTT Lua program using Xedge32 on the ESP32.

— — -

Before we delve into the topic, we invite you to support our ongoing efforts and explore our various platforms dedicated to enhancing your IoT projects:

  • Subscribe to our YouTube Channel: Stay updated with our latest tutorials and project insights by subscribing to our channel at YouTube — Shilleh.
  • Support Us: Your support is invaluable. Consider buying me a coffee at Buy Me A Coffee to help us continue creating quality content.
  • Hire Expert IoT Services: For personalized assistance with your IoT projects, hire me on UpWork.

ShillehTek Website (Exclusive Discounts):

https://shillehtek.com/collections/all

ShillehTekAmazon Store:

ShillehTek Amazon Store — US

ShillehTek Amazon Store — Canada

ShillehTek Amazon Store — Japan

What is MQTT?

MQTT is a lightweight messaging protocol designed for minimal bandwidth consumption, making it ideal for IoT applications. It operates on a publish-subscribe model, allowing devices to publish messages on topics and subscribe to topics to receive messages. MQTT supports various Quality of Service (QoS) levels, ensuring reliable message delivery. It uses TCP/IP for transport and can employ TLS encryption for secure communication.

Setting Up Xedge32

The ESP32 microcontroller, with its dual-core CPU, integrated WiFi, and extensive GPIOs, stands out in the IoT realm. However, the true magic unfolds with the Xedge32 IoT platform, which allows programming the ESP32 using the Lua programming language. Xedge32 simplifies the development of robust, commercial IoT products, making advanced programming more approachable and affordable.

Xedge32 Installation

To install Xedge32 on your ESP32, follow these steps:

Connect Your ESP32:

  • Connect the ESP32’s USB cable to your computer.
  • Click the ‘Install Xedge32’ button on the Xedge32 website.

Select Your Device:

  • A list of devices will appear. Select the device that includes ‘serial’ in its name.
  • Follow the installation wizard to complete the installation.

Reboot Your ESP32:

  • Once the installation is complete, unplug and replug the USB cable to reboot the ESP32.
  • The ESP32 will now be in access point mode. Follow the ESP32 Access Point Mode documentation for configuration.

For a visual guide on setting up Xedge32, refer to this video tutorial.

Crafting Your First MQTT Lua Program

With Xedge32 installed, let’s create an MQTT client in Lua.

-- Define the onstatus callback function
-- This function handles the status updates of the MQTT connection.
local function onstatus(type, code, status)
print("Status Callback Triggered:", type, code)
if type == "mqtt" and code == "connect" then
-- Check if the connection was successful
if status.reasoncode == 0 then
print("Successful new connection")
print("Server properties:", ba.json.encode(status.properties))
return true -- Accept the connection
else
print("Connection failed with reason code:", status.reasoncode)
return false -- Deny reconnect
end
elseif type == "mqtt" and code == "disconnect" then
-- Handle disconnection
print("Disconnected with reason code:", status and status.reasoncode or "unknown")
elseif type == "sock" then
-- Handle socket errors
print("Socket error occurred")
else
-- Handle unknown errors
print("Unknown error occurred")
end
return false -- Deny reconnect by default
end

-- Define the onpublish callback function
-- This function handles incoming messages from the subscribed topics.
local function onpublish(topic, payload, prop)
print("Received:", topic, payload, ba.json.encode(prop))
end

-- Create the MQTT client instance with TLS and authentication
-- Replace the placeholder values with your actual credentials and broker information.
local mqtt = require("mqttc").create(
"<>", -- Your broker URL
onstatus,
onpublish,
{
secure = true, -- Enable TLS for a secure connection
username = "<>", -- Your username
password = "<>", -- Your password
port = 8883, -- Default port for secure MQTT connections
keepalive = 60, -- Keep-alive interval in seconds
clientidentifier = "my_mqtt_client" -- Unique client ID, can be any string
}
)

print("Subbing")

-- Subscribe to a topic
-- This subscribes to the topic "mytopic". Replace "mytopic" with your desired topic.
mqtt:subscribe("mytopic")

-- Publish a message to the topic
-- This publishes the message "testing" to the topic "mytopic". Replace with your desired topic and message.
mqtt:publish("mytopic", "testing")

-- Give it some time to process messages
-- The sleep time can be adjusted as necessary to allow the client to receive messages.
ba.sleep(5000)

-- Disconnect the MQTT client
-- This gracefully disconnects the client from the broker.
mqtt:disconnect(0)

Script Details

onstatus Callback Function:

  • This function monitors the MQTT connection status.
  • It handles different connection events such as connection success, failure, disconnection, and socket errors.
  • It prints appropriate messages based on the connection status and decides whether to accept or deny reconnections.

onpublish Callback Function:

  • This function handles incoming messages from subscribed topics.
  • It prints the received topic and payload.

Creating the MQTT Client:

  • The mqtt client is created with TLS and authentication for a secure connection.
  • Replace the placeholder values (<>) with your actual broker URL, username, and password.

Subscribing to a Topic:

  • The script subscribes to a topic named “mytopic”.
  • Replace “mytopic” with your desired topic.

Publishing a Message:

  • The script publishes a message “testing” to the topic “mytopic”.
  • Replace “mytopic” and “testing” with your desired topic and message.

Processing Messages:

  • The script pauses for 5 seconds (ba.sleep(5000)) to allow the client to process incoming messages.

Disconnecting the Client:

  • The script gracefully disconnects the MQTT client from the broker using mqtt:disconnect(0).

Conclusion

With this tutorial, you have successfully created your first MQTT client program using Lua and Xedge32. You’ve learned how to set up Xedge32, connect to an MQTT broker, publish messages, subscribe to topics, and ensure secure communication using TLS. This foundational knowledge will enable you to build more complex and secure IoT applications in the future.

Xedge32’s integration with Lua and the ESP32 microcontroller simplifies IoT development, making it accessible to a broad range of users, from novices to seasoned developers. Dive into your next IoT project with confidence, leveraging the power of Xedge32 and MQTT.

Credits

Photo of mahmood-m-shilleh

mahmood-m-shilleh

Mechanical and Software Engineering Background. University at Buffalo 2019 Texas A&M 2021 I make data pipelines for my day job. Outside of work, I participate in online communities regarding Full Stack Engineering, Microelectronics, and more. You can find more details about me on my Youtube Channel. https://www.youtube.com/@mmshilleh Feel free to reach out!

   

Leave your feedback...