Skip to content

Wrong semantics for size in socket.recv() causes sporatic failures in message parsing #54

Closed
@flavio-fernandes

Description

@flavio-fernandes

The code for socket read has a buffer size param that indicates the maximum number of bytes
that can be returned within a single call:

https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/blob/fce466bd2bb70ca86b79e5cb36bbaca00afacfd1/adafruit_esp32spi/adafruit_esp32spi_socket.py#L107-L112

Trouble is, MQTT is using that param as if that would be the minimum number of bytes that should be returned.

Also, ping method tries to drain buffer looking for the PINGRESP message and if that is not the message in the
receive buffer, it never reverts the 1 byte it took out of the buffer.

while True:
op = self._wait_for_msg(0.5)
if op == 208:
ping_resp = self._sock.recv(2)
if ping_resp[0] != 0x00:
raise MMQTTException("PINGRESP not returned from broker.")
return

After that point, MQTT broker and client are 'out of sync', causing any future exchanges to be 'out of whack'.
A better approach would be to flag that a ping response is expected, but handle it together with any other MQTT
message via _wait_for_msg

1106.57: DEBUG - KeepAlive period elapsed - requesting a PINGRESP from the server...
1106.57: DEBUG - Sending PINGREQ
Writing: b'\xc0\x00'
1106.63: DEBUG - Checking PINGRESP
ESPSocket: 27 bytes available
Reading 1 bytes from ESP socket with status 4
ESPSocket: 26 bytes available
Reading 1 bytes from ESP socket with status 4
ESPSocket: 25 bytes available
Reading 2 bytes from ESP socket with status 4
ESPSocket: 23 bytes available
Reading 21 bytes from ESP socket with status 4
ESPSocket: 2 bytes available
Reading 2 bytes from ESP socket with status 4
Traceback (most recent call last):
  File "code.py", line 297, in <module>
  File "/lib/adafruit_minimqtt/adafruit_minimqtt.py", line 704, in loop
  File "/lib/adafruit_minimqtt/adafruit_minimqtt.py", line 407, in ping
  File "/lib/adafruit_minimqtt/adafruit_minimqtt.py", line 734, in _wait_for_msg
UnicodeError: 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions