41
41
42
42
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
43
43
"""
44
-
44
+ from random import randint
45
45
import time
46
46
from micropython import const
47
47
138
138
'remote_ip' : 0 ,
139
139
'remote_port' : 0 }
140
140
141
- class WIZNET5K :
141
+ class WIZNET5K : # pylint: disable=too-many-public-methods
142
142
"""Interface for WIZNET5K module.
143
143
:param ~busio.SPI spi_bus: The SPI bus the Wiznet module is connected to.
144
144
:param ~digitalio.DigitalInOut cs: Chip select pin.
@@ -149,7 +149,11 @@ class WIZNET5K:
149
149
150
150
"""
151
151
152
- # pylint: disable=too-many-arguments, too-many-public-methods
152
+ TCP_MODE = const (0x21 )
153
+ UDP_MODE = const (0x02 )
154
+ TLS_MODE = const (0x03 ) # This is NOT currently implemented
155
+
156
+ # pylint: disable=too-many-arguments
153
157
def __init__ (self , spi_bus , cs , reset = None ,
154
158
is_dhcp = True , mac = DEFAULT_MAC , debug = False ):
155
159
self ._debug = debug
@@ -180,7 +184,8 @@ def __init__(self, spi_bus, cs, reset=None,
180
184
self ._dns = 0
181
185
# Set DHCP
182
186
if is_dhcp :
183
- self .set_dhcp ()
187
+ ret = self .set_dhcp ()
188
+ assert ret == 0 , "Failed to configure DHCP Server!"
184
189
185
190
def set_dhcp (self , response_timeout = 1 ):
186
191
"""Initializes the DHCP client and attempts to retrieve
@@ -193,11 +198,9 @@ def set_dhcp(self, response_timeout=1):
193
198
print ("* Initializing DHCP" )
194
199
self ._src_port = 68
195
200
# Return IP assigned by DHCP
196
- _dhcp_client = dhcp .DHCP (self , self .mac_address , response_timeout )
201
+ _dhcp_client = dhcp .DHCP (self , self .mac_address , response_timeout , debug = self . _debug )
197
202
ret = _dhcp_client .request_dhcp_lease ()
198
203
if ret == 1 :
199
- if self ._debug :
200
- print ("* Found DHCP server - setting configuration..." )
201
204
_ip = (_dhcp_client .local_ip [0 ], _dhcp_client .local_ip [1 ],
202
205
_dhcp_client .local_ip [2 ], _dhcp_client .local_ip [3 ])
203
206
@@ -210,9 +213,15 @@ def set_dhcp(self, response_timeout=1):
210
213
self ._dns = (_dhcp_client .dns_server_ip [0 ], _dhcp_client .dns_server_ip [1 ],
211
214
_dhcp_client .dns_server_ip [2 ], _dhcp_client .dns_server_ip [3 ])
212
215
self .ifconfig = ((_ip , _subnet_mask , _gw_addr , self ._dns ))
216
+ if self ._debug :
217
+ print ("* Found DHCP Server:" )
218
+ print ("IP: {}\n Subnet Mask: {}\n GW Addr: {}\n DNS Server: {}" .format (_ip ,
219
+ _subnet_mask ,
220
+ _gw_addr ,
221
+ self ._dns ))
222
+ self ._src_port = 0
213
223
return 0
214
- self ._src_port = 0
215
- return 1
224
+ return - 1
216
225
217
226
def get_host_by_name (self , hostname ):
218
227
"""Convert a hostname to a packed 4-byte IP Address.
@@ -224,8 +233,11 @@ def get_host_by_name(self, hostname):
224
233
hostname = bytes (hostname , 'utf-8' )
225
234
self ._src_port = int (time .monotonic ())
226
235
# Return IP assigned by DHCP
227
- _dns_client = dns .DNS (self , self ._dns )
236
+ _dns_client = dns .DNS (self , self ._dns , debug = self . _debug )
228
237
ret = _dns_client .gethostbyname (hostname )
238
+ if self ._debug :
239
+ print ("* Resolved IP: " , ret )
240
+ assert ret != - 1 , "Failed to resolve hostname!"
229
241
self ._src_port = 0
230
242
return ret
231
243
@@ -303,15 +315,8 @@ def remote_port(self):
303
315
@property
304
316
def ifconfig (self ):
305
317
"""Returns the network configuration as a tuple."""
306
- # set subnet and gateway addresses
307
- self ._pbuff = bytearray (8 )
308
- for octet in range (0 , 4 ):
309
- self ._pbuff += self .read (REG_SUBR + octet , 0x04 )
310
- for octet in range (0 , 4 ):
311
- self ._pbuff += self .read (REG_GAR + octet , 0x04 )
312
-
313
- params = (self .ip_address , self ._pbuff [0 :3 ], self ._pbuff [3 :7 ], self ._dns )
314
- return params
318
+ return (self .ip_address , self .read (REG_SUBR , 0x00 , 4 ),
319
+ self .read (REG_GAR , 0x00 , 4 ), self ._dns )
315
320
316
321
@ifconfig .setter
317
322
def ifconfig (self , params ):
@@ -321,14 +326,10 @@ def ifconfig(self, params):
321
326
"""
322
327
ip_address , subnet_mask , gateway_address , dns_server = params
323
328
324
- # Set IP Address
325
329
self .write (REG_SIPR , 0x04 , ip_address )
330
+ self .write (REG_SUBR , 0x04 , subnet_mask )
331
+ self .write (REG_GAR , 0x04 , gateway_address )
326
332
327
- # set subnet and gateway addresses
328
- for octet in range (0 , 4 ):
329
- self .write (REG_SUBR + octet , 0x04 , subnet_mask [octet ])
330
- self .write (REG_GAR + octet , 0x04 , gateway_address [octet ])
331
- # set dns server address
332
333
self ._dns = dns_server
333
334
334
335
def _w5100_init (self ):
@@ -492,26 +493,36 @@ def socket_connect(self, socket_num, dest, port, conn_mode=SNMR_TCP):
492
493
"""
493
494
assert self .link_status , "Ethernet cable disconnected!"
494
495
if self ._debug :
495
- print ("*** Connecting: Socket# {}, conn_mode: {}" .format (socket_num , conn_mode ))
496
-
496
+ print ("* w5k socket connect, protocol= {}, port={}, ip= {}" .format (conn_mode , port ,
497
+ self . pretty_ip ( dest )))
497
498
# initialize a socket and set the mode
498
- res = self .socket_open (socket_num , dest , port , conn_mode = conn_mode )
499
+ res = self .socket_open (socket_num , conn_mode = conn_mode )
499
500
if res == 1 :
500
501
raise RuntimeError ('Failed to initalize a connection with the socket.' )
501
502
503
+ # set socket destination IP and port
504
+ self ._write_sndipr (socket_num , dest )
505
+ self ._write_sndport (socket_num , port )
506
+ self ._send_socket_cmd (socket_num , CMD_SOCK_CONNECT )
507
+
502
508
if conn_mode == SNMR_TCP :
503
- # TCP client - connect socket
504
- self ._write_sncr (socket_num , CMD_SOCK_CONNECT )
505
- self ._read_sncr (socket_num )
506
509
# wait for tcp connection establishment
507
510
while self .socket_status (socket_num )[0 ] != SNSR_SOCK_ESTABLISHED :
511
+ time .sleep (0.001 )
512
+ if self ._debug :
513
+ print ("SN_SR:" , self .socket_status (socket_num )[0 ])
508
514
if self .socket_status (socket_num )[0 ] == SNSR_SOCK_CLOSED :
509
515
raise RuntimeError ('Failed to establish connection.' )
510
- time .sleep (1 )
511
516
elif conn_mode == SNMR_UDP :
512
517
UDP_SOCK ['bytes_remaining' ] = 0
513
518
return 1
514
519
520
+ def _send_socket_cmd (self , socket , cmd ):
521
+ self ._write_sncr (socket , cmd )
522
+ while self ._read_sncr (socket ) != b'\x00 ' :
523
+ if self ._debug :
524
+ print ("waiting for sncr to clear..." )
525
+
515
526
def get_socket (self , sockets ):
516
527
"""Requests, allocates and returns a socket from the W5k
517
528
chip. Returned socket number may not exceed max_sockets.
@@ -528,23 +539,20 @@ def get_socket(self, sockets):
528
539
sock = _sock
529
540
break
530
541
531
- if self ._src_port == 0 :
532
- self ._src_port = 1024
533
-
534
542
if self ._debug :
535
- print ("Allocated socket #{}:{} " .format (sock , self . _src_port ))
543
+ print ("Allocated socket #{}" .format (sock ))
536
544
return sock
537
545
538
- def socket_open (self , socket_num , dest , port , conn_mode = SNMR_TCP ):
539
- """Opens a socket to a destination IP address or hostname . By default, we use
546
+ def socket_open (self , socket_num , conn_mode = SNMR_TCP ):
547
+ """Opens a TCP or UDP socket . By default, we use
540
548
'conn_mode'=SNMR_TCP but we may also use SNMR_UDP.
541
549
"""
542
550
assert self .link_status , "Ethernet cable disconnected!"
543
551
if self ._debug :
544
552
print ("*** Opening socket %d" % socket_num )
545
553
if self ._read_snsr (socket_num )[0 ] == SNSR_SOCK_CLOSED :
546
554
if self ._debug :
547
- print ("w5k socket begin , protocol={}, port={} " .format (conn_mode , port ))
555
+ print ("* Opening W5k Socket , protocol={}" .format (conn_mode ))
548
556
time .sleep (0.00025 )
549
557
550
558
self ._write_snmr (socket_num , conn_mode )
@@ -554,12 +562,7 @@ def socket_open(self, socket_num, dest, port, conn_mode=SNMR_TCP):
554
562
# write to socket source port
555
563
self ._write_sock_port (socket_num , self ._src_port )
556
564
else :
557
- # if source port is not set, set the local port number
558
- self ._write_sock_port (socket_num , LOCAL_PORT )
559
-
560
- # set socket destination IP and port
561
- self ._write_sndipr (socket_num , dest )
562
- self ._write_sndport (socket_num , port )
565
+ self ._write_sock_port (socket_num , randint (49152 , 65535 ))
563
566
564
567
# open socket
565
568
self ._write_sncr (socket_num , CMD_SOCK_OPEN )
0 commit comments