Skip to content

Commit 5cd1e5b

Browse files
authored
Merge pull request #7 from brentru/update-for-requests
Add Adafruit_CircuitPython_Requests Compatibility
2 parents 1b289b3 + f510eb2 commit 5cd1e5b

8 files changed

+425
-181
lines changed

README.rst

Lines changed: 35 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -57,45 +57,50 @@ wifitest.adafruit.com.
5757

5858
.. code-block:: python
5959
60-
import time
61-
6260
import board
6361
import busio
6462
import digitalio
65-
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET
63+
import adafruit_requests as requests
64+
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
6665
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
6766
67+
print("Wiznet5k WebClient Test")
68+
69+
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
70+
JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json"
71+
6872
cs = digitalio.DigitalInOut(board.D10)
6973
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
7074
7175
# Initialize ethernet interface with DHCP
72-
eth = WIZNET5K(spi_bus, cs, debug=True)
73-
74-
print("DHCP Assigned IP: ", eth.pretty_ip(eth.ip_address))
75-
76-
socket.set_interface(eth)
77-
78-
host = 'wifitest.adafruit.com'
79-
port = 80
80-
81-
addr_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
82-
sock = socket.socket(addr_info[0], addr_info[1], addr_info[2])
83-
84-
print("Connected to ", sock.getpeername())
85-
86-
# Make a HTTP Request
87-
sock.send(b"GET /testwifi/index.html HTTP/1.1\n")
88-
sock.send(b"Host: 104.236.193.178\n")
89-
sock.send(b"Connection: close\n\n")
90-
91-
bytes_avail = 0
92-
while not bytes_avail:
93-
bytes_avail = sock.available()
94-
if bytes_avail > 0:
95-
data = sock.recv(bytes_avail)
96-
print(data)
97-
break
98-
time.sleep(0.05)
76+
eth = WIZNET5K(spi_bus, cs)
77+
78+
# Initialize a requests object with a socket and ethernet interface
79+
requests.set_socket(socket, eth)
80+
81+
print("Chip Version:", eth.chip)
82+
print("MAC Address:", [hex(i) for i in eth.mac_address])
83+
print("My IP address is:", eth.pretty_ip(eth.ip_address))
84+
print("IP lookup adafruit.com: %s" %eth.pretty_ip(eth.get_host_by_name("adafruit.com")))
85+
86+
87+
#eth._debug = True
88+
print("Fetching text from", TEXT_URL)
89+
r = requests.get(TEXT_URL)
90+
print('-'*40)
91+
print(r.text)
92+
print('-'*40)
93+
r.close()
94+
95+
print()
96+
print("Fetching json from", JSON_URL)
97+
r = requests.get(JSON_URL)
98+
print('-'*40)
99+
print(r.json())
100+
print('-'*40)
101+
r.close()
102+
103+
print("Done!")
99104
100105
Contributing
101106
============

adafruit_wiznet5k/adafruit_wiznet5k.py

Lines changed: 48 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
4242
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
4343
"""
44-
44+
from random import randint
4545
import time
4646
from micropython import const
4747

@@ -138,7 +138,7 @@
138138
'remote_ip': 0,
139139
'remote_port': 0}
140140

141-
class WIZNET5K:
141+
class WIZNET5K: # pylint: disable=too-many-public-methods
142142
"""Interface for WIZNET5K module.
143143
:param ~busio.SPI spi_bus: The SPI bus the Wiznet module is connected to.
144144
:param ~digitalio.DigitalInOut cs: Chip select pin.
@@ -149,7 +149,11 @@ class WIZNET5K:
149149
150150
"""
151151

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
153157
def __init__(self, spi_bus, cs, reset=None,
154158
is_dhcp=True, mac=DEFAULT_MAC, debug=False):
155159
self._debug = debug
@@ -180,7 +184,8 @@ def __init__(self, spi_bus, cs, reset=None,
180184
self._dns = 0
181185
# Set DHCP
182186
if is_dhcp:
183-
self.set_dhcp()
187+
ret = self.set_dhcp()
188+
assert ret == 0, "Failed to configure DHCP Server!"
184189

185190
def set_dhcp(self, response_timeout=1):
186191
"""Initializes the DHCP client and attempts to retrieve
@@ -193,11 +198,9 @@ def set_dhcp(self, response_timeout=1):
193198
print("* Initializing DHCP")
194199
self._src_port = 68
195200
# 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)
197202
ret = _dhcp_client.request_dhcp_lease()
198203
if ret == 1:
199-
if self._debug:
200-
print("* Found DHCP server - setting configuration...")
201204
_ip = (_dhcp_client.local_ip[0], _dhcp_client.local_ip[1],
202205
_dhcp_client.local_ip[2], _dhcp_client.local_ip[3])
203206

@@ -210,9 +213,15 @@ def set_dhcp(self, response_timeout=1):
210213
self._dns = (_dhcp_client.dns_server_ip[0], _dhcp_client.dns_server_ip[1],
211214
_dhcp_client.dns_server_ip[2], _dhcp_client.dns_server_ip[3])
212215
self.ifconfig = ((_ip, _subnet_mask, _gw_addr, self._dns))
216+
if self._debug:
217+
print("* Found DHCP Server:")
218+
print("IP: {}\nSubnet Mask: {}\nGW Addr: {}\nDNS Server: {}".format(_ip,
219+
_subnet_mask,
220+
_gw_addr,
221+
self._dns))
222+
self._src_port = 0
213223
return 0
214-
self._src_port = 0
215-
return 1
224+
return -1
216225

217226
def get_host_by_name(self, hostname):
218227
"""Convert a hostname to a packed 4-byte IP Address.
@@ -224,8 +233,11 @@ def get_host_by_name(self, hostname):
224233
hostname = bytes(hostname, 'utf-8')
225234
self._src_port = int(time.monotonic())
226235
# Return IP assigned by DHCP
227-
_dns_client = dns.DNS(self, self._dns)
236+
_dns_client = dns.DNS(self, self._dns, debug=self._debug)
228237
ret = _dns_client.gethostbyname(hostname)
238+
if self._debug:
239+
print("* Resolved IP: ", ret)
240+
assert ret != -1, "Failed to resolve hostname!"
229241
self._src_port = 0
230242
return ret
231243

@@ -303,15 +315,8 @@ def remote_port(self):
303315
@property
304316
def ifconfig(self):
305317
"""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)
315320

316321
@ifconfig.setter
317322
def ifconfig(self, params):
@@ -321,14 +326,10 @@ def ifconfig(self, params):
321326
"""
322327
ip_address, subnet_mask, gateway_address, dns_server = params
323328

324-
# Set IP Address
325329
self.write(REG_SIPR, 0x04, ip_address)
330+
self.write(REG_SUBR, 0x04, subnet_mask)
331+
self.write(REG_GAR, 0x04, gateway_address)
326332

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
332333
self._dns = dns_server
333334

334335
def _w5100_init(self):
@@ -492,26 +493,36 @@ def socket_connect(self, socket_num, dest, port, conn_mode=SNMR_TCP):
492493
"""
493494
assert self.link_status, "Ethernet cable disconnected!"
494495
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)))
497498
# 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)
499500
if res == 1:
500501
raise RuntimeError('Failed to initalize a connection with the socket.')
501502

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+
502508
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)
506509
# wait for tcp connection establishment
507510
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])
508514
if self.socket_status(socket_num)[0] == SNSR_SOCK_CLOSED:
509515
raise RuntimeError('Failed to establish connection.')
510-
time.sleep(1)
511516
elif conn_mode == SNMR_UDP:
512517
UDP_SOCK['bytes_remaining'] = 0
513518
return 1
514519

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+
515526
def get_socket(self, sockets):
516527
"""Requests, allocates and returns a socket from the W5k
517528
chip. Returned socket number may not exceed max_sockets.
@@ -528,23 +539,20 @@ def get_socket(self, sockets):
528539
sock = _sock
529540
break
530541

531-
if self._src_port == 0:
532-
self._src_port = 1024
533-
534542
if self._debug:
535-
print("Allocated socket #{}:{}".format(sock, self._src_port))
543+
print("Allocated socket #{}".format(sock))
536544
return sock
537545

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
540548
'conn_mode'=SNMR_TCP but we may also use SNMR_UDP.
541549
"""
542550
assert self.link_status, "Ethernet cable disconnected!"
543551
if self._debug:
544552
print("*** Opening socket %d"%socket_num)
545553
if self._read_snsr(socket_num)[0] == SNSR_SOCK_CLOSED:
546554
if self._debug:
547-
print("w5k socket begin, protocol={}, port={}".format(conn_mode, port))
555+
print("* Opening W5k Socket, protocol={}".format(conn_mode))
548556
time.sleep(0.00025)
549557

550558
self._write_snmr(socket_num, conn_mode)
@@ -554,12 +562,7 @@ def socket_open(self, socket_num, dest, port, conn_mode=SNMR_TCP):
554562
# write to socket source port
555563
self._write_sock_port(socket_num, self._src_port)
556564
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))
563566

564567
# open socket
565568
self._write_sncr(socket_num, CMD_SOCK_OPEN)

0 commit comments

Comments
 (0)