Skip to content

Commit 9dedc5c

Browse files
author
Bongjun Hur
committed
2 parents baca531 + 5dc4aeb commit 9dedc5c

File tree

7 files changed

+384
-163
lines changed

7 files changed

+384
-163
lines changed

README.rst

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -126,29 +126,28 @@ This example demonstrates a simple web server that allows setting the Neopixel c
126126
cs = digitalio.DigitalInOut(board.D10)
127127
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
128128
129-
# Initialize ethernet interface with DHCP and the MAC we have from the 24AA02E48
129+
# Initialize Ethernet interface with DHCP
130130
eth = WIZNET5K(spi_bus, cs)
131131
132132
# Here we create our application, registering the
133133
# following functions to be called on specific HTTP GET requests routes
134134
135135
web_app = WSGIApp()
136136
137-
138137
@web_app.route("/led/<r>/<g>/<b>")
139138
def led_on(request, r, g, b):
140-
print("led handler")
139+
print("LED handler")
141140
led.fill((int(r), int(g), int(b)))
142-
return ("200 OK", [], ["led set!"])
141+
return ("200 OK", [], ["LED set!"])
143142
144143
@web_app.route("/")
145144
def root(request):
146-
print("root handler")
147-
return ("200 OK", [], ["root document"])
145+
print("Root handler")
146+
return ("200 OK", [], ["Root document"])
148147
149148
@web_app.route("/large")
150149
def large(request):
151-
print("large handler")
150+
print("Large pattern handler")
152151
return ("200 OK", [], ["*-.-" * 2000])
153152
154153
@@ -163,6 +162,8 @@ This example demonstrates a simple web server that allows setting the Neopixel c
163162
while True:
164163
# Our main loop where we have the server poll for incoming requests
165164
wsgiServer.update_poll()
165+
# Maintain DHCP lease
166+
eth.maintain_dhcp_lease()
166167
# Could do any other background tasks here, like reading sensors
167168
168169
Contributing

adafruit_wiznet5k/adafruit_wiznet5k.py

Lines changed: 34 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,9 @@
121121
# UDP socket struct.
122122
UDP_SOCK = {"bytes_remaining": 0, "remote_ip": 0, "remote_port": 0}
123123

124+
# Source ports in use
125+
SRC_PORTS = [0] * W5200_W5500_MAX_SOCK_NUM
126+
124127

125128
class WIZNET5K: # pylint: disable=too-many-public-methods
126129
"""Interface for WIZNET5K module.
@@ -173,18 +176,21 @@ def __init__(
173176
assert self._w5100_init() == 1, "Failed to initialize WIZnet module."
174177
# Set MAC address
175178
self.mac_address = mac
176-
self._src_port = 0
179+
self.src_port = 0
177180
self._dns = 0
178181

179182
# Set DHCP
183+
self._dhcp_client = None
180184
if is_dhcp:
181185
ret = self.set_dhcp(hostname, dhcp_timeout)
186+
if ret != 0:
187+
self._dhcp_client = None
182188
assert ret == 0, "Failed to configure DHCP Server!"
183189

184-
def set_dhcp(self, hostname=None, response_timeout=3):
190+
def set_dhcp(self, hostname=None, response_timeout=30):
185191
"""Initializes the DHCP client and attempts to retrieve
186192
and set network configuration from the DHCP server.
187-
Returns True if DHCP configured, False otherwise.
193+
Returns 0 if DHCP configured, -1 otherwise.
188194
:param str hostname: The desired hostname, with optional {} to fill in MAC.
189195
:param int response_timeout: Time to wait for server to return packet, in seconds.
190196
@@ -202,52 +208,28 @@ def set_dhcp(self, hostname=None, response_timeout=3):
202208
if self._debug:
203209
print("My Link is:", self.link_status)
204210

205-
self._src_port = 68
206211
# Return IP assigned by DHCP
207-
_dhcp_client = dhcp.DHCP(
212+
self._dhcp_client = dhcp.DHCP(
208213
self, self.mac_address, hostname, response_timeout, debug=self._debug
209214
)
210-
ret = _dhcp_client.request_dhcp_lease()
215+
ret = self._dhcp_client.request_dhcp_lease()
211216
if ret == 1:
212-
_ip = (
213-
_dhcp_client.local_ip[0],
214-
_dhcp_client.local_ip[1],
215-
_dhcp_client.local_ip[2],
216-
_dhcp_client.local_ip[3],
217-
)
218-
219-
_subnet_mask = (
220-
_dhcp_client.subnet_mask[0],
221-
_dhcp_client.subnet_mask[1],
222-
_dhcp_client.subnet_mask[2],
223-
_dhcp_client.subnet_mask[3],
224-
)
225-
226-
_gw_addr = (
227-
_dhcp_client.gateway_ip[0],
228-
_dhcp_client.gateway_ip[1],
229-
_dhcp_client.gateway_ip[2],
230-
_dhcp_client.gateway_ip[3],
231-
)
232-
233-
self._dns = (
234-
_dhcp_client.dns_server_ip[0],
235-
_dhcp_client.dns_server_ip[1],
236-
_dhcp_client.dns_server_ip[2],
237-
_dhcp_client.dns_server_ip[3],
238-
)
239-
self.ifconfig = (_ip, _subnet_mask, _gw_addr, self._dns)
240217
if self._debug:
218+
_ifconfig = self.ifconfig
241219
print("* Found DHCP Server:")
242220
print(
243221
"IP: {}\nSubnet Mask: {}\nGW Addr: {}\nDNS Server: {}".format(
244-
_ip, _subnet_mask, _gw_addr, self._dns
222+
*_ifconfig
245223
)
246224
)
247-
self._src_port = 0
248225
return 0
249226
return -1
250227

228+
def maintain_dhcp_lease(self):
229+
"""Maintain DHCP lease"""
230+
if self._dhcp_client is not None:
231+
self._dhcp_client.maintain_dhcp_lease()
232+
251233
def get_host_by_name(self, hostname):
252234
"""Convert a hostname to a packed 4-byte IP Address.
253235
Returns a 4 bytearray.
@@ -256,14 +238,12 @@ def get_host_by_name(self, hostname):
256238
print("* Get host by name")
257239
if isinstance(hostname, str):
258240
hostname = bytes(hostname, "utf-8")
259-
self._src_port = int(time.monotonic()) & 0xFFFF
260241
# Return IP assigned by DHCP
261242
_dns_client = dns.DNS(self, self._dns, debug=self._debug)
262243
ret = _dns_client.gethostbyname(hostname)
263244
if self._debug:
264245
print("* Resolved IP: ", ret)
265246
assert ret != -1, "Failed to resolve hostname!"
266-
self._src_port = 0
267247
return ret
268248

269249
@property
@@ -481,7 +461,11 @@ def socket_available(self, socket_num, sock_type=SNMR_TCP):
481461
:param int sock_type: Socket type, defaults to TCP.
482462
"""
483463
if self._debug:
484-
print("* socket_available called with protocol", sock_type)
464+
print(
465+
"* socket_available called on socket {}, protocol {}".format(
466+
socket_num, sock_type
467+
)
468+
)
485469
assert socket_num <= self.max_sockets, "Provided socket exceeds max_sockets."
486470

487471
res = self._get_rx_rcv_size(socket_num)
@@ -561,13 +545,7 @@ def get_socket(self):
561545
sock = SOCKET_INVALID
562546
for _sock in range(self.max_sockets):
563547
status = self.socket_status(_sock)[0]
564-
if status in (
565-
SNSR_SOCK_CLOSED,
566-
SNSR_SOCK_TIME_WAIT,
567-
SNSR_SOCK_FIN_WAIT,
568-
SNSR_SOCK_CLOSE_WAIT,
569-
SNSR_SOCK_CLOSING,
570-
):
548+
if status == SNSR_SOCK_CLOSED:
571549
sock = _sock
572550
break
573551

@@ -588,15 +566,16 @@ def socket_listen(self, socket_num, port):
588566
)
589567
)
590568
# Initialize a socket and set the mode
591-
self._src_port = port
569+
self.src_port = port
592570
res = self.socket_open(socket_num, conn_mode=SNMR_TCP)
571+
self.src_port = 0
593572
if res == 1:
594573
raise RuntimeError("Failed to initalize the socket.")
595574
# Send listen command
596575
self._send_socket_cmd(socket_num, CMD_SOCK_LISTEN)
597576
# Wait until ready
598577
status = [SNSR_SOCK_CLOSED]
599-
while status[0] != SNSR_SOCK_LISTEN:
578+
while status[0] not in (SNSR_SOCK_LISTEN, SNSR_SOCK_ESTABLISHED):
600579
status = self._read_snsr(socket_num)
601580
if status[0] == SNSR_SOCK_CLOSED:
602581
raise RuntimeError("Listening socket closed.")
@@ -639,11 +618,15 @@ def socket_open(self, socket_num, conn_mode=SNMR_TCP):
639618
self._write_snmr(socket_num, conn_mode)
640619
self._write_snir(socket_num, 0xFF)
641620

642-
if self._src_port > 0:
621+
if self.src_port > 0:
643622
# write to socket source port
644-
self._write_sock_port(socket_num, self._src_port)
623+
self._write_sock_port(socket_num, self.src_port)
645624
else:
646-
self._write_sock_port(socket_num, randint(49152, 65535))
625+
s_port = randint(49152, 65535)
626+
while s_port in SRC_PORTS:
627+
s_port = randint(49152, 65535)
628+
self._write_sock_port(socket_num, s_port)
629+
SRC_PORTS[socket_num] = s_port
647630

648631
# open socket
649632
self._write_sncr(socket_num, CMD_SOCK_OPEN)

0 commit comments

Comments
 (0)