Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix socket recv timeout: None:blocking, 0:non-blocking, >0:timeout #143

Merged
merged 1 commit into from
Mar 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions adafruit_wiznet5k/adafruit_wiznet5k_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from __future__ import annotations

try:
from typing import TYPE_CHECKING, Optional, Tuple, List, Union
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

if TYPE_CHECKING:
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
Expand All @@ -27,6 +27,7 @@
import gc
import time
from sys import byteorder

from micropython import const

import adafruit_wiznet5k as wiznet5k
Expand Down Expand Up @@ -79,7 +80,7 @@ def setdefaulttimeout(_timeout: Optional[float]) -> None:
:param Optional[float] _timeout: The default timeout in seconds or None.
"""
global _default_socket_timeout # pylint: disable=global-statement
if _timeout is None or (isinstance(_timeout, (int, float)) and _timeout >= 0):
if _timeout is None or _timeout >= 0:
_default_socket_timeout = _timeout
else:
raise ValueError("Timeout must be None, 0.0 or a positive numeric value.")
Expand Down Expand Up @@ -496,7 +497,11 @@ def recv(
:return bytes: Data from the socket.
"""
buf = bytearray(bufsize)
self.recv_into(buf, bufsize)
nread = self.recv_into(buf, bufsize)
if nread == 0:
return b""
if nread < bufsize:
return bytes(buf[:nread])
return bytes(buf)

def _embed_recv(
Expand Down Expand Up @@ -595,7 +600,13 @@ def recv_into(self, buffer: bytearray, nbytes: int = 0, flags: int = 0) -> int:
# We got a message, but there are no more bytes to read, so we can stop.
break
# No bytes yet, or more bytes requested.
if self._timeout > 0 and time.monotonic() - last_read_time > self._timeout:
if self._timeout is None:
# blocking mode
continue
if self._timeout == 0:
# non-blocking mode
break
if time.monotonic() - last_read_time > self._timeout:
raise timeout("timed out")
return num_read

Expand Down Expand Up @@ -688,7 +699,7 @@ def settimeout(self, value: Optional[float]) -> None:

:param Optional[float] value: Socket read timeout in seconds.
"""
if value is None or (isinstance(value, (int, float)) and value >= 0):
if value is None or value >= 0:
self._timeout = value
else:
raise ValueError("Timeout must be None, 0.0 or a positive numeric value.")
Expand Down
Loading