Skip to content

Standardise sockets #87

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

Merged
merged 27 commits into from
Jan 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
2a2b259
Rewrote socket.recv to match CPython and refactored other code in the…
Dec 22, 2022
e247f83
Rewrote htonl to use to_bytes and from_bytes, more than twice as fast…
Dec 22, 2022
bd2fe1d
Updated socket.send to return the number of bytes sent.
Dec 23, 2022
08adde6
Updated socket.sendto to return the number of bytes sent and match th…
Dec 23, 2022
cd92727
Updated socket.connect. Removed socket type parameter and ability to …
Dec 23, 2022
c3d6300
Updated socket.accept. Raise an exception instead of returning None. …
Dec 23, 2022
2b3edbd
Updated socket.bind to disallow changing the IP address of the interf…
Dec 24, 2022
95b618e
Removed _inet_aton. It duplicates wiznet5k.upretty_ip
Dec 24, 2022
6f65905
Updated socket.getpeername to return a tuple(address, port)
Dec 24, 2022
a454e91
Updated socket.__init__ to remove socknum from the attributes
Dec 24, 2022
721db87
Removed socket.is_ipv4 and updated getaddrinfo to compensate.
Dec 24, 2022
b76d15d
Removed socket.is_ipv4 and updated getaddrinfo to compensate.
Dec 24, 2022
0d91240
Implemented setdefaulttimeout, getdefaulttimeout, inet_ntoa, inet_ato…
Dec 24, 2022
b7650a3
Implemented timeout is None makes operations blocking.
Dec 24, 2022
05062e6
Sockets match CPython sockets. simpletest.py runs.
Dec 25, 2022
c47cd07
Disabled checking whether socket is already bound in socket.bind to a…
Dec 25, 2022
e6c8221
Checked type hints and doc strings. Added setblocking and getblocking…
Dec 25, 2022
baebea4
Fixed bad indent in doc string.
Dec 25, 2022
bc10472
Update tests after merging from origin.
Jan 9, 2023
eb3b04b
Merge in changes to main. Tests failing.
Jan 20, 2023
b794019
Updated tests to match changes merged in from main.
Jan 21, 2023
e28f87e
Check for endidness before converting in htonl and htons.
Jan 24, 2023
95871c9
Refactored two constants that were protected. Fixed a typo.
Jan 24, 2023
9cf28e5
Changed debugging default back to True.
Jan 24, 2023
150bfc9
Refactored soc_type to type.
Jan 24, 2023
ee6c82e
Merge branch 'adafruit:main' into Standardise_Sockets
BiffoBear Jan 24, 2023
bb60e7c
refactored bind() to allow it to be called with and without error che…
Jan 24, 2023
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
25 changes: 12 additions & 13 deletions adafruit_wiznet5k/adafruit_wiznet5k.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@
SNSR_SOCK_ESTABLISHED = const(0x17)
SNSR_SOCK_FIN_WAIT = const(0x18)
_SNSR_SOCK_CLOSING = const(0x1A)
_SNSR_SOCK_TIME_WAIT = const(0x1B)
_SNSR_SOCK_CLOSE_WAIT = const(0x1C)
SNSR_SOCK_TIME_WAIT = const(0x1B)
SNSR_SOCK_CLOSE_WAIT = const(0x1C)
_SNSR_SOCK_LAST_ACK = const(0x1D)
_SNSR_SOCK_UDP = const(0x22)
_SNSR_SOCK_IPRAW = const(0x32)
Expand Down Expand Up @@ -266,11 +266,13 @@ def get_host_by_name(self, hostname: str) -> bytes:
:return Union[int, bytes]: a 4 bytearray.
"""
if self._debug:
print("* Get host by name")
print(f"* Get host by name : {hostname}")
if isinstance(hostname, str):
hostname = bytes(hostname, "utf-8")
# Return IP assigned by DHCP
_dns_client = dns.DNS(self, self._dns, debug=self._debug)
_dns_client = dns.DNS(
self, self.pretty_ip(bytearray(self._dns)), debug=self._debug
)
ret = _dns_client.gethostbyname(hostname)
if self._debug:
print("* Resolved IP: ", ret)
Expand Down Expand Up @@ -824,9 +826,9 @@ def socket_open(self, socket_num: int, conn_mode: int = _SNMR_TCP) -> int:
status = self._read_snsr(socket_num)[0]
if status in (
SNSR_SOCK_CLOSED,
_SNSR_SOCK_TIME_WAIT,
SNSR_SOCK_TIME_WAIT,
SNSR_SOCK_FIN_WAIT,
_SNSR_SOCK_CLOSE_WAIT,
SNSR_SOCK_CLOSE_WAIT,
_SNSR_SOCK_CLOSING,
_SNSR_SOCK_UDP,
):
Expand Down Expand Up @@ -904,7 +906,7 @@ def socket_read( # pylint: disable=too-many-branches
if ret == 0:
# no data on socket?
status = self._read_snmr(socket_num)
if status in (SNSR_SOCK_LISTEN, SNSR_SOCK_CLOSED, _SNSR_SOCK_CLOSE_WAIT):
if status in (SNSR_SOCK_LISTEN, SNSR_SOCK_CLOSED, SNSR_SOCK_CLOSE_WAIT):
# remote end closed its side of the connection, EOF state
ret = 0
resp = 0
Expand Down Expand Up @@ -991,9 +993,6 @@ def socket_write(
if not self.link_status:
raise ConnectionError("Ethernet cable disconnected!")
assert socket_num <= self.max_sockets, "Provided socket exceeds max_sockets."
status = 0
ret = 0
free_size = 0
if len(buffer) > _SOCK_SIZE:
ret = _SOCK_SIZE
else:
Expand All @@ -1005,7 +1004,7 @@ def socket_write(
while free_size < ret:
free_size = self._get_tx_free_size(socket_num)
status = self.socket_status(socket_num)[0]
if status not in (SNSR_SOCK_ESTABLISHED, _SNSR_SOCK_CLOSE_WAIT) or (
if status not in (SNSR_SOCK_ESTABLISHED, SNSR_SOCK_CLOSE_WAIT) or (
timeout and time.monotonic() - stamp > timeout
):
ret = 0
Expand Down Expand Up @@ -1050,9 +1049,9 @@ def socket_write(
) != _SNIR_SEND_OK:
if self.socket_status(socket_num)[0] in (
SNSR_SOCK_CLOSED,
_SNSR_SOCK_TIME_WAIT,
SNSR_SOCK_TIME_WAIT,
SNSR_SOCK_FIN_WAIT,
_SNSR_SOCK_CLOSE_WAIT,
SNSR_SOCK_CLOSE_WAIT,
_SNSR_SOCK_CLOSING,
) or (timeout and time.monotonic() - stamp > timeout):
# self.socket_close(socket_num)
Expand Down
13 changes: 8 additions & 5 deletions adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,9 @@ def parse_dhcp_response(

:return Tuple[int, bytearray]: DHCP packet type and ID.
"""
global _BUFF # pylint: disable=global-statement
# store packet in buffer
_BUFF = self._sock.recv()
_BUFF = bytearray(self._sock.recv(len(_BUFF)))
if self._debug:
print("DHCP Response: ", _BUFF)

Expand Down Expand Up @@ -401,8 +402,10 @@ def _dhcp_state_machine(self) -> None:
self._dhcp_state = _STATE_DHCP_WAIT
else:
self._sock.settimeout(self._response_timeout)
self._sock.bind((None, 68))
self._sock.connect((self.dhcp_server_ip, _DHCP_SERVER_PORT))
self._sock.bind(("", 68))
self._sock.connect(
(".".join(map(str, self.dhcp_server_ip)), _DHCP_SERVER_PORT)
)
if self._last_lease_time == 0 or time.monotonic() > (
self._last_lease_time + self._lease_time
):
Expand All @@ -421,7 +424,7 @@ def _dhcp_state_machine(self) -> None:
self._dhcp_state = _STATE_DHCP_REQUEST

elif self._dhcp_state == _STATE_DHCP_DISCOVER:
if self._sock.available():
if self._sock._available(): # pylint: disable=protected-access
if self._debug:
print("* DHCP: Parsing OFFER")
try:
Expand Down Expand Up @@ -455,7 +458,7 @@ def _dhcp_state_machine(self) -> None:
print("* DHCP: Received DHCP Message is not OFFER")

elif self._dhcp_state == _STATE_DHCP_REQUEST:
if self._sock.available():
if self._sock._available(): # pylint: disable=protected-access
if self._debug:
print("* DHCP: Parsing ACK")
try:
Expand Down
12 changes: 7 additions & 5 deletions adafruit_wiznet5k/adafruit_wiznet5k_dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,6 @@ def __init__(
socket.set_interface(iface)
self._sock = socket.socket(type=socket.SOCK_DGRAM)
self._sock.settimeout(1)

self._dns_server = dns_address
self._query_id = 0 # Request ID.
self._query_length = 0 # Length of last query.
Expand All @@ -245,13 +244,14 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]:

:return Union[int, bytes] The IPv4 address if successful, -1 otherwise.
"""

if self._dns_server is None:
return _INVALID_SERVER
# build DNS request packet
self._query_id, self._query_length, buffer = _build_dns_query(hostname)

# Send DNS request packet
self._sock.bind((None, _DNS_PORT))
self._sock.bind(("", _DNS_PORT))
self._sock.connect((self._dns_server, _DNS_PORT))
_debug_print(debug=self._debug, message="* DNS: Sending request packet...")
self._sock.send(buffer)
Expand All @@ -261,9 +261,11 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]:
for _ in range(5):
# wait for a response
socket_timeout = time.monotonic() + 1.0
packet_size = self._sock.available()
packet_size = self._sock._available() # pylint: disable=protected-access
while packet_size == 0:
packet_size = self._sock.available()
packet_size = (
self._sock._available() # pylint: disable=protected-access
)
if time.monotonic() > socket_timeout:
_debug_print(
debug=self._debug,
Expand All @@ -273,7 +275,7 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]:
return -1
time.sleep(0.05)
# recv packet into buf
buffer = self._sock.recv()
buffer = self._sock.recv(512) # > UDP payload length
_debug_print(
debug=self._debug,
message="DNS Packet Received: {}".format(buffer),
Expand Down
2 changes: 1 addition & 1 deletion adafruit_wiznet5k/adafruit_wiznet5k_ntp.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def get_time(self) -> time.struct_time:
self._sock.sendto(self._pkt_buf_, (self._ntp_server, 123))
end_time = time.monotonic() + 0.2 * 2**retry
while time.monotonic() < end_time:
data = self._sock.recv()
data = self._sock.recv(64) # NTP returns a 48 byte message.
if data:
sec = data[40:44]
int_cal = int.from_bytes(sec, "big")
Expand Down
Loading