Unable to connect with CircuitPython - MiniMQTT Library

I am totally desperate, as I cannot connect in CircuitPython with the MiniMQTT Library to HiveMQ.

My code looks like this

import ssl
import wifi
import socketpool
import adafruit_minimqtt.adafruit_minimqtt as MQTT

# WLAN-Configuration
WLAN_SSID = "mySSID"  # 
WLAN_PASSWORD = "mypassword"  # 

# WLAN Connection
print("Connect with %s"%WLAN_SSID)
wifi.radio.connect(WLAN_SSID, WLAN_PASSWORD)
print("Connected with %s!"%WLAN_SSID)
print("My IP-Adress is", wifi.radio.ipv4_address)

# MQTT-Broker-Data
MQTT_HOST = "URL"
MQTT_PORT = 8883  
MQTT_USER = "username"
MQTT_PASSWORD = "password"

# Create SSL-Context
socket_pool = socketpool.SocketPool(wifi.radio)
ssl_context = ssl.create_default_context()

# Create MQTT-Client
mqtt_client = MQTT.MQTT(broker=MQTT_HOST, port=MQTT_PORT, username=MQTT_USER, password=MQTT_PASSWORD, socket_pool=socket_pool, ssl_context=ssl_context)

# Connect to MQTT
try:
    mqtt_client.connect()
    print("Connected to HiveMQ Cloud!")
except Exception as e:
    print("Connection Error:", e)

It returns: “Connection Error: (‘Repeated connect failures’, None)”

My device (XIAO ESP32C3) properly connects to Wifi. On another client (notebook) within the same Wifi network, I tried to connect to HiveMQ with the Paho library with Python and it all works properly (so most likely no typo in URL, username, password, no port issue).

AI did not provide any solutions - any ideas what could be wrong? Support is very much appreciated!

I guess I have the solution. Somewhere deeply hidden in Github was the hint:

context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.verify_mode = ssl.CERT_NONE

client = MQTTClient(
MQTT_CLIENT_ID,
MQTT_BROKER,
MQTT_PORT,
MQTT_USER,
MQTT_PASSWORD,
keepalive=7200,
ssl=context
)

Would be great if some up-to-date code examples could be provided by HiveMQ…

Do you mind giving me a code example? I have the same issue as you. Please make the solution clear.

I have made the code working, although very unstable, which may be an issue with the ESP32C3 Wifi capability:

from umqtt.simple import MQTTClient
import time
import network
import ssl

Wi-Fi credentials

WIFI_SSID = “xxx”
WIFI_PASSWORD = “xxx”

HiveMQ Cloud Configuration

MQTT_BROKER = “xxx.s1.eu.hivemq.cloud”
MQTT_PORT = 8883
MQTT_USER = “xxx”
MQTT_PASSWORD = “xxx”
MQTT_CLIENT_ID = “ESP_32”

Topics for Publishing and Subscription

MQTT_TOPIC_PUBLISH = “your/publish/topic”
MQTT_TOPIC_SUBSCRIBE = “your/subscribe/topic”

wlan = network.WLAN(network.STA_IF)

wlan.disconnect()

wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)

print(“Connecting to WiFi…”, end=“”)
while not wlan.isconnected():
print(“.”, end=“”)
time.sleep(1)
print(“\nWiFi connected! IP:”, wlan.ifconfig()[0])

MQTT-Client

context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # Works, but is considered as unsecure
context.verify_mode = ssl.CERT_NONE # Security Risk!

client = MQTTClient(
MQTT_CLIENT_ID,
MQTT_BROKER,
MQTT_PORT,
MQTT_USER,
MQTT_PASSWORD,
keepalive=7200,
ssl=context
)

Callback-Function for received messages

def sub_cb(topic, msg):
print(f"Nachricht empfangen: {msg.decode()}")

Connect with MQTT Broker

try:
client.connect()
print(“Connected with HiveMQ Cloud!”)
except Exception as e:
print(f"Connection Error: {e}")
exit()

Subscribe

#client.subscribe(MQTT_TOPIC_SUBSCRIBE)
#client.set_callback(sub_cb)

Publish messages

try:
for i in range(10):
message = f"Hello from MicroPython! {i}"
client.publish(MQTT_TOPIC_PUBLISH, message)
print(f"Message Sent: {message}“)
time.sleep(2) # Wait 2 seconds
except Exception as e:
print(f"Publishing Error: {e}”)

Receive Messages

while True:
client.check_msg()
time.sleep(1)

Hi there! @KaenguruKoala

It’s fantastic to hear that you’re interested in MQTT and the HiveMQ broker. Welcome to the HiveMQ Community! We’re thrilled to have you join us.

I noticed your question about connecting ESP32C3 to HiveMQ Cloud with MicroPython. Great job getting it working! I understand you’re experiencing stability issues with your connection.

For the unstable connection, here are some suggestions:

  1. Reduce the keepalive time - 7200 seconds is quite long and might be contributing to the instability. Try a value between 60-300 seconds.

  2. Add reconnection logic - Implement automatic reconnection if the connection drops:

def reconnect():
    print('Reconnecting...')
    time.sleep(5)
    # Either reset the device or re-establish connection
    client.connect()

# In your main loop
try:
    # Your code here
except Exception as e:
    print(f"Connection lost: {e}")
    reconnect()
  1. Power stability - Ensure your ESP32C3 has stable power as fluctuations can affect WiFi performance.

  2. WiFi signal strength - Position your device closer to your router if possible.

  3. Secure connection - I noticed you’re using CERT_NONE which, as you mentioned, is a security risk. For production use, consider loading the proper CA certificates:

import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# Load the CA certificate that signed the HiveMQ Cloud certificate
context.load_verify_locations('path/to/ca_cert.pem')

The ESP32C3 does have some known WiFi limitations compared to other ESP32 variants. If stability remains an issue after these adjustments, you might want to consider an ESP32-S3 or ESP32-WROOM which generally have better WiFi performance.

Hope this helps! Let me know if you have any further questions.

Best,
Dasha from The HiveMQ Team