← index #1056Issue #110
Likely Duplicate · medium · value 2.277
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

[solved] MQTT: c.connect() -> IndexError: bytes index out of range

closedby BigMan200opened 2016-10-30updated 2022-09-06

On a raspian (IP=10.0.0.32) I installed mosquitto:
service mosquitto status
gives me: [ ok ] mosquitto is running.

An ESP8266 is in the same network:
FW: esp8266-20161017-v1.8.5.bin
'>>> sta_if.ifconfig()
gives me: ('10.0.0.105', ...)

On the raspian-terminal I can also ping my ESP8266:
ping 10.0.0.105
gives me: 64 bytes from 10.0.0.105: icmp_req=1 ttl=255 time=2.62 ms ...

But I am failing to connect with the MQTT:
'>>> from umqtt.simple import MQTTClient
'>>> c = MQTTClient("client", "10.0.0.32")
'>>> c.connect()
gives me:
Traceback (most recent call last):
File "", line 1, in
File "umqtt/simple.py", line 84, in connect
IndexError: bytes index out of range

25 comments
pfalcon · 2016-10-30

I think the problem is solved:
I have to change '>>> c = MQTTClient("client", "10.0.0.32")
With '>>> c = MQTTClient(b"client", b"10.0.0.32")

Well, that might make a difference for CPython, but not for MicroPython, we have relaxed rules regarding str vs bytes, and in many contexts where bytes are required, str can be passed (assumed to have utf-8 encoding).

As https://github.com/micropython/micropython-lib/blob/v1.8.4/umqtt.simple/umqtt/simple.py#L84, the problem is that your server doesn't return valid MQTT response. So, you would need to diagnose your server why it does so (it may be a network problem too, etc.)

pfalcon · 2016-10-30

From my perspective as a maintainer, the content of this bug is: should this error be caught and and MQTTException be thrown instead? That won't change much - there will still be one error instead of another, and it still will be numerically coded, so user would need to look at the source to figure out what's wrong, just like they need to do now. But that will increase code size, eating out resources from user application (so it will start to fail with a higher probability). Is it worth it? I can't decide myself, experienced users, please comment and vote.

BigMan200 · 2016-10-30

Well unfortunately, the change below, did not work:
I have to change '>>> c = MQTTClient("client", "10.0.0.32")
With '>>> c = MQTTClient(b"client", b"10.0.0.32")

The problem is still existing.
However ... next I will check if I can connect to the mqtt-Broker by clients other than the ESP8266 ... just so see, if the problem is really at the server's side.

pfalcon · 2016-10-30

However ... next I will check if I can connect to the mqtt-Broker by clients other than the ESP8266 ... just so see, if the problem is really at the server's side.

Good idea. I would actually recommend (for all future cases) to start with that, and only then try it with systems like esp8266.

cprima · 2016-10-30

I get that frequently when I do only a soft-reset.
Try to do a proper import machine, machine.reset() and see if your problem goes away.

I have not looked at it, but soon I need a better "tear-down and rebuild" way of doing it.

Unfortunately the normal ping() responses are filtered away by the code, so we cannot check that in a try-except-block.

BigMan200 · 2016-10-30

... I have installed a MQTT-Client on my Android-Phone ... well ... it connected to the broker and also received messages from it ... so, I cannot blame the server and I am back on searching the bug at the ESP8266 resp. at my microPython-code

I also made a machine.reset() ... no success.

cprima · 2016-10-30

Something is funny with the latest changes, in master there is now a line
self.settimeout(self.timeout)
which maybe is intended to be self.socket.settimeout()
?

pfalcon · 2016-10-30

back on searching the bug at the ESP8266 resp.

Fortunately, with MicroPython it's easy - all code is open and simple enough. And that's the idea behine MicroPython - you have insight into everything, so if something for example doesn't work as expected, you can easily investigate it.

I also made a machine.reset() ... no success.

Wouldn't help in general. Again, your server replies wrong data, or just closes connection when your esp8266 tries to connect. (Or your network makes it look so for your esp8266, you'd need network analyzer to check that possibility).

pfalcon · 2016-10-30

self.settimeout(self.timeout)
which maybe is intended to be self.socket.settimeout()

Thanks for spotting.

cprima · 2016-10-30

The current micropython-lib/umqtt/simple.py copied into modules/ and manually adding .sock and compiling for the esp8266 gives me:

from umqtt.simple import MQTTClient
c = MQTTClient("client", "10.xx.yy.236")
c.connect()
0

But my button debouncing stopped working with funny negative values in ticks_diff(), it does though if I revert to esp8266-20161022-v1.8.5-26-g3730090.bin :( But that's not the topic here, maybe I find some qulified bug-report-worthy issue

cprima · 2016-10-30

Ah, for that OT thingy I found the commit message :)

pfalcon · 2016-10-30

But my button debouncing stopped working with funny negative values in ticks_diff()

Switch args to ticks_diff(). And thanks for the notice - I wouldn't think a first case of it breaking somebody's code will appear so soon :-I. We'll have a topic on the forum regarding this, you're welcome to chime in and criticize such changes (but if we don't change API to make it better, we'll have messy bloat accumulate in uPy, as we need to drag "old" and "new" APIs along).

pfalcon · 2016-10-30

timeout changes are reverted. You'll need to do git pull --rebase in your micropython-lib checkout.

BigMan200 · 2016-10-30

The latest suggestion was that the server (=mqtt-broker) provides wrong data ... can this be, given the cirumstance that other clients (android-apps) are fine with the server (they do connect to the broker and receive data)??

I also tried to follow the recommendation to check the network-traffic with a network analyzer (even if I was not sure, how to use such an analyzer and what to look for). I installed Wireshark (with all the hazzle to make it running as a non-root). .... but there are now 1E6 further questions regarding Wireshark (which I had to post on a Wireshark forum) ... simply speaking: I am not experienced enough for that ..

Bottom line:
is there a another way than a network analyzer to make sure that the server is really the problem, although my mobile-phone client can perfectly communcate with the mqtt-broker/server?

cprima · 2016-10-30

On the mosquitto-side I have added this to /etc/mosquitto/mosquitto.conf
log_dest file /var/log/mosquitto.log
and did a chown mosquitto:mosquitto /var/log/mosquitto.log
Then a systemctl restart mosquitto

Maybe you could do that and see if there are

  • "Socket error in client"...
  • "Invalid"...
  • ..."exceeded timeout"...
    or similar log entries?
cprima · 2016-10-30

By the way, I have this mosquitto version and it works:

# mosquitto -h
mosquitto version 1.4.10 (build date 2016-10-10 19:26:42+0000)

mosquitto is an MQTT v3.1 broker.
cprima · 2016-10-30

I cannot reproduce on a NodeMCU ESP8266:

wget http://micropython.org/resources/firmware/esp8266-20161017-v1.8.5.bin

esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=8m -fm dio 0x00000 esp8266-20161017-v1.8.5.bin --verify

def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('my_essid', 'my_password')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())


from umqtt.simple import MQTTClient
c = MQTTClient("client", "10.xx.yy.236")
c.connect()
BigMan200 · 2016-10-30

I started the logging on the mqtt-server side (IP: 10.0.0.32). When I do the c.connect() on the ESP8266 (IP: 10.0.0.105), I get the following log-message:

Oct 30 15:10:09 raspberrypi mosquitto[2288]: Invalid protocol "MQTT" in CONNECT from 10.0.0.105.
Oct 30 15:10:09 raspberrypi mosquitto[2288]: Socket read error on client (null), disconnecting.
Oct 30 15:10:09 raspberrypi mosquitto[2288]: New connection from 10.0.0.105.
Oct 30 15:10:09 raspberrypi mosquitto[2288]: Invalid protocol "MQTT" in CONNECT from 10.0.0.105.
Oct 30 15:10:09 raspberrypi mosquitto[2288]: Socket read error on client (null), disconnecting.

BTW: mosquitto -h --> mosquitto is an MQTT v3.1 broker.

cprima · 2016-10-30

There are many hits on Google that say something like "on an RPi it incorrectly reported as v3.1" -- do you also get a "proper" version info?

Here is a sample solution that I am sure will work for you, too (as I am 100% sure this is on your RPi):
http://diy.viktak.com/2015/05/installing-mosquitto-for-use-with.html

BigMan200 · 2016-10-30

WOW ... cprior ... you are my hero!
It works! Thanks a million time!
:-) :-) :-)

cprima · 2016-10-30

I am currently also deep in all that MicroPython & MQTT stuff, so your Issue caught my attention.
Have a lot of fun then! :)

(And maybe close the Issue)

pfalcon · 2016-10-30

@peterhinch: Maybe something from this ticket will be useful for your FAQ.

peterhinch · 2016-10-31

@pfalcon Now done.

pfalcon · 2017-03-12

Ok, as this marked "[solved]", closing.

timsengit · 2022-09-06

in my case,I write wrong port case this error,please check your emqttx port one more time!!

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