From ed53c4d5be0b16409be8832fae7ea092c05f84d0 Mon Sep 17 00:00:00 2001 From: Kattni Rembor Date: Thu, 9 Apr 2020 16:08:29 -0400 Subject: [PATCH] Black reformatting with Python 3 target. --- adafruit_wiznet5k/adafruit_wiznet5k.py | 346 ++++++++++-------- adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py | 134 ++++--- adafruit_wiznet5k/adafruit_wiznet5k_dns.py | 64 ++-- adafruit_wiznet5k/adafruit_wiznet5k_socket.py | 95 +++-- docs/conf.py | 116 +++--- examples/adafruit_wiznet5k_cheerlights.py | 10 +- examples/wiznet5k_aio_post.py | 15 +- examples/wiznet5k_simpletest.py | 14 +- .../wiznet5k_simpletest_manual_network.py | 10 +- setup.py | 55 ++- 10 files changed, 481 insertions(+), 378 deletions(-) diff --git a/adafruit_wiznet5k/adafruit_wiznet5k.py b/adafruit_wiznet5k/adafruit_wiznet5k.py index 0d870a5..db71c7c 100755 --- a/adafruit_wiznet5k/adafruit_wiznet5k.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k.py @@ -56,73 +56,73 @@ # pylint: disable=bad-whitespace # Wiznet5k Registers -REG_MR = const(0x0000) # Mode -REG_GAR = const(0x0001) # Gateway IP Address -REG_SUBR = const(0x0005) # Subnet Mask Address -REG_VERSIONR_W5500 = const(0x0039) # W5500 Silicon Version -REG_SHAR = const(0x0009) # Source Hardware Address -REG_SIPR = const(0x000F) # Source IP Address -REG_PHYCFGR = const(0x002E) # W5500 PHY Configuration +REG_MR = const(0x0000) # Mode +REG_GAR = const(0x0001) # Gateway IP Address +REG_SUBR = const(0x0005) # Subnet Mask Address +REG_VERSIONR_W5500 = const(0x0039) # W5500 Silicon Version +REG_SHAR = const(0x0009) # Source Hardware Address +REG_SIPR = const(0x000F) # Source IP Address +REG_PHYCFGR = const(0x002E) # W5500 PHY Configuration # Wiznet5k Socket Registers -REG_SNMR = const(0x0000) # Socket n Mode -REG_SNCR = const(0x0001) # Socket n Command -REG_SNIR = const(0x0002) # Socket n Interrupt -REG_SNSR = const(0x0003) # Socket n Status -REG_SNPORT = const(0x0004) # Socket n Source Port -REG_SNDIPR = const(0x000C) # Destination IP Address -REG_SNDPORT = const(0x0010) # Destination Port -REG_SNRX_RSR = const(0x0026) # RX Free Size -REG_SNRX_RD = const(0x0028) # Read Size Pointer -REG_SNTX_FSR = const(0x0020) # Socket n TX Free Size -REG_SNTX_WR = const(0x0024) # TX Write Pointer +REG_SNMR = const(0x0000) # Socket n Mode +REG_SNCR = const(0x0001) # Socket n Command +REG_SNIR = const(0x0002) # Socket n Interrupt +REG_SNSR = const(0x0003) # Socket n Status +REG_SNPORT = const(0x0004) # Socket n Source Port +REG_SNDIPR = const(0x000C) # Destination IP Address +REG_SNDPORT = const(0x0010) # Destination Port +REG_SNRX_RSR = const(0x0026) # RX Free Size +REG_SNRX_RD = const(0x0028) # Read Size Pointer +REG_SNTX_FSR = const(0x0020) # Socket n TX Free Size +REG_SNTX_WR = const(0x0024) # TX Write Pointer # SNSR Commands -SNSR_SOCK_CLOSED = const(0x00) -SNSR_SOCK_INIT = const(0x13) -SNSR_SOCK_LISTEN = const(0x14) -SNSR_SOCK_SYNSENT = const(0x15) -SNSR_SOCK_SYNRECV = const(0x16) +SNSR_SOCK_CLOSED = const(0x00) +SNSR_SOCK_INIT = const(0x13) +SNSR_SOCK_LISTEN = const(0x14) +SNSR_SOCK_SYNSENT = const(0x15) +SNSR_SOCK_SYNRECV = const(0x16) SNSR_SOCK_ESTABLISHED = const(0x17) -SNSR_SOCK_FIN_WAIT = const(0x18) -SNSR_SOCK_CLOSING = const(0x1A) -SNSR_SOCK_TIME_WAIT = const(0x1B) -SNSR_SOCK_CLOSE_WAIT = const(0x1C) -SNSR_SOCK_LAST_ACK = const(0x1D) -SNSR_SOCK_UDP = const(0x22) -SNSR_SOCK_IPRAW = const(0x32) -SNSR_SOCK_MACRAW = const(0x42) -SNSR_SOCK_PPPOE = const(0x5F) +SNSR_SOCK_FIN_WAIT = const(0x18) +SNSR_SOCK_CLOSING = const(0x1A) +SNSR_SOCK_TIME_WAIT = const(0x1B) +SNSR_SOCK_CLOSE_WAIT = const(0x1C) +SNSR_SOCK_LAST_ACK = const(0x1D) +SNSR_SOCK_UDP = const(0x22) +SNSR_SOCK_IPRAW = const(0x32) +SNSR_SOCK_MACRAW = const(0x42) +SNSR_SOCK_PPPOE = const(0x5F) # Sock Commands (CMD) -CMD_SOCK_OPEN = const(0x01) -CMD_SOCK_LISTEN = const(0x02) -CMD_SOCK_CONNECT = const(0x04) -CMD_SOCK_DISCON = const(0x08) -CMD_SOCK_CLOSE = const(0x10) -CMD_SOCK_SEND = const(0x20) -CMD_SOCK_SEND_MAC = const(0x21) +CMD_SOCK_OPEN = const(0x01) +CMD_SOCK_LISTEN = const(0x02) +CMD_SOCK_CONNECT = const(0x04) +CMD_SOCK_DISCON = const(0x08) +CMD_SOCK_CLOSE = const(0x10) +CMD_SOCK_SEND = const(0x20) +CMD_SOCK_SEND_MAC = const(0x21) CMD_SOCK_SEND_KEEP = const(0x22) -CMD_SOCK_RECV = const(0x40) +CMD_SOCK_RECV = const(0x40) # Socket n Interrupt Register SNIR_SEND_OK = const(0x10) SNIR_TIMEOUT = const(0x08) -SNIR_RECV = const(0x04) -SNIR_DISCON = const(0x02) -SNIR_CON = const(0x01) +SNIR_RECV = const(0x04) +SNIR_DISCON = const(0x02) +SNIR_CON = const(0x01) -CH_SIZE = const(0x100) -SOCK_SIZE = const(0x800) # MAX W5k socket size +CH_SIZE = const(0x100) +SOCK_SIZE = const(0x800) # MAX W5k socket size # Register commands -MR_RST = const(0x80) # Mode Register RST +MR_RST = const(0x80) # Mode Register RST # Socket mode register -SNMR_CLOSE = const(0x00) -SNMR_TCP = const(0x21) -SNMR_UDP = const(0x02) -SNMR_IPRAW = const(0x03) +SNMR_CLOSE = const(0x00) +SNMR_TCP = const(0x21) +SNMR_UDP = const(0x02) +SNMR_IPRAW = const(0x03) SNMR_MACRAW = const(0x04) -SNMR_PPPOE = const(0x05) +SNMR_PPPOE = const(0x05) # pylint: enable=bad-whitespace MAX_PACKET = const(4000) @@ -134,11 +134,10 @@ W5200_W5500_MAX_SOCK_NUM = const(0x08) # UDP socket struct. -UDP_SOCK = {'bytes_remaining': 0, - 'remote_ip': 0, - 'remote_port': 0} +UDP_SOCK = {"bytes_remaining": 0, "remote_ip": 0, "remote_port": 0} -class WIZNET5K: # pylint: disable=too-many-public-methods + +class WIZNET5K: # pylint: disable=too-many-public-methods """Interface for WIZNET5K module. :param ~busio.SPI spi_bus: The SPI bus the Wiznet module is connected to. :param ~digitalio.DigitalInOut cs: Chip select pin. @@ -151,16 +150,15 @@ class WIZNET5K: # pylint: disable=too-many-public-methods TCP_MODE = const(0x21) UDP_MODE = const(0x02) - TLS_MODE = const(0x03) # This is NOT currently implemented + TLS_MODE = const(0x03) # This is NOT currently implemented # pylint: disable=too-many-arguments - def __init__(self, spi_bus, cs, reset=None, - is_dhcp=True, mac=DEFAULT_MAC, debug=False): + def __init__( + self, spi_bus, cs, reset=None, is_dhcp=True, mac=DEFAULT_MAC, debug=False + ): self._debug = debug self._chip_type = None - self._device = SPIDevice(spi_bus, cs, - baudrate=8000000, - polarity=0, phase=0) + self._device = SPIDevice(spi_bus, cs, baudrate=8000000, polarity=0, phase=0) # init c.s. self._cs = cs @@ -198,27 +196,46 @@ def set_dhcp(self, response_timeout=1): print("* Initializing DHCP") self._src_port = 68 # Return IP assigned by DHCP - _dhcp_client = dhcp.DHCP(self, self.mac_address, response_timeout, debug=self._debug) + _dhcp_client = dhcp.DHCP( + self, self.mac_address, response_timeout, debug=self._debug + ) ret = _dhcp_client.request_dhcp_lease() if ret == 1: - _ip = (_dhcp_client.local_ip[0], _dhcp_client.local_ip[1], - _dhcp_client.local_ip[2], _dhcp_client.local_ip[3]) - - _subnet_mask = (_dhcp_client.subnet_mask[0], _dhcp_client.subnet_mask[1], - _dhcp_client.subnet_mask[2], _dhcp_client.subnet_mask[3]) - - _gw_addr = (_dhcp_client.gateway_ip[0], _dhcp_client.gateway_ip[1], - _dhcp_client.gateway_ip[2], _dhcp_client.gateway_ip[3]) - - self._dns = (_dhcp_client.dns_server_ip[0], _dhcp_client.dns_server_ip[1], - _dhcp_client.dns_server_ip[2], _dhcp_client.dns_server_ip[3]) - self.ifconfig = ((_ip, _subnet_mask, _gw_addr, self._dns)) + _ip = ( + _dhcp_client.local_ip[0], + _dhcp_client.local_ip[1], + _dhcp_client.local_ip[2], + _dhcp_client.local_ip[3], + ) + + _subnet_mask = ( + _dhcp_client.subnet_mask[0], + _dhcp_client.subnet_mask[1], + _dhcp_client.subnet_mask[2], + _dhcp_client.subnet_mask[3], + ) + + _gw_addr = ( + _dhcp_client.gateway_ip[0], + _dhcp_client.gateway_ip[1], + _dhcp_client.gateway_ip[2], + _dhcp_client.gateway_ip[3], + ) + + self._dns = ( + _dhcp_client.dns_server_ip[0], + _dhcp_client.dns_server_ip[1], + _dhcp_client.dns_server_ip[2], + _dhcp_client.dns_server_ip[3], + ) + self.ifconfig = (_ip, _subnet_mask, _gw_addr, self._dns) if self._debug: print("* Found DHCP Server:") - print("IP: {}\nSubnet Mask: {}\nGW Addr: {}\nDNS Server: {}".format(_ip, - _subnet_mask, - _gw_addr, - self._dns)) + print( + "IP: {}\nSubnet Mask: {}\nGW Addr: {}\nDNS Server: {}".format( + _ip, _subnet_mask, _gw_addr, self._dns + ) + ) self._src_port = 0 return 0 return -1 @@ -230,7 +247,7 @@ def get_host_by_name(self, hostname): if self._debug: print("* Get host by name") if isinstance(hostname, str): - hostname = bytes(hostname, 'utf-8') + hostname = bytes(hostname, "utf-8") self._src_port = int(time.monotonic()) # Return IP assigned by DHCP _dns_client = dns.DNS(self, self._dns, debug=self._debug) @@ -258,16 +275,16 @@ def ip_address(self): """Returns the configured IP address.""" return self.read(REG_SIPR, 0x00, 4) - def pretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name + def pretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name """Converts a bytearray IP address to a dotted-quad string for printing """ return "%d.%d.%d.%d" % (ip[0], ip[1], ip[2], ip[3]) - def unpretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name + def unpretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name """Converts a dotted-quad string to a bytearray IP address""" - octets = [int(x) for x in ip.split('.')] + octets = [int(x) for x in ip.split(".")] return bytes(octets) @property @@ -283,13 +300,19 @@ def mac_address(self, address): """ self.write(REG_SHAR, 0x04, address) - def pretty_mac(self, mac): # pylint: disable=no-self-use, invalid-name + def pretty_mac(self, mac): # pylint: disable=no-self-use, invalid-name """Converts a bytearray MAC address to a dotted-quad string for printing """ - return "%s:%s:%s:%s:%s:%s" % (hex(mac[0]), hex(mac[1]), hex(mac[2]), - hex(mac[3]), hex(mac[4]), hex(mac[5])) + return "%s:%s:%s:%s:%s:%s" % ( + hex(mac[0]), + hex(mac[1]), + hex(mac[2]), + hex(mac[3]), + hex(mac[4]), + hex(mac[5]), + ) def remote_ip(self, socket_num): """Returns the IP address of the host who sent the current incoming packet. @@ -299,7 +322,7 @@ def remote_ip(self, socket_num): if socket_num >= self.max_sockets: return self._pbuff for octet in range(0, 4): - self._pbuff[octet] = self._read_socket(socket_num, REG_SNDIPR+octet)[0] + self._pbuff[octet] = self._read_socket(socket_num, REG_SNDIPR + octet)[0] return self.pretty_ip(self._pbuff) @property @@ -320,8 +343,12 @@ def remote_port(self): @property def ifconfig(self): """Returns the network configuration as a tuple.""" - return (self.ip_address, self.read(REG_SUBR, 0x00, 4), - self.read(REG_GAR, 0x00, 4), self._dns) + return ( + self.ip_address, + self.read(REG_SUBR, 0x00, 4), + self.read(REG_GAR, 0x00, 4), + self._dns, + ) @ifconfig.setter def ifconfig(self, params): @@ -349,7 +376,7 @@ def _w5100_init(self): if self.detect_w5500() == 1: # perform w5500 initialization for i in range(0, W5200_W5500_MAX_SOCK_NUM): - ctrl_byte = (0x0C + (i<<5)) + ctrl_byte = 0x0C + (i << 5) self.write(0x1E, ctrl_byte, 2) self.write(0x1F, ctrl_byte, 2) else: @@ -408,14 +435,14 @@ def read(self, addr, callback, length=1, buffer=None): """ with self._device as bus_device: - bus_device.write(bytes([addr >> 8])) # pylint: disable=no-member - bus_device.write(bytes([addr & 0xFF])) # pylint: disable=no-member - bus_device.write(bytes([callback])) # pylint: disable=no-member + bus_device.write(bytes([addr >> 8])) # pylint: disable=no-member + bus_device.write(bytes([addr & 0xFF])) # pylint: disable=no-member + bus_device.write(bytes([callback])) # pylint: disable=no-member if buffer is None: self._rxbuf = bytearray(length) - bus_device.readinto(self._rxbuf) # pylint: disable=no-member + bus_device.readinto(self._rxbuf) # pylint: disable=no-member return self._rxbuf - bus_device.readinto(buffer, end=length) # pylint: disable=no-member + bus_device.readinto(buffer, end=length) # pylint: disable=no-member return buffer def write(self, addr, callback, data): @@ -427,22 +454,22 @@ def write(self, addr, callback, data): """ with self._device as bus_device: - bus_device.write(bytes([addr >> 8])) # pylint: disable=no-member - bus_device.write(bytes([addr & 0xFF])) # pylint: disable=no-member - bus_device.write(bytes([callback])) # pylint: disable=no-member + bus_device.write(bytes([addr >> 8])) # pylint: disable=no-member + bus_device.write(bytes([addr & 0xFF])) # pylint: disable=no-member + bus_device.write(bytes([callback])) # pylint: disable=no-member - if hasattr(data, 'from_bytes'): - bus_device.write(bytes([data])) # pylint: disable=no-member + if hasattr(data, "from_bytes"): + bus_device.write(bytes([data])) # pylint: disable=no-member else: for i, _ in enumerate(data): - bus_device.write(bytes([data[i]])) # pylint: disable=no-member + bus_device.write(bytes([data[i]])) # pylint: disable=no-member # Socket-Register API def udp_remaining(self): """Returns amount of bytes remaining in a udp socket.""" if self._debug: - print("* UDP Bytes Remaining: ", UDP_SOCK['bytes_remaining']) - return UDP_SOCK['bytes_remaining'] + print("* UDP Bytes Remaining: ", UDP_SOCK["bytes_remaining"]) + return UDP_SOCK["bytes_remaining"] def socket_available(self, socket_num, sock_type=SNMR_TCP): """Returns the amount of bytes to be read from the socket. @@ -456,15 +483,15 @@ def socket_available(self, socket_num, sock_type=SNMR_TCP): if sock_type == 0x02: # flush by reading remaining data from previous packet - while UDP_SOCK['bytes_remaining'] > 0 and self.socket_read(socket_num, 1): + while UDP_SOCK["bytes_remaining"] > 0 and self.socket_read(socket_num, 1): if self._debug: - print("Flushing {} bytes".format(UDP_SOCK['bytes_remaining'])) - if UDP_SOCK['bytes_remaining'] > 0: - UDP_SOCK['bytes_remaining'] = UDP_SOCK['bytes_remaining'] - 1 + print("Flushing {} bytes".format(UDP_SOCK["bytes_remaining"])) + if UDP_SOCK["bytes_remaining"] > 0: + UDP_SOCK["bytes_remaining"] = UDP_SOCK["bytes_remaining"] - 1 res = self._get_rx_rcv_size(socket_num) - res = int.from_bytes(res, 'b') + res = int.from_bytes(res, "b") if sock_type == SNMR_TCP: return res if res > 0: @@ -473,12 +500,16 @@ def socket_available(self, socket_num, sock_type=SNMR_TCP): # read the first 8 header bytes ret, self._pbuff = self.socket_read(socket_num, 8) if ret > 0: - UDP_SOCK['remote_ip'] = self._pbuff - UDP_SOCK['remote_port'] = self._pbuff[4] - UDP_SOCK['remote_port'] = (UDP_SOCK['remote_port'] << 8) + self._pbuff[5] - UDP_SOCK['bytes_remaining'] = self._pbuff[6] - UDP_SOCK['bytes_remaining'] = (UDP_SOCK['bytes_remaining'] << 8) + self._pbuff[7] - ret = UDP_SOCK['bytes_remaining'] + UDP_SOCK["remote_ip"] = self._pbuff + UDP_SOCK["remote_port"] = self._pbuff[4] + UDP_SOCK["remote_port"] = (UDP_SOCK["remote_port"] << 8) + self._pbuff[ + 5 + ] + UDP_SOCK["bytes_remaining"] = self._pbuff[6] + UDP_SOCK["bytes_remaining"] = ( + UDP_SOCK["bytes_remaining"] << 8 + ) + self._pbuff[7] + ret = UDP_SOCK["bytes_remaining"] return ret return 0 @@ -498,12 +529,15 @@ def socket_connect(self, socket_num, dest, port, conn_mode=SNMR_TCP): """ assert self.link_status, "Ethernet cable disconnected!" if self._debug: - print("* w5k socket connect, protocol={}, port={}, ip={}".format(conn_mode, port, - self.pretty_ip(dest))) + print( + "* w5k socket connect, protocol={}, port={}, ip={}".format( + conn_mode, port, self.pretty_ip(dest) + ) + ) # initialize a socket and set the mode res = self.socket_open(socket_num, conn_mode=conn_mode) if res == 1: - raise RuntimeError('Failed to initalize a connection with the socket.') + raise RuntimeError("Failed to initalize a connection with the socket.") # set socket destination IP and port self._write_sndipr(socket_num, dest) @@ -517,14 +551,14 @@ def socket_connect(self, socket_num, dest, port, conn_mode=SNMR_TCP): if self._debug: print("SN_SR:", self.socket_status(socket_num)[0]) if self.socket_status(socket_num)[0] == SNSR_SOCK_CLOSED: - raise RuntimeError('Failed to establish connection.') + raise RuntimeError("Failed to establish connection.") elif conn_mode == SNMR_UDP: - UDP_SOCK['bytes_remaining'] = 0 + UDP_SOCK["bytes_remaining"] = 0 return 1 def _send_socket_cmd(self, socket, cmd): self._write_sncr(socket, cmd) - while self._read_sncr(socket) != b'\x00': + while self._read_sncr(socket) != b"\x00": if self._debug: print("waiting for sncr to clear...") @@ -539,8 +573,11 @@ def get_socket(self, sockets): sock = 0 for _sock in range(len(sockets), self.max_sockets): status = self.socket_status(_sock) - if status[0] == SNSR_SOCK_CLOSED or status[0] == SNSR_SOCK_FIN_WAIT \ - or status[0] == SNSR_SOCK_CLOSE_WAIT: + if ( + status[0] == SNSR_SOCK_CLOSED + or status[0] == SNSR_SOCK_FIN_WAIT + or status[0] == SNSR_SOCK_CLOSE_WAIT + ): sock = _sock break @@ -554,7 +591,7 @@ def socket_open(self, socket_num, conn_mode=SNMR_TCP): """ assert self.link_status, "Ethernet cable disconnected!" if self._debug: - print("*** Opening socket %d"%socket_num) + print("*** Opening socket %d" % socket_num) if self._read_snsr(socket_num)[0] == SNSR_SOCK_CLOSED: if self._debug: print("* Opening W5k Socket, protocol={}".format(conn_mode)) @@ -572,9 +609,10 @@ def socket_open(self, socket_num, conn_mode=SNMR_TCP): # open socket self._write_sncr(socket_num, CMD_SOCK_OPEN) self._read_sncr(socket_num) - assert self._read_snsr((socket_num))[0] == 0x13 or \ - self._read_snsr((socket_num))[0] == 0x22, \ - "Could not open socket in TCP or UDP mode." + assert ( + self._read_snsr((socket_num))[0] == 0x13 + or self._read_snsr((socket_num))[0] == 0x22 + ), "Could not open socket in TCP or UDP mode." return 0 return 1 @@ -602,15 +640,13 @@ def socket_read(self, socket_num, length): # Check if there is data available on the socket ret = self._get_rx_rcv_size(socket_num) - ret = int.from_bytes(ret, 'b') + ret = int.from_bytes(ret, "b") if self._debug: print("Bytes avail. on sock: ", ret) if ret == 0: # no data on socket? status = self._read_snmr(socket_num) - if status in (SNSR_SOCK_LISTEN, - SNSR_SOCK_CLOSED, - SNSR_SOCK_CLOSE_WAIT): + if status in (SNSR_SOCK_LISTEN, SNSR_SOCK_CLOSED, SNSR_SOCK_CLOSE_WAIT): # remote end closed its side of the connection, EOF state ret = 0 resp = 0 @@ -624,12 +660,12 @@ def socket_read(self, socket_num, length): if ret > 0: if self._debug: - print('\t * Processing {} bytes of data'.format(ret)) + print("\t * Processing {} bytes of data".format(ret)) # Read the starting save address of the received data ptr = self._read_snrx_rd(socket_num) # Read data from the starting address of snrx_rd - ctrl_byte = (0x18+(socket_num<<5)) + ctrl_byte = 0x18 + (socket_num << 5) resp = self.read(ptr, ctrl_byte, ret) @@ -646,17 +682,16 @@ def socket_read(self, socket_num, length): def read_udp(self, socket_num, length): """Read UDP socket's remaining bytes. """ - if UDP_SOCK['bytes_remaining'] > 0: - if UDP_SOCK['bytes_remaining'] <= length: - ret, resp = self.socket_read(socket_num, UDP_SOCK['bytes_remaining']) + if UDP_SOCK["bytes_remaining"] > 0: + if UDP_SOCK["bytes_remaining"] <= length: + ret, resp = self.socket_read(socket_num, UDP_SOCK["bytes_remaining"]) else: ret, resp = self.socket_read(socket_num, length) if ret > 0: - UDP_SOCK['bytes_remaining'] -= ret + UDP_SOCK["bytes_remaining"] -= ret return ret, resp return -1 - def socket_write(self, socket_num, buffer): """Writes a bytearray to a provided socket. @@ -676,30 +711,31 @@ def socket_write(self, socket_num, buffer): while free_size < ret: free_size = self._get_tx_free_size(socket_num) status = self.socket_status(socket_num) - if status not in (SNSR_SOCK_ESTABLISHED, - SNSR_SOCK_CLOSE_WAIT): + if status not in (SNSR_SOCK_ESTABLISHED, SNSR_SOCK_CLOSE_WAIT): ret = 0 break # Read the starting address for saving the transmitting data. ptr = self._read_sntx_wr(socket_num) offset = ptr & 0x07FF - dst_addr = offset + (socket_num * 2048 + 0x8000) + dst_addr = offset + (socket_num * 2048 + 0x8000) # update sn_tx_wr to the value + data size ptr += len(buffer) self._write_sntx_wr(socket_num, ptr) - cntl_byte = (0x14+(socket_num<<5)) + cntl_byte = 0x14 + (socket_num << 5) self.write(dst_addr, cntl_byte, buffer) self._write_sncr(socket_num, CMD_SOCK_SEND) self._read_sncr(socket_num) # check data was transferred correctly - while(self._read_socket(socket_num, REG_SNIR)[0] & SNIR_SEND_OK) != SNIR_SEND_OK: + while ( + self._read_socket(socket_num, REG_SNIR)[0] & SNIR_SEND_OK + ) != SNIR_SEND_OK: if self.socket_status(socket_num) == SNSR_SOCK_CLOSED: - #self.socket_close(socket_num) + # self.socket_close(socket_num) return 0 time.sleep(0.01) @@ -734,32 +770,30 @@ def _get_tx_free_size(self, sock): def _read_snrx_rd(self, sock): self._pbuff[0] = self._read_socket(sock, REG_SNRX_RD)[0] - self._pbuff[1] = self._read_socket(sock, REG_SNRX_RD+1)[0] + self._pbuff[1] = self._read_socket(sock, REG_SNRX_RD + 1)[0] return self._pbuff[0] << 8 | self._pbuff[1] - def _write_snrx_rd(self, sock, data): self._write_socket(sock, REG_SNRX_RD, data >> 8) - self._write_socket(sock, REG_SNRX_RD+1, data & 0xff) + self._write_socket(sock, REG_SNRX_RD + 1, data & 0xFF) def _write_sntx_wr(self, sock, data): self._write_socket(sock, REG_SNTX_WR, data >> 8) - self._write_socket(sock, REG_SNTX_WR+1, data & 0xff) + self._write_socket(sock, REG_SNTX_WR + 1, data & 0xFF) def _read_sntx_wr(self, sock): self._pbuff[0] = self._read_socket(sock, 0x0024)[0] - self._pbuff[1] = self._read_socket(sock, 0x0024+1)[0] + self._pbuff[1] = self._read_socket(sock, 0x0024 + 1)[0] return self._pbuff[0] << 8 | self._pbuff[1] - def _read_sntx_fsr(self, sock): data = self._read_socket(sock, REG_SNTX_FSR) - data += self._read_socket(sock, REG_SNTX_FSR+1) + data += self._read_socket(sock, REG_SNTX_FSR + 1) return data def _read_snrx_rsr(self, sock): data = self._read_socket(sock, REG_SNRX_RSR) - data += self._read_socket(sock, REG_SNRX_RSR+1) + data += self._read_socket(sock, REG_SNRX_RSR + 1) return data def _write_sndipr(self, sock, ip_addr): @@ -767,14 +801,14 @@ def _write_sndipr(self, sock, ip_addr): """ for octet in range(0, 4): - self._write_socket(sock, REG_SNDIPR+octet, ip_addr[octet]) + self._write_socket(sock, REG_SNDIPR + octet, ip_addr[octet]) def _write_sndport(self, sock, port): """Writes to socket destination port. """ self._write_socket(sock, REG_SNDPORT, port >> 8) - self._write_socket(sock, REG_SNDPORT+1, port & 0xFF) + self._write_socket(sock, REG_SNDPORT + 1, port & 0xFF) def _read_snsr(self, sock): """Reads Socket n Status Register. @@ -782,8 +816,6 @@ def _read_snsr(self, sock): """ return self._read_socket(sock, REG_SNSR) - - def _write_snmr(self, sock, protocol): """Write to Socket n Mode Register. @@ -799,7 +831,7 @@ def _write_sock_port(self, sock, port): """Write to the socket port number. """ self._write_socket(sock, REG_SNPORT, port >> 8) - self._write_socket(sock, REG_SNPORT+1, port & 0xFF) + self._write_socket(sock, REG_SNPORT + 1, port & 0xFF) def _write_sncr(self, sock, data): self._write_socket(sock, REG_SNCR, data) @@ -814,7 +846,7 @@ def _write_socket(self, sock, address, data, length=None): """Write to a W5k socket register. """ base = self._ch_base_msb << 8 - cntl_byte = (sock<<5)+0x0C + cntl_byte = (sock << 5) + 0x0C if length is None: return self.write(base + sock * CH_SIZE + address, cntl_byte, data) return self.write(base + sock * CH_SIZE + address, cntl_byte, data) @@ -822,5 +854,5 @@ def _write_socket(self, sock, address, data, length=None): def _read_socket(self, sock, address): """Read a W5k socket register. """ - cntl_byte = (sock<<5)+0x08 + cntl_byte = (sock << 5) + 0x08 return self.read(address, cntl_byte) diff --git a/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py b/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py index 5993c22..a52d4d1 100755 --- a/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py @@ -39,57 +39,58 @@ # pylint: disable=bad-whitespace # DHCP State Machine -STATE_DHCP_START = const(0x00) -STATE_DHCP_DISCOVER = const(0x01) -STATE_DHCP_REQUEST = const(0x02) -STATE_DHCP_LEASED = const(0x03) +STATE_DHCP_START = const(0x00) +STATE_DHCP_DISCOVER = const(0x01) +STATE_DHCP_REQUEST = const(0x02) +STATE_DHCP_LEASED = const(0x03) STATE_DHCP_REREQUEST = const(0x04) -STATE_DHCP_RELEASE = const(0x05) +STATE_DHCP_RELEASE = const(0x05) # DHCP Message Types DHCP_DISCOVER = const(1) -DHCP_OFFER = const(2) -DHCP_REQUEST = const(3) -DHCP_DECLINE = const(4) -DHCP_ACK = const(5) -DHCP_NAK = const(6) -DHCP_RELEASE = const(7) -DHCP_INFORM = const(8) +DHCP_OFFER = const(2) +DHCP_REQUEST = const(3) +DHCP_DECLINE = const(4) +DHCP_ACK = const(5) +DHCP_NAK = const(6) +DHCP_RELEASE = const(7) +DHCP_INFORM = const(8) # DHCP Message OP Codes DHCP_BOOT_REQUEST = const(0x01) -DHCP_BOOT_REPLY = const(0x02) +DHCP_BOOT_REPLY = const(0x02) -DHCP_HTYPE10MB = const(0x01) +DHCP_HTYPE10MB = const(0x01) DHCP_HTYPE100MB = const(0x02) DHCP_HLENETHERNET = const(0x06) -DHCP_HOPS = const(0x00) +DHCP_HOPS = const(0x00) MAGIC_COOKIE = const(0x63825363) MAX_DHCP_OPT = const(0x10) # Default DHCP Server port -DHCP_SERVER_PORT = const(67) +DHCP_SERVER_PORT = const(67) # DHCP Lease Time, in seconds DEFAULT_LEASE_TIME = const(900) -BROADCAST_SERVER_ADDR = '255.255.255.255' +BROADCAST_SERVER_ADDR = "255.255.255.255" # DHCP Response Options -MSG_TYPE = 53 -SUBNET_MASK = 1 +MSG_TYPE = 53 +SUBNET_MASK = 1 ROUTERS_ON_SUBNET = 3 -DNS_SERVERS = 6 -DHCP_SERVER_ID = 54 -T1_VAL = 58 -T2_VAL = 59 -LEASE_TIME = 51 -OPT_END = 255 +DNS_SERVERS = 6 +DHCP_SERVER_ID = 54 +T1_VAL = 58 +T2_VAL = 59 +LEASE_TIME = 51 +OPT_END = 255 # pylint: enable=bad-whitespace _BUFF = bytearray(317) + class DHCP: """W5k DHCP Client implementation. :param eth: Wiznet 5k object @@ -148,16 +149,16 @@ def send_dhcp_message(self, state, time_elapsed): # Transaction ID (xid) self._initial_xid = htonl(self._transaction_id) - self._initial_xid = self._initial_xid.to_bytes(4, 'l') + self._initial_xid = self._initial_xid.to_bytes(4, "l") _BUFF[4:7] = self._initial_xid # seconds elapsed - _BUFF[8] = ((int(time_elapsed) & 0xff00) >> 8) - _BUFF[9] = (int(time_elapsed) & 0x00ff) + _BUFF[8] = (int(time_elapsed) & 0xFF00) >> 8 + _BUFF[9] = int(time_elapsed) & 0x00FF # flags flags = htons(0x8000) - flags = flags.to_bytes(2, 'b') + flags = flags.to_bytes(2, "b") _BUFF[10] = flags[1] _BUFF[11] = flags[0] @@ -170,10 +171,10 @@ def send_dhcp_message(self, state, time_elapsed): # NOTE: 192 octets of 0's, BOOTP legacy # Magic Cookie - _BUFF[236] = ((MAGIC_COOKIE >> 24)& 0xFF) - _BUFF[237] = ((MAGIC_COOKIE >> 16)& 0xFF) - _BUFF[238] = ((MAGIC_COOKIE >> 8)& 0xFF) - _BUFF[239] = (MAGIC_COOKIE& 0xFF) + _BUFF[236] = (MAGIC_COOKIE >> 24) & 0xFF + _BUFF[237] = (MAGIC_COOKIE >> 16) & 0xFF + _BUFF[238] = (MAGIC_COOKIE >> 8) & 0xFF + _BUFF[239] = MAGIC_COOKIE & 0xFF # Option - DHCP Message Type _BUFF[240] = 53 @@ -188,7 +189,7 @@ def send_dhcp_message(self, state, time_elapsed): _BUFF[245] = 0x01 # Client MAC Address for mac in range(0, len(self._mac_address)): - _BUFF[246+mac] = self._mac_address[mac] + _BUFF[246 + mac] = self._mac_address[mac] # Option - Host Name _BUFF[252] = 12 @@ -196,7 +197,7 @@ def send_dhcp_message(self, state, time_elapsed): _BUFF[254:260] = b"WIZnet" for mac in range(0, 5): - _BUFF[260+mac] = self._mac_address[mac] + _BUFF[260 + mac] = self._mac_address[mac] if state == DHCP_REQUEST: # Set the parsed local IP addr @@ -228,7 +229,9 @@ def send_dhcp_message(self, state, time_elapsed): # Send DHCP packet self._sock.send(_BUFF) - def parse_dhcp_response(self, response_timeout): # pylint: disable=too-many-branches, too-many-statements + def parse_dhcp_response( + self, response_timeout + ): # pylint: disable=too-many-branches, too-many-statements """Parse DHCP response from DHCP server. Returns DHCP packet type. @@ -248,7 +251,9 @@ def parse_dhcp_response(self, response_timeout): # pylint: disable=too-many-bran # -- Parse Packet, FIXED -- # # Validate OP - assert _BUFF[0] == DHCP_BOOT_REPLY, "Malformed Packet - \ + assert ( + _BUFF[0] == DHCP_BOOT_REPLY + ), "Malformed Packet - \ DHCP message OP is not expected BOOT Reply." xid = _BUFF[4:8] @@ -260,7 +265,7 @@ def parse_dhcp_response(self, response_timeout): # pylint: disable=too-many-bran if _BUFF[28:34] == 0: return 0, 0 - if int.from_bytes(_BUFF[235:240], 'l') != MAGIC_COOKIE: + if int.from_bytes(_BUFF[235:240], "l") != MAGIC_COOKIE: return 0, 0 # -- Parse Packet, VARIABLE -- # @@ -276,43 +281,43 @@ def parse_dhcp_response(self, response_timeout): # pylint: disable=too-many-bran ptr += 1 opt_len = _BUFF[ptr] ptr += 1 - self.subnet_mask = _BUFF[ptr:ptr+opt_len] + self.subnet_mask = _BUFF[ptr : ptr + opt_len] ptr += opt_len elif _BUFF[ptr] == DHCP_SERVER_ID: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 - self.dhcp_server_ip = _BUFF[ptr:ptr+opt_len] + self.dhcp_server_ip = _BUFF[ptr : ptr + opt_len] ptr += opt_len elif _BUFF[ptr] == LEASE_TIME: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 - self._lease_time = int.from_bytes(_BUFF[ptr:ptr+opt_len], 'l') + self._lease_time = int.from_bytes(_BUFF[ptr : ptr + opt_len], "l") ptr += opt_len elif _BUFF[ptr] == ROUTERS_ON_SUBNET: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 - self.gateway_ip = _BUFF[ptr:ptr+opt_len] + self.gateway_ip = _BUFF[ptr : ptr + opt_len] ptr += opt_len elif _BUFF[ptr] == DNS_SERVERS: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 - self.dns_server_ip = _BUFF[ptr:ptr+4] - ptr += opt_len # still increment even though we only read 1 addr. + self.dns_server_ip = _BUFF[ptr : ptr + 4] + ptr += opt_len # still increment even though we only read 1 addr. elif _BUFF[ptr] == T1_VAL: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 - self._t1 = int.from_bytes(_BUFF[ptr:ptr+opt_len], 'l') + self._t1 = int.from_bytes(_BUFF[ptr : ptr + opt_len], "l") ptr += opt_len elif _BUFF[ptr] == T2_VAL: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 - self._t2 = int.from_bytes(_BUFF[ptr:ptr+opt_len], 'l') + self._t2 = int.from_bytes(_BUFF[ptr : ptr + opt_len], "l") ptr += opt_len elif _BUFF[ptr] == 0: break @@ -325,18 +330,26 @@ def parse_dhcp_response(self, response_timeout): # pylint: disable=too-many-bran ptr += opt_len if self._debug: - print("Msg Type: {}\nSubnet Mask: {}\nDHCP Server ID:{}\nDNS Server IP:{}\ - \nGateway IP:{}\nT1:{}\nT2:{}\nLease Time:{}".format(msg_type, self.subnet_mask, - self.dhcp_server_ip, - self.dns_server_ip, - self.gateway_ip, - self._t1, self._t2, - self._lease_time)) + print( + "Msg Type: {}\nSubnet Mask: {}\nDHCP Server ID:{}\nDNS Server IP:{}\ + \nGateway IP:{}\nT1:{}\nT2:{}\nLease Time:{}".format( + msg_type, + self.subnet_mask, + self.dhcp_server_ip, + self.dns_server_ip, + self.gateway_ip, + self._t1, + self._t2, + self._lease_time, + ) + ) gc.collect() return msg_type, xid - def request_dhcp_lease(self): # pylint: disable=too-many-branches, too-many-statements + def request_dhcp_lease( + self, + ): # pylint: disable=too-many-branches, too-many-statements """Request to renew or acquire a DHCP lease. """ @@ -353,8 +366,9 @@ def request_dhcp_lease(self): # pylint: disable=too-many-branches, too-many-stat self._sock.connect(((BROADCAST_SERVER_ADDR), DHCP_SERVER_PORT)) if self._debug: print("* DHCP: Discover") - self.send_dhcp_message(STATE_DHCP_DISCOVER, - ((time.monotonic() - start_time) / 1000)) + self.send_dhcp_message( + STATE_DHCP_DISCOVER, ((time.monotonic() - start_time) / 1000) + ) self._dhcp_state = STATE_DHCP_DISCOVER elif self._dhcp_state == STATE_DHCP_DISCOVER: if self._debug: @@ -363,10 +377,12 @@ def request_dhcp_lease(self): # pylint: disable=too-many-branches, too-many-stat if msg_type == DHCP_OFFER: # use the _transaction_id the offer returned, # rather than the current one - self._transaction_id = self._transaction_id.from_bytes(xid, 'l') + self._transaction_id = self._transaction_id.from_bytes(xid, "l") if self._debug: print("* DHCP: Request") - self.send_dhcp_message(DHCP_REQUEST, ((time.monotonic() - start_time) / 1000)) + self.send_dhcp_message( + DHCP_REQUEST, ((time.monotonic() - start_time) / 1000) + ) self._dhcp_state = STATE_DHCP_REQUEST else: print("* Received DHCP Message is not OFFER") @@ -396,7 +412,7 @@ def request_dhcp_lease(self): # pylint: disable=too-many-branches, too-many-stat msg_type = 0 self._dhcp_state = STATE_DHCP_START - if (result != 1 and ((time.monotonic() - start_time > self._timeout))): + if result != 1 and ((time.monotonic() - start_time > self._timeout)): break self._transaction_id += 1 diff --git a/adafruit_wiznet5k/adafruit_wiznet5k_dns.py b/adafruit_wiznet5k/adafruit_wiznet5k_dns.py index 083e10d..5f02592 100755 --- a/adafruit_wiznet5k/adafruit_wiznet5k_dns.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k_dns.py @@ -38,29 +38,31 @@ # pylint: disable=bad-whitespace -QUERY_FLAG = const(0x00) -OPCODE_STANDARD_QUERY = const(0x00) -RECURSION_DESIRED_FLAG = 1<<8 +QUERY_FLAG = const(0x00) +OPCODE_STANDARD_QUERY = const(0x00) +RECURSION_DESIRED_FLAG = 1 << 8 -TYPE_A = const(0x0001) +TYPE_A = const(0x0001) CLASS_IN = const(0x0001) DATA_LEN = const(0x0004) # Return codes for gethostbyname -SUCCESS = const(1) -TIMED_OUT = const(-1) -INVALID_SERVER = const(-2) -TRUNCATED = const(-3) +SUCCESS = const(1) +TIMED_OUT = const(-1) +INVALID_SERVER = const(-2) +TRUNCATED = const(-3) INVALID_RESPONSE = const(-4) -DNS_PORT = const(0x35) # port used for DNS request +DNS_PORT = const(0x35) # port used for DNS request # pylint: enable=bad-whitespace + class DNS: """W5K DNS implementation. :param iface: Network interface """ + def __init__(self, iface, dns_address, debug=False): self._debug = debug self._iface = iface @@ -70,7 +72,7 @@ def __init__(self, iface, dns_address, debug=False): self._dns_server = dns_address self._host = 0 - self._request_id = 0 # request identifier + self._request_id = 0 # request identifier self._pkt_buf = bytearray() def gethostbyname(self, hostname): @@ -104,7 +106,9 @@ def gethostbyname(self, hostname): self._sock.close() return addr - def _parse_dns_response(self): # pylint: disable=too-many-return-statements, too-many-branches, too-many-statements, too-many-locals + def _parse_dns_response( + self, + ): # pylint: disable=too-many-return-statements, too-many-branches, too-many-statements, too-many-locals """Receives and parses DNS query response. Returns desired hostname address if obtained, -1 otherwise. @@ -126,26 +130,30 @@ def _parse_dns_response(self): # pylint: disable=too-many-return-statements, too print("DNS Packet Received: ", self._pkt_buf) # Validate request identifier - xid = int.from_bytes(self._pkt_buf[0:2], 'l') + xid = int.from_bytes(self._pkt_buf[0:2], "l") if not xid == self._request_id: if self._debug: - print("* DNS ERROR: Received request identifer {} \ - does not match expected {}".format(xid, self._request_id)) + print( + "* DNS ERROR: Received request identifer {} \ + does not match expected {}".format( + xid, self._request_id + ) + ) return -1 # Validate flags - flags = int.from_bytes(self._pkt_buf[2:4], 'l') + flags = int.from_bytes(self._pkt_buf[2:4], "l") if not flags == 0x8180: if self._debug: print("* DNS ERROR: Invalid flags, ", flags) return -1 # Number of questions - qr_count = int.from_bytes(self._pkt_buf[4:6], 'l') + qr_count = int.from_bytes(self._pkt_buf[4:6], "l") if not qr_count >= 1: if self._debug: print("* DNS ERROR: Question count >=1, ", qr_count) return -1 # Number of answers - an_count = int.from_bytes(self._pkt_buf[6:8], 'l') + an_count = int.from_bytes(self._pkt_buf[6:8], "l") if self._debug: print("* DNS Answer Count: ", an_count) if not an_count >= 1: @@ -159,13 +167,13 @@ def _parse_dns_response(self): # pylint: disable=too-many-return-statements, too name_len = self._pkt_buf[ptr] if name_len == 0x00: # we reached the end of this name - ptr += 1 # inc. pointer by 0x00 + ptr += 1 # inc. pointer by 0x00 break # advance pointer ptr += name_len + 1 # Validate Query is Type A - q_type = int.from_bytes(self._pkt_buf[ptr:ptr+2], 'l') + q_type = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "l") if not q_type == TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Query Type: ", q_type) @@ -173,7 +181,7 @@ def _parse_dns_response(self): # pylint: disable=too-many-return-statements, too ptr += 2 # Validate Query is Type A - q_class = int.from_bytes(self._pkt_buf[ptr:ptr+2], 'l') + q_class = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "l") if not q_class == TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Query Class: ", q_class) @@ -181,16 +189,16 @@ def _parse_dns_response(self): # pylint: disable=too-many-return-statements, too ptr += 2 # Let's take the first type-a answer - if self._pkt_buf[ptr] != 0xc0: + if self._pkt_buf[ptr] != 0xC0: return -1 ptr += 1 - if self._pkt_buf[ptr] != 0xc: + if self._pkt_buf[ptr] != 0xC: return -1 ptr += 1 # Validate Answer Type A - ans_type = int.from_bytes(self._pkt_buf[ptr:ptr+2], 'l') + ans_type = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "l") if not ans_type == TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Answer Type: ", ans_type) @@ -198,7 +206,7 @@ def _parse_dns_response(self): # pylint: disable=too-many-return-statements, too ptr += 2 # Validate Answer Class IN - ans_class = int.from_bytes(self._pkt_buf[ptr:ptr+2], 'l') + ans_class = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "l") if not ans_class == TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Answer Class: ", ans_class) @@ -209,14 +217,14 @@ def _parse_dns_response(self): # pylint: disable=too-many-return-statements, too ptr += 4 # Validate addr is IPv4 - data_len = int.from_bytes(self._pkt_buf[ptr:ptr+2], 'l') + data_len = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "l") if not data_len == DATA_LEN: if self._debug: print("* DNS ERROR: Unexpected Data Length: ", data_len) return -1 ptr += 2 # Return address - return self._pkt_buf[ptr:ptr+4] + return self._pkt_buf[ptr : ptr + 4] def _build_dns_header(self): """Builds DNS header.""" @@ -240,13 +248,13 @@ def _build_dns_header(self): # NSCOUNT self._pkt_buf.append(0x00) self._pkt_buf.append(0x00) - #ARCOUNT + # ARCOUNT self._pkt_buf.append(0x00) self._pkt_buf.append(0x00) def _build_dns_question(self): """Build DNS question""" - host = self._host.decode('utf-8') + host = self._host.decode("utf-8") host = host.split(".") # write out each section of host for i, _ in enumerate(host): diff --git a/adafruit_wiznet5k/adafruit_wiznet5k_socket.py b/adafruit_wiznet5k/adafruit_wiznet5k_socket.py index d58504a..fd13919 100755 --- a/adafruit_wiznet5k/adafruit_wiznet5k_socket.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k_socket.py @@ -34,33 +34,42 @@ from micropython import const from adafruit_wiznet5k import adafruit_wiznet5k -_the_interface = None # pylint: disable=invalid-name +_the_interface = None # pylint: disable=invalid-name + + def set_interface(iface): """Helper to set the global internet interface.""" - global _the_interface # pylint: disable=global-statement, invalid-name + global _the_interface # pylint: disable=global-statement, invalid-name _the_interface = iface + def htonl(x): """Convert 32-bit positive integers from host to network byte order.""" - return ((x)<<24 & 0xFF000000) | ((x)<< 8 & 0x00FF0000) | \ - ((x)>> 8 & 0x0000FF00) | ((x)>>24 & 0x000000FF) + return ( + ((x) << 24 & 0xFF000000) + | ((x) << 8 & 0x00FF0000) + | ((x) >> 8 & 0x0000FF00) + | ((x) >> 24 & 0x000000FF) + ) + def htons(x): """Convert 16-bit positive integers from host to network byte order.""" - return (((x)<<8)&0xFF00) | (((x)>>8)&0xFF) + return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF) + # pylint: disable=bad-whitespace -SOCK_STREAM = const(0x21) # TCP -TCP_MODE = 80 -SOCK_DGRAM = const(0x02) # UDP -AF_INET = const(3) +SOCK_STREAM = const(0x21) # TCP +TCP_MODE = 80 +SOCK_DGRAM = const(0x02) # UDP +AF_INET = const(3) NO_SOCKET_AVAIL = const(255) # pylint: enable=bad-whitespace # keep track of sockets we allocate SOCKETS = [] -#pylint: disable=too-many-arguments, unused-argument +# pylint: disable=too-many-arguments, unused-argument def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0): """Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. @@ -68,7 +77,8 @@ def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0): """ if not isinstance(port, int): raise RuntimeError("Port must be an integer") - return [(AF_INET, socktype, proto, '', (gethostbyname(host), port))] + return [(AF_INET, socktype, proto, "", (gethostbyname(host), port))] + def gethostbyname(hostname): """Translate a host name to IPv4 address format. The IPv4 address @@ -79,7 +89,8 @@ def gethostbyname(hostname): addr = "{}.{}.{}.{}".format(addr[0], addr[1], addr[2], addr[3]) return addr -#pylint: disable=invalid-name + +# pylint: disable=invalid-name class socket: """A simplified implementation of the Python 'socket' class for connecting to a Wiznet5k module. @@ -87,8 +98,11 @@ class socket: :param int type: Socket type. """ + # pylint: disable=redefined-builtin,unused-argument - def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, socknum=None): + def __init__( + self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, socknum=None + ): if family != AF_INET: raise RuntimeError("Only AF_INET family supported by W5K modules.") self._sock_type = type @@ -110,12 +124,17 @@ def connected(self): if self.socknum >= _the_interface.max_sockets: return 0 status = _the_interface.socket_status(self.socknum)[0] - if status == adafruit_wiznet5k.SNSR_SOCK_CLOSE_WAIT and self.available()[0] == 0: + if ( + status == adafruit_wiznet5k.SNSR_SOCK_CLOSE_WAIT + and self.available()[0] == 0 + ): result = False - result = status not in (adafruit_wiznet5k.SNSR_SOCK_CLOSED, - adafruit_wiznet5k.SNSR_SOCK_LISTEN, - adafruit_wiznet5k.SNSR_SOCK_CLOSE_WAIT, - adafruit_wiznet5k.SNSR_SOCK_FIN_WAIT) + result = status not in ( + adafruit_wiznet5k.SNSR_SOCK_CLOSED, + adafruit_wiznet5k.SNSR_SOCK_LISTEN, + adafruit_wiznet5k.SNSR_SOCK_CLOSE_WAIT, + adafruit_wiznet5k.SNSR_SOCK_FIN_WAIT, + ) if not result: self.close() return result @@ -130,8 +149,8 @@ def inet_aton(self, ip_string): :param str ip_string: IP Address, as a dotted-quad string. """ - self._buffer = b'' - self._buffer = [int(item) for item in ip_string.split('.')] + self._buffer = b"" + self._buffer = [int(item) for item in ip_string.split(".")] self._buffer = bytearray(self._buffer) return self._buffer @@ -141,14 +160,18 @@ def connect(self, address, conntype=None): :param tuple address: Remote socket as a (host, port) tuple. """ - assert conntype != 0x03, "Error: SSL/TLS is not currently supported by CircuitPython." + assert ( + conntype != 0x03 + ), "Error: SSL/TLS is not currently supported by CircuitPython." host, port = address - if hasattr(host, 'split'): - host = tuple(map(int, host.split('.'))) - if not _the_interface.socket_connect(self.socknum, host, port, conn_mode=self._sock_type): + if hasattr(host, "split"): + host = tuple(map(int, host.split("."))) + if not _the_interface.socket_connect( + self.socknum, host, port, conn_mode=self._sock_type + ): raise RuntimeError("Failed to connect to host", host) - self._buffer = b'' + self._buffer = b"" def send(self, data): """Send data to the socket. The socket must be connected to @@ -159,8 +182,7 @@ def send(self, data): _the_interface.socket_write(self.socknum, data) gc.collect() - - def recv(self, bufsize=0): #pylint: disable=too-many-branches + def recv(self, bufsize=0): # pylint: disable=too-many-branches """Reads some bytes from the connected remote address. :param int bufsize: Maximum number of bytes to receive. """ @@ -174,19 +196,20 @@ def recv(self, bufsize=0): #pylint: disable=too-many-branches avail = _the_interface.udp_remaining() if avail: if self._sock_type == SOCK_STREAM: - self._buffer += _the_interface.socket_read(self.socknum, avail)[1] + self._buffer += _the_interface.socket_read(self.socknum, avail)[ + 1 + ] elif self._sock_type == SOCK_DGRAM: self._buffer += _the_interface.read_udp(self.socknum, avail)[1] else: break gc.collect() ret = self._buffer - self._buffer = b'' + self._buffer = b"" gc.collect() return ret stamp = time.monotonic() - to_read = bufsize - len(self._buffer) received = [] while to_read > 0: @@ -198,7 +221,9 @@ def recv(self, bufsize=0): #pylint: disable=too-many-branches if avail: stamp = time.monotonic() if self._sock_type == SOCK_STREAM: - recv = _the_interface.socket_read(self.socknum, min(to_read, avail))[1] + recv = _the_interface.socket_read( + self.socknum, min(to_read, avail) + )[1] elif self._sock_type == SOCK_DGRAM: recv = _the_interface.read_udp(self.socknum, min(to_read, avail))[1] recv = bytes(recv) @@ -207,12 +232,12 @@ def recv(self, bufsize=0): #pylint: disable=too-many-branches gc.collect() if self._timeout > 0 and time.monotonic() - stamp > self._timeout: break - self._buffer += b''.join(received) + self._buffer += b"".join(received) ret = None if len(self._buffer) == bufsize: ret = self._buffer - self._buffer = b'' + self._buffer = b"" else: ret = self._buffer[:bufsize] self._buffer = self._buffer[bufsize:] @@ -225,7 +250,7 @@ def readline(self): """ stamp = time.monotonic() - while b'\r\n' not in self._buffer: + while b"\r\n" not in self._buffer: if self._sock_type == SOCK_STREAM: avail = self.available() if avail: @@ -237,7 +262,7 @@ def readline(self): elif self._timeout > 0 and time.monotonic() - stamp > self._timeout: self.close() raise RuntimeError("Didn't receive response, failing out...") - firstline, self._buffer = self._buffer.split(b'\r\n', 1) + firstline, self._buffer = self._buffer.split(b"\r\n", 1) gc.collect() return firstline diff --git a/docs/conf.py b/docs/conf.py index 4b31871..e36a5e4 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,8 @@ import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,10 +11,10 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.napoleon', - 'sphinx.ext.todo', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", ] # TODO: Please Read! @@ -23,29 +24,36 @@ autodoc_mock_imports = ["digitalio", "busio", "adafruit_bus_device"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", None), + "BusDevice": ( + "https://circuitpython.readthedocs.io/projects/busdevice/en/latest/", + None, + ), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit Wiznet5k Library' -copyright = u'2020 Brent Rubell' -author = u'Brent Rubell' +project = "Adafruit Wiznet5k Library" +copyright = "2020 Brent Rubell" +author = "Brent Rubell" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'1.0' +version = "1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = "1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -57,7 +65,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -69,7 +77,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -84,59 +92,62 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +on_rtd = os.environ.get("READTHEDOCS", None) == "True" if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] except: - html_theme = 'default' - html_theme_path = ['.'] + html_theme = "default" + html_theme_path = ["."] else: - html_theme_path = ['.'] + html_theme_path = ["."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitWiznet5kLibrarydoc' +htmlhelp_basename = "AdafruitWiznet5kLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitWiznet5kLibrary.tex', u'AdafruitWiznet5k Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitWiznet5kLibrary.tex", + "AdafruitWiznet5k Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -144,8 +155,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitWiznet5klibrary', u'Adafruit Wiznet5k Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitWiznet5klibrary", + "Adafruit Wiznet5k Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -154,7 +170,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitWiznet5kLibrary', u'Adafruit Wiznet5k Library Documentation', - author, 'AdafruitWiznet5kLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitWiznet5kLibrary", + "Adafruit Wiznet5k Library Documentation", + author, + "AdafruitWiznet5kLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/adafruit_wiznet5k_cheerlights.py b/examples/adafruit_wiznet5k_cheerlights.py index 2e9851e..fcdeb1b 100755 --- a/examples/adafruit_wiznet5k_cheerlights.py +++ b/examples/adafruit_wiznet5k_cheerlights.py @@ -26,7 +26,7 @@ pixels = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.3) pixels.fill(0) -attempts = 3 # Number of attempts to retry each request +attempts = 3 # Number of attempts to retry each request failure_count = 0 response = None @@ -48,8 +48,10 @@ print("Request failed, retrying...\n", error) failure_count += 1 if failure_count >= attempts: - raise AssertionError("Failed to resolve hostname, \ - please check your router's DNS configuration.") + raise AssertionError( + "Failed to resolve hostname, \ + please check your router's DNS configuration." + ) continue if not value: continue @@ -57,7 +59,7 @@ color = int(value[1:], 16) red = color >> 16 & 0xFF green = color >> 8 & 0xFF - blue = color& 0xFF + blue = color & 0xFF gamma_corrected = fancy.gamma_adjust(fancy.CRGB(red, green, blue)).pack() pixels.fill(gamma_corrected) diff --git a/examples/wiznet5k_aio_post.py b/examples/wiznet5k_aio_post.py index eb6f0a1..5634677 100644 --- a/examples/wiznet5k_aio_post.py +++ b/examples/wiznet5k_aio_post.py @@ -23,14 +23,19 @@ counter = 0 while True: - print("Posting data...", end='') + print("Posting data...", end="") data = counter - feed = 'test' - payload = {'value':data} + feed = "test" + payload = {"value": data} response = requests.post( - "http://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data", + "http://io.adafruit.com/api/v2/" + + secrets["aio_username"] + + "/feeds/" + + feed + + "/data", json=payload, - headers={"X-AIO-KEY":secrets['aio_key']}) + headers={"X-AIO-KEY": secrets["aio_key"]}, + ) print(response.json()) response.close() counter = counter + 1 diff --git a/examples/wiznet5k_simpletest.py b/examples/wiznet5k_simpletest.py index 53797de..807945f 100644 --- a/examples/wiznet5k_simpletest.py +++ b/examples/wiznet5k_simpletest.py @@ -22,23 +22,25 @@ print("Chip Version:", eth.chip) print("MAC Address:", [hex(i) for i in eth.mac_address]) print("My IP address is:", eth.pretty_ip(eth.ip_address)) -print("IP lookup adafruit.com: %s" %eth.pretty_ip(eth.get_host_by_name("adafruit.com"))) +print( + "IP lookup adafruit.com: %s" % eth.pretty_ip(eth.get_host_by_name("adafruit.com")) +) -#eth._debug = True +# eth._debug = True print("Fetching text from", TEXT_URL) r = requests.get(TEXT_URL) -print('-'*40) +print("-" * 40) print(r.text) -print('-'*40) +print("-" * 40) r.close() print() print("Fetching json from", JSON_URL) r = requests.get(JSON_URL) -print('-'*40) +print("-" * 40) print(r.json()) -print('-'*40) +print("-" * 40) r.close() print("Done!") diff --git a/examples/wiznet5k_simpletest_manual_network.py b/examples/wiznet5k_simpletest_manual_network.py index 9b5dfe3..265da69 100644 --- a/examples/wiznet5k_simpletest_manual_network.py +++ b/examples/wiznet5k_simpletest_manual_network.py @@ -30,14 +30,16 @@ print("Chip Version:", eth.chip) print("MAC Address:", [hex(i) for i in eth.mac_address]) print("My IP address is:", eth.pretty_ip(eth.ip_address)) -print("IP lookup adafruit.com: %s" %eth.pretty_ip(eth.get_host_by_name("adafruit.com"))) +print( + "IP lookup adafruit.com: %s" % eth.pretty_ip(eth.get_host_by_name("adafruit.com")) +) -#eth._debug = True +# eth._debug = True print("Fetching text from", TEXT_URL) r = requests.get(TEXT_URL) -print('-'*40) +print("-" * 40) print(r.text) -print('-'*40) +print("-" * 40) r.close() print() diff --git a/setup.py b/setup.py index 35741a4..da9fdeb 100644 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ """ from setuptools import setup, find_packages + # To use a consistent encoding from codecs import open from os import path @@ -13,53 +14,41 @@ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file -with open(path.join(here, 'README.rst'), encoding='utf-8') as f: +with open(path.join(here, "README.rst"), encoding="utf-8") as f: long_description = f.read() setup( - name='adafruit-circuitpython-wiznet5k', - + name="adafruit-circuitpython-wiznet5k", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='Pure-Python interface for WIZNET 5k ethernet modules.', + setup_requires=["setuptools_scm"], + description="Pure-Python interface for WIZNET 5k ethernet modules.", long_description=long_description, - long_description_content_type='text/x-rst', - + long_description_content_type="text/x-rst", # The project's main homepage. - url='https://github.com/adafruit/Adafruit_CircuitPython_Wiznet5k', - + url="https://github.com/adafruit/Adafruit_CircuitPython_Wiznet5k", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=[ - 'Adafruit-Blinka', - 'adafruit-circuitpython-busdevice' - ], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice"], # Choose your license - license='MIT', - + license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries', - 'Topic :: System :: Hardware', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", ], - # What does your project relate to? - keywords='adafruit blinka circuitpython micropython wiznet5k ethernet, wiznet, w5500, ' - 'w5200, internet, iot', - + keywords="adafruit blinka circuitpython micropython wiznet5k ethernet, wiznet, w5500, " + "w5200, internet, iot", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=['adafruit_wiznet5k'], + py_modules=["adafruit_wiznet5k"], )