MicroPython ESP32 IndexError: bytes index out of range

Hello, I want to read the data from 2 distance sensors on esp32 c2102 and send it instantly to my own cluster in HiveMQ cloud which I have opened for free. However, whatever I do, I have trouble sending the data to the broker.

Traceback (most recent call last):
File “”, line 44, in
File “mqtt.py”, line 19, in connect
File “umqttsimple.py”, line 110, in connect
IndexError: bytes index out of range

I couldn’t get past the error. I will be sharing the codes below. When I make the ports 1883 I get the following code

Traceback (most recent call last):
File “”, line 44, in
File “mqtt.py”, line 19, in connect
File “umqttsimple.py”, line 68, in connect
OSError: [Errno 113] ECONNABORTED

I am using ESP32 with OTA support edition and I used version 1.19.1.

I would like to ask for your help on how those who have encountered this situation before have solved it.

mqtt.py

import time
from umqtt.robust import MQTTClient
#simple, simple2, robust2 all experimented same result
class MQTTSubscriber:
    def __init__(self, server, port, client_id, username, password, topic, ssl, ssl_params):
        self.server = server
        self.port = port
        self.client_id = client_id
        self.username = username
        self.password = password
        self.topic = topic
        self.ssl = ssl
        self.ssl_params = ssl_params
        self.client = MQTTClient(self.client_id, self.server, port=self.port, user=self.username, password=self.password, ssl=self.ssl, ssl_params=self.ssl_params)
        self.client.set_callback(self.callback)

    def callback(self, topic, msg):
        print("Received message on topic: {}, Message: {}".format(topic, msg))

    def connect(self):
        self.client.connect()
        self.client.subscribe(self.topic)

    def publish_message(self, message):
        self.client.publish(self.topic, message)
        print("Published message: {}".format(message))

    def run(self, interval):
        while True:
            self.publish_message("Hello, world!")
            time.sleep(interval)

    def disconnect(self):
        self.client.disconnect()

wifi.py

import network

class WiFiManager:
    def __init__(self, ssid, password):
        self.ssid = ssid
        self.password = password
        self.wlan = network.WLAN(network.STA_IF)

    def connect(self):
        self.wlan.active(True)
        if not self.wlan.isconnected():
            print("Connecting to Wi-Fi...")
            self.wlan.connect(self.ssid, self.password)
            while not self.wlan.isconnected():
                pass
        print("Wi-Fi connected!")
        print("IP address:", self.wlan.ifconfig()[0])

    def disconnect(self):
        self.wlan.disconnect()

main.py

from mqtt import MQTTSubscriber
from time import sleep
from wifi import WiFiManager
import ubinascii
import machine

import gc
gc.collect()

# ESP32
sensor1 = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)
sensor2 = HCSR04(trigger_pin=4, echo_pin=16, echo_timeout_us=10000)
# ESP8266
#sensor = HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=10000)

# Wi-Fi credentials
wifi_ssid = "MYSSID"
wifi_password = "MYPASSWORD"

# Instantiate the WiFiManager and MQTTSubscriber classes
wifi_manager = WiFiManager(wifi_ssid, wifi_password)

# Connect to Wi-Fi, MQTT, run, and disconnect
wifi_manager.connect()




# Instantiate the MQTTSubscriber class
subscriber = MQTTSubscriber(
    server= b"MYBROKER.s2.eu.hivemq.cloud",
    port=8883,
    client_id= ubinascii.hexlify(machine.unique_id()),
   #created credentials in access management
    username="MQTTUSER",
    password="MQTTPASS",
    topic= b"Floor00/Desk01",
    ssl= False,
    ssl_params={}
)

interval=3

# Connect, run, and disconnect
subscriber.connect()

Hello @rsemihkoca ,

Thank you for the outreach, and welcome to the HiveMQ Community!

Off the top, the first thing that comes to mind here is that the HiveMQ Cloud Broker requires TLS in order for a client to complete connection via port 8883 (port 1883 is not exposed for HiveMQ Cloud Brokers, resulting in connection error you’ve provided).

Based on the details provided here, it does not appear that we are providing a cert to the broker for connectivity, and SSL is currently set to false, with no provided parameters - this client implementation may require a server CA cert to complete TLS connectivity. This has been the case for some ESP32 implementations in the past, and the server CA file can be obtained from our Frequently Asked Questions thread here on the forum.

Best,
Aaron from the HiveMQ Team

Aaron thank you for your reply.

As you said, I solved it by adding a certificate. I will be adding a github link in an hour or two to help others. There is one point that sticks in my mind. Normally, when we connect from cli or linux machines, we can connect only with username and password without the need for special certification. What is the reason behind this situation for ESP32? Why does the broker consider esp32 as insecure?

Thank you very much.

Hello @rsemihkoca ,

I’m glad to hear that you were able to connect!

Typically, this has to do with the specific MQTT client implementation, rather than the device that is used to connect to the MQTT broker. In this case, the connection utilized by the client looks to have not been able to fully negotiate TLS with the server automatically, and required the CA certificate for authentication. This has been the case for a few different client implementations that we have seen with ESP32 devices. This can also be due to the CA not being automatically included in trust for a particular device, and we have seen some success with users adding Let’s Encrypt to trust.

Best,
Aaron from the HiveMQ Team

Thank you AAron for your detailed answer.

For anybody looking for basic implementation, here my public repo: