Send a message through HiveMQ with MicroPython on ESP32S3

Ats
3 min readJun 29, 2024

--

This is my note about what I did to send messages through HiveMQ with MicroPython on ESP32S3.

Photo by Erik Karits on Unsplash

First of all

I used an ESP32S3 and the firmware provided by Seeed Studio. The setup of an MQTT client could be different based on your firmware.

Background

I’ve used HiveMQ broker for my MQTT messages in my job and private projects.

However, I’ve never tried it with an ESP32 board before. Currently, I’m working on it for my private project. Then I tried to use MQTT messages with it for fun.

What I did

I found the article and used it as my reference.

From the article, I needed to install umqtt.sample2 to initialize MQTT client.

I tried it with mip and it raised ImportError: no module named ‘mip’ . I felt weird and tried with upip just in case. However, it also raised ImportError: no module named ‘upip’ . I haven’t investigated it properly yet but I guess the firmware provided by Seeed Studio doesn’t contain mip or upip and that’s why I couldn’t use them. So I installed the package manually as the README says.

git clone https://github.com/fizista/micropython-umqtt.simple2.git

Then I created the MQTT client class like below. I put many print logs in my code because the error message by umqtt.sample2is a bit unclear to me so I needed to clarify where problems came from.


import ubinascii
import machine
from umqtt.simple2 import MQTTClient
from config import *

CLIENT_ID = ubinascii.hexlify(machine.unique_id())
MQTT_BROKER_SERVER = mqtt_config['server']
MQTT_BROKER_PORT = mqtt_config['port']
MQTT_BROKER_USERNAME = mqtt_config['username']
MQTT_BROKER_PASSWORD = mqtt_config['password']

class Mqtt:
def __init__(self,
server: str = MQTT_BROKER_SERVER,
port: int = MQTT_BROKER_PORT,
username: str = MQTT_BROKER_USERNAME,
password: str = MQTT_BROKER_PASSWORD,
device_uuid: str = CLIENT_ID,
) -> None:

# Connection
self._server = server
self._port = port
self._username = username
self._password = password

# Client
self._client = None
self._client_id: str = device_uuid

def _connect(self):
try:
if self._client is None:
self._client = MQTTClient(
self._client_id,
self._server,
port=self._port,
user=self._username,
password=self._password,
)
self._client.connect()
else:
print(f"Reboot because of error of setting up MQTT client")
machine.reset()
return True, {}
except Exception as err:
print(f"Error connecting device to message broker: {err}")
return False, {'msg': err}

def _disconnect(self) -> None:
if self._client is not None:
self._client.disconnect()

def start(self) -> None:
succ, resp = self._connect()
if succ and self._client is not None:
print("Started App MQTT Client")
else:
print(f"Can't start MQTT client - {resp['msg']}")

def stop(self) -> None:
if self._client is not None:
self._client.disconnect()
print("Stopped App MQTT Client")

def publish(self, topic: str, message: str) -> None:
if self._client is not None:
print(f"Will publish message - {self._client_id}, {topic}, {message[:20]}")
self._client.publish(topic, message)
print(f"Published message - {self._client_id}, {topic}, {message[:20]}")

I tried to publish a message to my HiveMQ broker but it failed. Based on the log messages, my code failed at the point where the client would connect to the broker. Then I realized I hadn’t activated the SSL/TSL connection. I googled how to do that with MicroPython and found the discussion.

Specifically, for the HiveMQ, I needed to set the server_hostname in ssl_params

So I changed my _connect function like below.

     def _connect(self):
try:
if self._client is None:
ssl_params = { 'server_hostname': self._server }
self._client = MQTTClient(
self._client_id,
self._server,
port=self._port,
user=self._username,
password=self._password,
keepalive=3600,
ssl=True,
ssl_params=ssl_params
)
self._client.connect()
else:
print(f"Reboot because of error of setting up MQTT client")
machine.reset()
return True, {}
except Exception as err:
print(f"Error connecting device to message broker: {err}")
return False, {'msg': err}

Then I came to send messages through MQTT and saw the messages on the HiveMQ console.

That’s it!

--

--

Ats
Ats

Written by Ats

I like building something tangible like touch, gesture, and voice. Ruby on Rails / React Native / Yocto / Raspberry Pi / Interaction Design / CIID IDP alumni

No responses yet