Skip to content

Commit 8492a58

Browse files
author
brentru
committed
backwards compat. recv, adding shared buffer impl to save memory
1 parent fbfb6ec commit 8492a58

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -144,15 +144,15 @@ def __init__(
144144
socket_pool=None,
145145
ssl_context=None
146146
):
147-
# Socket Pool
148-
if socket_pool:
149-
self._socket_pool = socket_pool
147+
148+
self._socket_pool = socket_pool
150149
self._ssl_context = ssl_context
151150
# Hang onto open sockets so that we can reuse them
152151
self._socket_free = {}
153152
self._open_sockets = {}
154-
155153
self._sock = None
154+
self._backwards_compatible_sock = False
155+
156156
self.keep_alive = keep_alive
157157
self._user_data = None
158158
self._is_connected = False
@@ -290,6 +290,8 @@ def _get_socket(self, host, port, *, timeout=1):
290290
if sock is None:
291291
raise RuntimeError("Repeated socket failures")
292292

293+
self._backwards_compatible_sock = not hasattr(sock, "recv_into")
294+
293295
self._open_sockets[key] = sock
294296
self._socket_free[sock] = False
295297
return sock
@@ -819,15 +821,16 @@ def loop(self, timeout=0.01):
819821

820822
def _wait_for_msg(self, timeout=0.01):
821823
"""Reads and processes network events."""
822-
res = bytearray(1) #TODO: This should be a globally shared buffer for readinto
823824

825+
# attempt to recv from socket within `timeout` seconds
824826
self._sock.settimeout(timeout)
825827
try:
828+
res = bytearray(1) #TODO: This should be a globally shared buffer for readinto
826829
self._sock.recv_into(res, 1)
827-
except BlockingIOError: # fix for macOS Errno
828-
return None
829830
except self._socket_pool.timeout:
830831
return None
832+
except BlockingIOError: # fixes macOS socket Errno 35
833+
return None
831834

832835
self._sock.setblocking(True)
833836
if res in [None, b""]:
@@ -868,6 +871,17 @@ def _recv_len(self):
868871
return n
869872
sh += 7
870873

874+
def _recv_into(self, buf, size=0):
875+
"""Backwards-compatible _recv_into implementation.
876+
"""
877+
if self._backwards_compatible_sock:
878+
size = len(buf) if size == 0 else size
879+
b = self._sock.recv(size)
880+
read_size = len(b)
881+
buf[:read_size] = b
882+
return read_size
883+
return self._sock.recv_into(buf, size)
884+
871885
def _send_str(self, string):
872886
"""Packs and encodes a string to a socket.
873887

0 commit comments

Comments
 (0)