Skip to content

An IoT Tutorial Using HiveMQ MQTT Cluster, ESP32, Lua, and Xedge32

by Wilfred Nilsen
7 min read

In this beginner-friendly tutorial, featuring two comprehensive videos, you will learn how to send and receive messages to the HiveMQ MQTT cluster on the ESP32 microcontroller using the Lua programming language powered by the Xedge32 firmware. We'll also demonstrate how simple it is to securely use MQTT with a TLS connection and showcase tools that enable you to create production-grade MQTT applications.

What is Xedge32?

Xedge32 is a platform designed for the low-cost ESP32 microcontroller, renowned for its versatility in Internet of Things (IoT) projects. The ESP32 offers built-in WiFi and Bluetooth, dual-core processing, and numerous input/output (GPIO) options, making it a robust choice for various IoT applications. Xedge32 uses Lua, a powerful yet beginner-friendly, high-level language ideal for embedded programming.

The Xedge32 Development Environment is an integral platform that includes many IoT protocols. This comprehensive suite is tailored for industrial edge devices, integrating advanced protocols such as MQTT, MQTT Sparkplug, OPC UA, Modbus, HTTPS, and WebSockets.

With Xedge32, programming embedded systems become accessible to everyone, not just embedded C/C++ experts. It simplifies the development of robust, commercial IoT products, making advanced programming more approachable and affordable.

Why Lua?

Lua's compact size, impressive speed, and engineering excellence make it unique. It is also the fastest non-JIT high-level language. Lua was not designed to be a standalone language; it was crafted to be an embeddable extension language from the ground up. This makes Lua an excellent choice for embedding and integrating with software like Xedge32, which extends the standard Lua APIs for IoT, web, and ESP32 GPIO programming. Lua is known for its simplicity and ease of use.

If you're not familiar with Lua yet, you can get a quick start by checking out an online interactive Lua tutorial.

Xedge32: Perfect for Hardware Engineers

For hardware engineers, Xedge32 offers an ideal platform to bridge the gap between hardware and software development. Learning Lua is straightforward, making it accessible for hardware engineers without extensive IoT security, system design, and programming backgrounds. Unlike traditional development requiring complex C coding, IoT security considerations, and device driver design, Xedge32 simplifies the process with an easy-to-use ESP32 GPIO API and many IoT APIs. This allows hardware designers to use the ESP32 as the main controller in new designs or to easily IoT-enable existing designs using the ESP32 as a coprocessor. This flexibility significantly reduces development time and complexity.

Getting Started

In the first video tutorial, you will be guided through installing the ready-to-run Xedge32 firmware. The installation is straightforward and is performed using your browser.

Watch the Xedge32 installation video tutorial

Configuring Your HiveMQ MQTT Cluster and Connecting Xedge32

Once you are familiar with the web-based Xedge32 source code IDE, it's time to set up your HiveMQ Cluster and connect your Xedge32-powered ESP32 to it.

Watch the HiveMQ cluster video tutorial

Ready to Run MQTT Lua Code

The following ready-to-run MQTT Lua program is similar to the one presented in the video. You can copy this Lua code, create an xlua file using the Xedge32 IDE, and paste the content into this file. Before running the code, make sure to set the following three variables: broker, username, and password. You can find these details in your HiveMQ Cloud console. See the MQTT Lua reference manual for more information on the APIs used.

local broker="3e7c81edd7634b198a3689fa4e17f326.s1.eu.hivemq.cloud"
local username="my username"
local password="my password"

local mqtt -- The broker instance, set below

-- Called on connect and disconnect
local function onstatus(type,code,status)
   print("Connection details:",type,code,ba.json.encode(status or {}))
   if "mqtt" == type and "connect" == code and 0 == status.reasoncode then
      print"Connected to broker"
      local sock=mqtt.sock -- The actual socket object used by MQTT
      print("Connection trusted",sock:trusted()) -- prints 'true'
      print("TLS Chiper:",sock:cipher())
      local cert=sock:certificate() -- Fetch broker's certificate
      -- print Lua table using 'serpent'
      print("Certificate:", require"serpent".block(cert,{comment=false}))
      return true -- Accept connection
   end
   print("Disconnect or connect failed",type,code)
   return false -- Deny reconnect
end

local options={
   secure=true, -- Use TLS
   username=username,
   password=password,
}

-- Create MQTT client instance
mqtt=require("mqttc").create(broker,onstatus,options)

-- The onpub callback triggers when we receive a message matching:
-- "sensors/+/temperature"
mqtt:subscribe("sensors/+/temperature",
               {
                  onpub=function(topic,payload)
                     print("Received message:", topic, payload)
                  end
               })

-- Create a "publish" timer
local timer = ba.timer(function()
   for i=10,20 do -- Lua coroutine interval timer
      mqtt:publish("sensors/1/temperature",tostring(i))
      mqtt:publish("sensors/2/temperature",tostring(i+ba.rnd(-10,10)))
      coroutine.yield(true) -- Timer sleep
   end
   print"Done publishing"
end)
timer:set(2000) -- Run timer every two seconds

-- Make sure to close the connection when the server or script stops.
function onunload()
   timer:cancel()
   mqtt:disconnect()
end

Conclusion 

By following this MQTT beginner tutorial, you'll gain the skills needed to leverage MQTT with HiveMQ and Xedge32, creating efficient and secure IoT applications easily and confidently. For additional details on Xedge32 and how to select a suitable ESP32 development board, see the Xedge32 introduction page.

Wilfred Nilsen

Wilfred is a software healer and IoT shaman. He navigates IoT security, protocols, and web wizardry with a mix of ancient coding wisdom and cutting-edge innovation, safeguarding your digital realm and keeping your smart devices secure and harmonious.

  • Wilfred Nilsen on LinkedIn
HiveMQ logo
Review HiveMQ on G2