← index #1056Issue #5071
Related · high · value 1.294
QUERY · ISSUE

IndexError: bytes index out of range

openby MikeZhou-UofTopened 2025-11-10updated 2025-11-10

When I run the code simple.py on a Pi Pico.

I was getting "IndexError: bytes index out of range" after the internet was connected, but the MQTT broker connection failed.

From line 112 of simple.py: assert resp[0] == 0x20 and resp[1] == 0x02

It was saying "in connect" but afterward, it is giving me IndexError: bytes index out of range. Has anyone had this issue before?

What I have to do is unplug the USB and plug it back in multiple times to make it work.

1 comment
Josverl · 2025-11-10

Likely, in that case, the resp object is shorter than the two bytes.

The library is simple, it does not handle all possible error, so you may need to wrap it in additional error handling,
also to deal with external glitches in networks , DNS and other interferences.

CANDIDATE · ISSUE

[STM32-F2] - mqtt connect fails on latest builds.

closedby pacmacopened 2019-09-05updated 2019-09-16
bugport-stm32

When using build MicroPython v1.9.3-1869-ga9b1d3ca3, the mqtt transaction succeeds:

>>> import mqtest
dbug-msg: 0x9 b'04:4d:51:54:54:04:02:00:00'
dbug-resp: b' \x02\x00\x00'
connect: 0
publish: None
disconnect: None

On latest release: MicroPython v1.11-274-g06661890d - it fails:

>>> import mqtest
dbug-msg: 0x9 b'04:4d:51:54:54:04:02:00:00'
dbug-resp: b''
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mqtest.py", line 37, in <module>
  File "mqtest.py", line 33, in go
  File "umqtt_robust.py", line 101, in connect
IndexError: bytes index out of range

This is my test code:

from umqtt_robust import MQTTClient

id      = b'484a300173f0'
host    = b'mqtt.thingspeak.com'
port    = 1883
retain  = False
topic   = "channels/MY-CHANNEL-ID/publish/MY-ACCESS-KEY"
data    = 'field6=100&field5=4019&field4=64.20001&field3=29.5&field2=73.1&field1=29.5&field8={"last_stamp": 1495097691048, "update_secs": 300, "name": "Room", "devid": "484a300173f0"}&status=MQTTPUBLISH&field7=-9318.205'

client = MQTTClient(id,host,port=port)

def go():
  print('connect:',client.connect())
  print('publish:',client.publish(topic,data,retain=retain))
  print('disconnect:',client.disconnect());

go()

This is the code in mqtt_simple / robust that is debugged & failing:

    def connect(self, clean_session=True):
        self.sock = socket.socket()
        addr = socket.getaddrinfo(self.server, self.port)[0][-1]
        self.sock.connect(addr)
        if self.ssl:
            import ussl
            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
        premsg = bytearray(b"\x10\0\0\0\0\0")
        msg = bytearray(b"\x04MQTT\x04\x02\0\0")

        sz = 10 + 2 + len(self.client_id)
        msg[6] = clean_session << 1
        if self.user is not None:
            sz += 2 + len(self.user) + 2 + len(self.pswd)
            msg[6] |= 0xC0
        if self.keepalive:
            assert self.keepalive < 65536
            msg[7] |= self.keepalive >> 8
            msg[8] |= self.keepalive & 0x00FF
        if self.lw_topic:
            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
            msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
            msg[6] |= self.lw_retain << 5

        i = 1
        while sz > 0x7f:
            premsg[i] = (sz & 0x7f) | 0x80
            sz >>= 7
            i += 1
        premsg[i] = sz

        self.sock.write(premsg, i + 2)
        self.sock.write(msg)
        print('dbug-msg:',hex(len(msg)), hexlify(msg, ":"))
        self._send_str(self.client_id)
        if self.lw_topic:
            self._send_str(self.lw_topic)
            self._send_str(self.lw_msg)
        if self.user is not None:
            self._send_str(self.user)
            self._send_str(self.pswd)
        resp = self.sock.read(4)
        print('dbug-resp:',resp)
        assert resp[0] == 0x20 and resp[1] == 0x02
        if resp[3] != 0:
            raise MQTTException(resp[3])
        return resp[2] & 1

This is also reported here: https://forum.micropython.org/viewtopic.php?f=2&t=6890

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied