Skip to content

Commit 05062e6

Browse files
author
BiffoBear
committed
Sockets match CPython sockets. simpletest.py runs.
1 parent b7650a3 commit 05062e6

File tree

4 files changed

+37
-28
lines changed

4 files changed

+37
-28
lines changed

adafruit_wiznet5k/adafruit_wiznet5k.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -264,11 +264,13 @@ def get_host_by_name(self, hostname: str) -> bytes:
264264
:return Union[int, bytes]: a 4 bytearray.
265265
"""
266266
if self._debug:
267-
print("* Get host by name")
267+
print(f"* Get host by name : {hostname}")
268268
if isinstance(hostname, str):
269269
hostname = bytes(hostname, "utf-8")
270270
# Return IP assigned by DHCP
271-
_dns_client = dns.DNS(self, self._dns, debug=self._debug)
271+
_dns_client = dns.DNS(
272+
self, self.pretty_ip(bytearray(self._dns)), debug=self._debug
273+
)
272274
ret = _dns_client.gethostbyname(hostname)
273275
if self._debug:
274276
print("* Resolved IP: ", ret)

adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,9 @@ def parse_dhcp_response(
267267
268268
:return Union[Tuple[int, bytes], Tuple[int, int]]: DHCP packet type.
269269
"""
270+
global _BUFF # pylint: disable=global-statement
270271
# store packet in buffer
271-
_BUFF = self._sock.recv()
272+
_BUFF = bytearray(self._sock.recv(len(_BUFF)))
272273
if self._debug:
273274
print("DHCP Response: ", _BUFF)
274275

@@ -403,8 +404,10 @@ def _dhcp_state_machine(self) -> None:
403404
self._dhcp_state = STATE_DHCP_WAIT
404405
else:
405406
self._sock.settimeout(self._response_timeout)
406-
self._sock.bind((None, 68))
407-
self._sock.connect((self.dhcp_server_ip, DHCP_SERVER_PORT))
407+
self._sock.bind(("", 68))
408+
self._sock.connect(
409+
(".".join(map(str, self.dhcp_server_ip)), DHCP_SERVER_PORT)
410+
)
408411
if self._last_lease_time == 0 or time.monotonic() > (
409412
self._last_lease_time + self._lease_time
410413
):
@@ -423,7 +426,7 @@ def _dhcp_state_machine(self) -> None:
423426
self._dhcp_state = STATE_DHCP_REQUEST
424427

425428
elif self._dhcp_state == STATE_DHCP_DISCOVER:
426-
if self._sock.available():
429+
if self._sock._available(): # pylint: disable=protected-access
427430
if self._debug:
428431
print("* DHCP: Parsing OFFER")
429432
msg_type, xid = self.parse_dhcp_response()
@@ -448,7 +451,7 @@ def _dhcp_state_machine(self) -> None:
448451
print("* DHCP: Received DHCP Message is not OFFER")
449452

450453
elif self._dhcp_state == STATE_DHCP_REQUEST:
451-
if self._sock.available():
454+
if self._sock._available(): # pylint: disable=protected-access
452455
if self._debug:
453456
print("* DHCP: Parsing ACK")
454457
msg_type, xid = self.parse_dhcp_response()

adafruit_wiznet5k/adafruit_wiznet5k_dns.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
"""
1616
from __future__ import annotations
1717

18+
import gc
19+
1820
try:
1921
from typing import TYPE_CHECKING, Union, Tuple
2022

@@ -54,7 +56,7 @@ def __init__(
5456
self,
5557
iface: WIZNET5K,
5658
dns_address: Union[str, Tuple[int, int, int, int]],
57-
debug: bool = False,
59+
debug: bool = True,
5860
) -> None:
5961
"""
6062
:param adafruit_wiznet5k.WIZNET5K: Ethernet network connection.
@@ -66,7 +68,6 @@ def __init__(
6668
socket.set_interface(iface)
6769
self._sock = socket.socket(type=socket.SOCK_DGRAM)
6870
self._sock.settimeout(1)
69-
7071
self._dns_server = dns_address
7172
self._host = b""
7273
self._request_id = 0 # request identifier
@@ -80,6 +81,7 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]:
8081
8182
:return Union[int, bytes] The IPv4 address if successful, -1 otherwise.
8283
"""
84+
8385
if self._dns_server is None:
8486
return INVALID_SERVER
8587
self._host = hostname
@@ -88,7 +90,7 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]:
8890
self._build_dns_question()
8991

9092
# Send DNS request packet
91-
self._sock.bind((None, DNS_PORT))
93+
self._sock.bind(("", DNS_PORT))
9294
self._sock.connect((self._dns_server, DNS_PORT))
9395
if self._debug:
9496
print("* DNS: Sending request packet...")
@@ -225,6 +227,7 @@ def _parse_dns_response(
225227
print("* DNS ERROR: Unexpected Data Length: ", data_len)
226228
return -1
227229
ptr += 2
230+
gc.collect()
228231
# Return address
229232
return self._pkt_buf[ptr : ptr + 4]
230233

adafruit_wiznet5k/adafruit_wiznet5k_socket.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,8 @@ def gethostbyname(hostname: str) -> str:
186186
187187
:return str: IPv4 address (a string of the form '0.0.0.0').
188188
"""
189+
if _is_ipv4_string(hostname):
190+
return hostname
189191
address = _the_interface.get_host_by_name(hostname)
190192
address = "{}.{}.{}.{}".format(address[0], address[1], address[2], address[3])
191193
return address
@@ -297,7 +299,9 @@ def bind(self, address: Tuple[Optional[str], int]) -> None:
297299
:raises ValueError: If the IPv4 address specified is not the address
298300
assigned to the WIZNET5K interface.
299301
"""
300-
if not self._listen_port:
302+
if self._listen_port:
303+
raise ConnectionError("The socket is already bound.")
304+
if address[0]:
301305
if gethostbyname(address[0]) != _the_interface.pretty_ip(
302306
_the_interface.ip_address
303307
):
@@ -307,18 +311,16 @@ def bind(self, address: Tuple[Optional[str], int]) -> None:
307311
_the_interface.pretty_ip(_the_interface.ip_address)
308312
)
309313
)
310-
self._listen_port = address[1]
311-
# For UDP servers we need to open the socket here because we won't call
312-
# listen
313-
if self._sock_type == SOCK_DGRAM:
314-
_the_interface.socket_listen(
315-
self._socknum,
316-
self._listen_port,
317-
wiznet5k.adafruit_wiznet5k.SNMR_UDP,
318-
)
319-
self._buffer = b""
320-
else:
321-
raise ConnectionError("The socket is already bound.")
314+
self._listen_port = address[1]
315+
# For UDP servers we need to open the socket here because we won't call
316+
# listen
317+
if self._sock_type == SOCK_DGRAM:
318+
_the_interface.socket_listen(
319+
self._socknum,
320+
self._listen_port,
321+
wiznet5k.adafruit_wiznet5k.SNMR_UDP,
322+
)
323+
self._buffer = b""
322324

323325
def listen(self, backlog: int = 0) -> None:
324326
"""
@@ -379,7 +381,10 @@ def connect(self, address: Tuple[str, int]) -> None:
379381
if self._listen_port is not None:
380382
_the_interface.src_port = self._listen_port
381383
result = _the_interface.socket_connect(
382-
self._socknum, bytes(gethostbyname(address[0])), address[1], self._sock_type
384+
self._socknum,
385+
_the_interface.unpretty_ip(gethostbyname(address[0])),
386+
address[1],
387+
self._sock_type,
383388
)
384389
_the_interface.src_port = 0
385390
if not result:
@@ -467,8 +472,6 @@ def _embed_recv(
467472
468473
:return bytes: All data available from the connection.
469474
"""
470-
# print("Socket read", bufsize)
471-
ret = None
472475
avail = self._available()
473476
if avail:
474477
if self._sock_type == SOCK_STREAM:
@@ -477,7 +480,6 @@ def _embed_recv(
477480
self._buffer += _the_interface.read_udp(self._socknum, avail)[1]
478481
gc.collect()
479482
ret = self._buffer
480-
# print("RET ptr:", id(ret), id(self._buffer))
481483
self._buffer = b""
482484
gc.collect()
483485
return ret
@@ -597,7 +599,6 @@ def settimeout(self, value: Optional[float]) -> None:
597599
598600
:param fOptional[float] value: Socket read timeout in seconds.
599601
"""
600-
# TODO: Implement None and 0.0 as valid once all socket funcs can handle them.
601602
if value is None or (isinstance(value, (int, float)) and value >= 0):
602603
self._timeout = value
603604
else:

0 commit comments

Comments
 (0)