Skip to content

Commit bc10472

Browse files
author
BiffoBear
committed
Update tests after merging from origin.
2 parents baebea4 + 6bc9f63 commit bc10472

File tree

5 files changed

+625
-91
lines changed

5 files changed

+625
-91
lines changed

adafruit_wiznet5k/adafruit_wiznet5k.py

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,8 @@ def __init__(
187187

188188
# attempt to initialize the module
189189
self._ch_base_msb = 0
190-
assert self._w5xxx_init() == 1, "Failed to initialize WIZnet module."
190+
if self._w5xxx_init() != 1:
191+
raise RuntimeError("Failed to initialize WIZnet module.")
191192
# Set MAC address
192193
self.mac_address = mac
193194
self.src_port = 0
@@ -214,7 +215,8 @@ def __init__(
214215
ret = self.set_dhcp(hostname, dhcp_timeout)
215216
if ret != 0:
216217
self._dhcp_client = None
217-
assert ret == 0, "Failed to configure DHCP Server!"
218+
if ret != 0:
219+
raise RuntimeError("Failed to configure DHCP Server!")
218220

219221
def set_dhcp(
220222
self, hostname: Optional[str] = None, response_timeout: float = 30
@@ -274,7 +276,8 @@ def get_host_by_name(self, hostname: str) -> bytes:
274276
ret = _dns_client.gethostbyname(hostname)
275277
if self._debug:
276278
print("* Resolved IP: ", ret)
277-
assert ret != -1, "Failed to resolve hostname!"
279+
if ret == -1:
280+
raise RuntimeError("Failed to resolve hostname!")
278281
return ret
279282

280283
@property
@@ -628,7 +631,8 @@ def socket_available(self, socket_num: int, sock_type: int = SNMR_TCP) -> int:
628631
socket_num, sock_type
629632
)
630633
)
631-
assert socket_num <= self.max_sockets, "Provided socket exceeds max_sockets."
634+
if socket_num > self.max_sockets:
635+
raise ValueError("Provided socket exceeds max_sockets.")
632636

633637
res = self._get_rx_rcv_size(socket_num)
634638

@@ -681,7 +685,8 @@ def socket_connect(
681685
:param int conn_mode: The connection mode. Use SNMR_TCP for TCP or SNMR_UDP for UDP,
682686
defaults to SNMR_TCP.
683687
"""
684-
assert self.link_status, "Ethernet cable disconnected!"
688+
if not self.link_status:
689+
raise ConnectionError("Ethernet cable disconnected!")
685690
if self._debug:
686691
print(
687692
"* w5k socket connect, protocol={}, port={}, ip={}".format(
@@ -691,7 +696,7 @@ def socket_connect(
691696
# initialize a socket and set the mode
692697
res = self.socket_open(socket_num, conn_mode=conn_mode)
693698
if res == 1:
694-
raise RuntimeError("Failed to initialize a connection with the socket.")
699+
raise ConnectionError("Failed to initialize a connection with the socket.")
695700

696701
# set socket destination IP and port
697702
self._write_sndipr(socket_num, dest)
@@ -705,7 +710,7 @@ def socket_connect(
705710
if self._debug:
706711
print("SN_SR:", self.socket_status(socket_num)[0])
707712
if self.socket_status(socket_num)[0] == SNSR_SOCK_CLOSED:
708-
raise RuntimeError("Failed to establish connection.")
713+
raise ConnectionError("Failed to establish connection.")
709714
elif conn_mode == SNMR_UDP:
710715
self.udp_datasize[socket_num] = 0
711716
return 1
@@ -749,7 +754,8 @@ def socket_listen(
749754
:param int conn_mode: Connection mode SNMR_TCP for TCP or SNMR_UDP for
750755
UDP, defaults to SNMR_TCP.
751756
"""
752-
assert self.link_status, "Ethernet cable disconnected!"
757+
if not self.link_status:
758+
raise ConnectionError("Ethernet cable disconnected!")
753759
if self._debug:
754760
print(
755761
"* Listening on port={}, ip={}".format(
@@ -809,7 +815,8 @@ def socket_open(self, socket_num: int, conn_mode: int = SNMR_TCP) -> int:
809815
UDP, defaults to SNMR_TCP.
810816
:return int: 1 if the socket was opened, 0 if not.
811817
"""
812-
assert self.link_status, "Ethernet cable disconnected!"
818+
if not self.link_status:
819+
raise ConnectionError("Ethernet cable disconnected!")
813820
if self._debug:
814821
print("*** Opening socket %d" % socket_num)
815822
status = self._read_snsr(socket_num)[0]
@@ -841,10 +848,8 @@ def socket_open(self, socket_num: int, conn_mode: int = SNMR_TCP) -> int:
841848
# open socket
842849
self._write_sncr(socket_num, CMD_SOCK_OPEN)
843850
self._read_sncr(socket_num)
844-
assert (
845-
self._read_snsr((socket_num))[0] == 0x13
846-
or self._read_snsr((socket_num))[0] == 0x22
847-
), "Could not open socket in TCP or UDP mode."
851+
if self._read_snsr((socket_num))[0] not in [0x13, 0x22]:
852+
raise RuntimeError("Could not open socket in TCP or UDP mode.")
848853
return 0
849854
return 1
850855

@@ -870,7 +875,7 @@ def socket_disconnect(self, socket_num: int) -> None:
870875
self._write_sncr(socket_num, CMD_SOCK_DISCON)
871876
self._read_sncr(socket_num)
872877

873-
def socket_read(
878+
def socket_read( # pylint: disable=too-many-branches
874879
self, socket_num: int, length: int
875880
) -> Tuple[int, Union[int, bytearray]]:
876881
"""
@@ -884,8 +889,11 @@ def socket_read(
884889
was unsuccessful then both items equal an error code, 0 for no data waiting and -1
885890
for no connection to the socket.
886891
"""
887-
assert self.link_status, "Ethernet cable disconnected!"
888-
assert socket_num <= self.max_sockets, "Provided socket exceeds max_sockets."
892+
893+
if not self.link_status:
894+
raise ConnectionError("Ethernet cable disconnected!")
895+
if socket_num > self.max_sockets:
896+
raise ValueError("Provided socket exceeds max_sockets.")
889897

890898
# Check if there is data available on the socket
891899
ret = self._get_rx_rcv_size(socket_num)
@@ -978,7 +986,8 @@ def socket_write(
978986
979987
:return int: The number of bytes written to the buffer.
980988
"""
981-
assert self.link_status, "Ethernet cable disconnected!"
989+
if not self.link_status:
990+
raise ConnectionError("Ethernet cable disconnected!")
982991
assert socket_num <= self.max_sockets, "Provided socket exceeds max_sockets."
983992
if len(buffer) > SOCK_SIZE:
984993
ret = SOCK_SIZE

adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py

Lines changed: 82 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@
6565
DHCP_HLENETHERNET = const(0x06)
6666
DHCP_HOPS = const(0x00)
6767

68-
MAGIC_COOKIE = const(0x63825363)
68+
MAGIC_COOKIE = b"c\x82Sc" # Four bytes 99.130.83.99
6969
MAX_DHCP_OPT = const(0x10)
7070

7171
# Default DHCP Server port
@@ -179,7 +179,7 @@ def send_dhcp_message(
179179
# Transaction ID (xid)
180180
self._initial_xid = htonl(self._transaction_id)
181181
self._initial_xid = self._initial_xid.to_bytes(4, "big")
182-
_BUFF[4:7] = self._initial_xid
182+
_BUFF[4:8] = self._initial_xid
183183

184184
# seconds elapsed
185185
_BUFF[8] = (int(time_elapsed) & 0xFF00) >> 8
@@ -195,18 +195,15 @@ def send_dhcp_message(
195195
# as they're already set to 0.0.0.0
196196
# Except when renewing, then fill in ciaddr
197197
if renew:
198-
_BUFF[12:15] = bytes(self.local_ip)
198+
_BUFF[12:16] = bytes(self.local_ip)
199199

200200
# chaddr
201201
_BUFF[28:34] = self._mac_address
202202

203203
# NOTE: 192 octets of 0's, BOOTP legacy
204204

205205
# Magic Cookie
206-
_BUFF[236] = (MAGIC_COOKIE >> 24) & 0xFF
207-
_BUFF[237] = (MAGIC_COOKIE >> 16) & 0xFF
208-
_BUFF[238] = (MAGIC_COOKIE >> 8) & 0xFF
209-
_BUFF[239] = MAGIC_COOKIE & 0xFF
206+
_BUFF[236:240] = MAGIC_COOKIE
210207

211208
# Option - DHCP Message Type
212209
_BUFF[240] = 53
@@ -262,10 +259,10 @@ def send_dhcp_message(
262259
# pylint: disable=too-many-branches, too-many-statements
263260
def parse_dhcp_response(
264261
self,
265-
) -> Union[Tuple[int, bytes], Tuple[int, int]]:
262+
) -> Tuple[int, bytearray]:
266263
"""Parse DHCP response from DHCP server.
267264
268-
:return Union[Tuple[int, bytes], Tuple[int, int]]: DHCP packet type.
265+
:return Tuple[int, bytearray]: DHCP packet type and ID.
269266
"""
270267
global _BUFF # pylint: disable=global-statement
271268
# store packet in buffer
@@ -275,22 +272,23 @@ def parse_dhcp_response(
275272

276273
# -- Parse Packet, FIXED -- #
277274
# Validate OP
278-
assert (
279-
_BUFF[0] == DHCP_BOOT_REPLY
280-
), "Malformed Packet - \
275+
if _BUFF[0] != DHCP_BOOT_REPLY:
276+
raise RuntimeError(
277+
"Malformed Packet - \
281278
DHCP message OP is not expected BOOT Reply."
279+
)
282280

283281
xid = _BUFF[4:8]
284-
if bytes(xid) < self._initial_xid:
285-
print("f")
286-
return 0, 0
282+
if bytes(xid) != self._initial_xid:
283+
raise ValueError("DHCP response ID mismatch.")
287284

288285
self.local_ip = tuple(_BUFF[16:20])
289-
if _BUFF[28:34] == 0:
290-
return 0, 0
286+
# Check that there is a server ID.
287+
if _BUFF[28:34] == b"\x00\x00\x00\x00\x00\x00":
288+
raise ValueError("No DHCP server ID in the response.")
291289

292-
if int.from_bytes(_BUFF[235:240], "big") != MAGIC_COOKIE:
293-
return 0, 0
290+
if _BUFF[236:240] != MAGIC_COOKIE:
291+
raise ValueError("No DHCP Magic Cookie in the response.")
294292

295293
# -- Parse Packet, VARIABLE -- #
296294
ptr = 240
@@ -323,8 +321,8 @@ def parse_dhcp_response(
323321
ptr += 1
324322
opt_len = _BUFF[ptr]
325323
ptr += 1
326-
self.gateway_ip = tuple(_BUFF[ptr : ptr + opt_len])
327-
ptr += opt_len
324+
self.gateway_ip = tuple(_BUFF[ptr : ptr + 4])
325+
ptr += opt_len # still increment even though we only read 1 addr.
328326
elif _BUFF[ptr] == DNS_SERVERS:
329327
ptr += 1
330328
opt_len = _BUFF[ptr]
@@ -429,65 +427,79 @@ def _dhcp_state_machine(self) -> None:
429427
if self._sock._available(): # pylint: disable=protected-access
430428
if self._debug:
431429
print("* DHCP: Parsing OFFER")
432-
msg_type, xid = self.parse_dhcp_response()
433-
if msg_type == DHCP_OFFER:
434-
# Check if transaction ID matches, otherwise it may be an offer
435-
# for another device
436-
if htonl(self._transaction_id) == int.from_bytes(xid, "big"):
437-
if self._debug:
438-
print(
439-
"* DHCP: Send request to {}".format(self.dhcp_server_ip)
430+
try:
431+
msg_type, xid = self.parse_dhcp_response()
432+
except ValueError as error:
433+
if self._debug:
434+
print(error)
435+
else:
436+
if msg_type == DHCP_OFFER:
437+
# Check if transaction ID matches, otherwise it may be an offer
438+
# for another device
439+
if htonl(self._transaction_id) == int.from_bytes(xid, "big"):
440+
if self._debug:
441+
print(
442+
"* DHCP: Send request to {}".format(
443+
self.dhcp_server_ip
444+
)
445+
)
446+
self._transaction_id = (
447+
self._transaction_id + 1
448+
) & 0x7FFFFFFF
449+
self.send_dhcp_message(
450+
DHCP_REQUEST, (time.monotonic() - self._start_time)
440451
)
441-
self._transaction_id = (self._transaction_id + 1) & 0x7FFFFFFF
442-
self.send_dhcp_message(
443-
DHCP_REQUEST, (time.monotonic() - self._start_time)
444-
)
445-
self._dhcp_state = STATE_DHCP_REQUEST
452+
self._dhcp_state = STATE_DHCP_REQUEST
453+
else:
454+
if self._debug:
455+
print("* DHCP: Received OFFER with non-matching xid")
446456
else:
447457
if self._debug:
448-
print("* DHCP: Received OFFER with non-matching xid")
449-
else:
450-
if self._debug:
451-
print("* DHCP: Received DHCP Message is not OFFER")
458+
print("* DHCP: Received DHCP Message is not OFFER")
452459

453460
elif self._dhcp_state == STATE_DHCP_REQUEST:
454461
if self._sock._available(): # pylint: disable=protected-access
455462
if self._debug:
456463
print("* DHCP: Parsing ACK")
457-
msg_type, xid = self.parse_dhcp_response()
458-
# Check if transaction ID matches, otherwise it may be
459-
# for another device
460-
if htonl(self._transaction_id) == int.from_bytes(xid, "big"):
461-
if msg_type == DHCP_ACK:
462-
if self._debug:
463-
print("* DHCP: Successful lease")
464-
self._sock.close()
465-
self._sock = None
466-
self._dhcp_state = STATE_DHCP_LEASED
467-
self._last_lease_time = self._start_time
468-
if self._lease_time == 0:
469-
self._lease_time = DEFAULT_LEASE_TIME
470-
if self._t1 == 0:
471-
# T1 is 50% of _lease_time
472-
self._t1 = self._lease_time >> 1
473-
if self._t2 == 0:
474-
# T2 is 87.5% of _lease_time
475-
self._t2 = self._lease_time - (self._lease_time >> 3)
476-
self._renew_in_sec = self._t1
477-
self._rebind_in_sec = self._t2
478-
self._eth.ifconfig = (
479-
self.local_ip,
480-
self.subnet_mask,
481-
self.gateway_ip,
482-
self.dns_server_ip,
483-
)
484-
gc.collect()
464+
try:
465+
msg_type, xid = self.parse_dhcp_response()
466+
except ValueError as error:
467+
if self._debug:
468+
print(error)
469+
else:
470+
# Check if transaction ID matches, otherwise it may be
471+
# for another device
472+
if htonl(self._transaction_id) == int.from_bytes(xid, "big"):
473+
if msg_type == DHCP_ACK:
474+
if self._debug:
475+
print("* DHCP: Successful lease")
476+
self._sock.close()
477+
self._sock = None
478+
self._dhcp_state = STATE_DHCP_LEASED
479+
self._last_lease_time = self._start_time
480+
if self._lease_time == 0:
481+
self._lease_time = DEFAULT_LEASE_TIME
482+
if self._t1 == 0:
483+
# T1 is 50% of _lease_time
484+
self._t1 = self._lease_time >> 1
485+
if self._t2 == 0:
486+
# T2 is 87.5% of _lease_time
487+
self._t2 = self._lease_time - (self._lease_time >> 3)
488+
self._renew_in_sec = self._t1
489+
self._rebind_in_sec = self._t2
490+
self._eth.ifconfig = (
491+
self.local_ip,
492+
self.subnet_mask,
493+
self.gateway_ip,
494+
self.dns_server_ip,
495+
)
496+
gc.collect()
497+
else:
498+
if self._debug:
499+
print("* DHCP: Received DHCP Message is not ACK")
485500
else:
486501
if self._debug:
487-
print("* DHCP: Received DHCP Message is not ACK")
488-
else:
489-
if self._debug:
490-
print("* DHCP: Received non-matching xid")
502+
print("* DHCP: Received non-matching xid")
491503

492504
elif self._dhcp_state == STATE_DHCP_WAIT:
493505
if time.monotonic() > (self._start_time + DHCP_WAIT_TIME):

adafruit_wiznet5k/adafruit_wiznet5k_socket.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,6 @@ def inet_ntoa(ip_address: Union[bytes, bytearray]) -> str:
146146

147147

148148
# pylint: disable=too-many-arguments, unused-argument
149-
150-
151149
def getaddrinfo(
152150
host: str,
153151
port: int,
@@ -334,7 +332,8 @@ def listen(self, backlog: int = 0) -> None:
334332
335333
:param int backlog: Included for compatibility but ignored.
336334
"""
337-
assert self._listen_port is not None, "Use bind to set the port before listen!"
335+
if self._listen_port is None:
336+
raise RuntimeError("Use bind to set the port before listen!")
338337
_the_interface.socket_listen(self._socknum, self._listen_port)
339338
self._buffer = b""
340339

@@ -576,7 +575,8 @@ def _readline(self) -> bytes:
576575

577576
def _disconnect(self) -> None:
578577
"""Disconnect a TCP socket."""
579-
assert self._sock_type == SOCK_STREAM, "Socket must be a TCP socket."
578+
if self._sock_type != SOCK_STREAM:
579+
raise RuntimeError("Socket must be a TCP socket.")
580580
_the_interface.socket_disconnect(self._socknum)
581581

582582
def close(self) -> None:

optional_requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries
22
#
33
# SPDX-License-Identifier: Unlicense
4+
pytest

0 commit comments

Comments
 (0)