Skip to content

Commit 93d6d28

Browse files
authored
Merge pull request #143 from us3r64/fix/socket-recv-timeout
Fix socket recv timeout: None:blocking, 0:non-blocking, >0:timeout
2 parents a0e9562 + 828a243 commit 93d6d28

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

adafruit_wiznet5k/adafruit_wiznet5k_socket.py

+16-5
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from __future__ import annotations
1818

1919
try:
20-
from typing import TYPE_CHECKING, Optional, Tuple, List, Union
20+
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
2121

2222
if TYPE_CHECKING:
2323
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
@@ -27,6 +27,7 @@
2727
import gc
2828
import time
2929
from sys import byteorder
30+
3031
from micropython import const
3132

3233
import adafruit_wiznet5k as wiznet5k
@@ -79,7 +80,7 @@ def setdefaulttimeout(_timeout: Optional[float]) -> None:
7980
:param Optional[float] _timeout: The default timeout in seconds or None.
8081
"""
8182
global _default_socket_timeout # pylint: disable=global-statement
82-
if _timeout is None or (isinstance(_timeout, (int, float)) and _timeout >= 0):
83+
if _timeout is None or _timeout >= 0:
8384
_default_socket_timeout = _timeout
8485
else:
8586
raise ValueError("Timeout must be None, 0.0 or a positive numeric value.")
@@ -496,7 +497,11 @@ def recv(
496497
:return bytes: Data from the socket.
497498
"""
498499
buf = bytearray(bufsize)
499-
self.recv_into(buf, bufsize)
500+
nread = self.recv_into(buf, bufsize)
501+
if nread == 0:
502+
return b""
503+
if nread < bufsize:
504+
return bytes(buf[:nread])
500505
return bytes(buf)
501506

502507
def _embed_recv(
@@ -595,7 +600,13 @@ def recv_into(self, buffer: bytearray, nbytes: int = 0, flags: int = 0) -> int:
595600
# We got a message, but there are no more bytes to read, so we can stop.
596601
break
597602
# No bytes yet, or more bytes requested.
598-
if self._timeout > 0 and time.monotonic() - last_read_time > self._timeout:
603+
if self._timeout is None:
604+
# blocking mode
605+
continue
606+
if self._timeout == 0:
607+
# non-blocking mode
608+
break
609+
if time.monotonic() - last_read_time > self._timeout:
599610
raise timeout("timed out")
600611
return num_read
601612

@@ -688,7 +699,7 @@ def settimeout(self, value: Optional[float]) -> None:
688699
689700
:param Optional[float] value: Socket read timeout in seconds.
690701
"""
691-
if value is None or (isinstance(value, (int, float)) and value >= 0):
702+
if value is None or value >= 0:
692703
self._timeout = value
693704
else:
694705
raise ValueError("Timeout must be None, 0.0 or a positive numeric value.")

0 commit comments

Comments
 (0)