diff --git a/adafruit_wiznet5k/adafruit_wiznet5k.py b/adafruit_wiznet5k/adafruit_wiznet5k.py index 9bb1f57..a94581d 100644 --- a/adafruit_wiznet5k/adafruit_wiznet5k.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k.py @@ -52,97 +52,97 @@ import adafruit_wiznet5k.adafruit_wiznet5k_dns as dns # 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_VERSIONR_W5100S = const(0x0080) # W5100S Silicon Version -REG_SHAR = const(0x0009) # Source Hardware Address -REG_SIPR = const(0x000F) # Source IP Address -REG_PHYCFGR = const(0x002E) # W5500 PHY Configuration -REG_PHYCFGR_W5100S = const(0x003C) # W5100S 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_VERSIONR_W5100S = const(0x0080) # W5100S Silicon Version +_REG_SHAR = const(0x0009) # Source Hardware Address +_REG_SIPR = const(0x000F) # Source IP Address +_REG_PHYCFGR = const(0x002E) # W5500 PHY Configuration +_REG_PHYCFGR_W5100S = const(0x003C) # W5100S 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_INIT = const(0x13) SNSR_SOCK_LISTEN = const(0x14) -SNSR_SOCK_SYNSENT = const(0x15) +_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_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_SEND_KEEP = const(0x22) -CMD_SOCK_RECV = const(0x40) +_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) # 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) - -CH_SIZE = const(0x100) -SOCK_SIZE = const(0x800) # MAX W5k socket size -SOCK_MASK = const(0x7FF) +_SNIR_SEND_OK = const(0x10) +_SNIR_TIMEOUT = const(0x08) +_SNIR_RECV = const(0x04) +_SNIR_DISCON = const(0x02) +_SNIR_CON = const(0x01) + +_CH_SIZE = const(0x100) +_SOCK_SIZE = const(0x800) # MAX W5k socket size +_SOCK_MASK = const(0x7FF) # 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_CLOSE = const(0x00) +_SNMR_TCP = const(0x21) SNMR_UDP = const(0x02) -SNMR_IPRAW = const(0x03) -SNMR_MACRAW = const(0x04) -SNMR_PPPOE = const(0x05) +_SNMR_IPRAW = const(0x03) +_SNMR_MACRAW = const(0x04) +_SNMR_PPPOE = const(0x05) -MAX_PACKET = const(4000) -LOCAL_PORT = const(0x400) +_MAX_PACKET = const(4000) +_LOCAL_PORT = const(0x400) # Default hardware MAC address -DEFAULT_MAC = (0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED) +_DEFAULT_MAC = (0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED) # Maximum number of sockets to support, differs between chip versions. -W5200_W5500_MAX_SOCK_NUM = const(0x08) -W5100_MAX_SOCK_NUM = const(0x04) -SOCKET_INVALID = const(255) +_W5200_W5500_MAX_SOCK_NUM = const(0x08) +_W5100_MAX_SOCK_NUM = const(0x04) +_SOCKET_INVALID = const(255) # Source ports in use -SRC_PORTS = [0] * W5200_W5500_MAX_SOCK_NUM +_SRC_PORTS = [0] * _W5200_W5500_MAX_SOCK_NUM class WIZNET5K: # pylint: disable=too-many-public-methods, too-many-instance-attributes """Interface for WIZNET5K module.""" - TCP_MODE = const(0x21) - UDP_MODE = const(0x02) - TLS_MODE = const(0x03) # This is NOT currently implemented + _TCP_MODE = const(0x21) + _UDP_MODE = const(0x02) + _TLS_MODE = const(0x03) # This is NOT currently implemented # pylint: disable=too-many-arguments def __init__( @@ -151,7 +151,7 @@ def __init__( cs: digitalio.DigitalInOut, # pylint: disable=invalid-name reset: Optional[digitalio.DigitalInOut] = None, is_dhcp: bool = True, - mac: Union[List[int], Tuple[int]] = DEFAULT_MAC, + mac: Union[List[int], Tuple[int]] = _DEFAULT_MAC, hostname: Optional[str] = None, dhcp_timeout: float = 30.0, debug: bool = False, @@ -183,7 +183,7 @@ def __init__( # Buffer for reading params from module self._pbuff = bytearray(8) - self._rxbuf = bytearray(MAX_PACKET) + self._rxbuf = bytearray(_MAX_PACKET) # attempt to initialize the module self._ch_base_msb = 0 @@ -286,9 +286,9 @@ def max_sockets(self) -> int: :return int: Maximum supported sockets. """ if self._chip_type == "w5500": - return W5200_W5500_MAX_SOCK_NUM + return _W5200_W5500_MAX_SOCK_NUM if self._chip_type == "w5100s": - return W5100_MAX_SOCK_NUM + return _W5100_MAX_SOCK_NUM return -1 @property @@ -307,7 +307,7 @@ def ip_address(self) -> bytearray: :return bytearray: IP address as four bytes. """ - return self.read(REG_SIPR, 0x00, 4) + return self.read(_REG_SIPR, 0x00, 4) def pretty_ip( self, @@ -344,7 +344,7 @@ def mac_address(self) -> bytearray: Ethernet hardware's MAC address. :return bytearray: Six byte MAC address.""" - return self.read(REG_SHAR, 0x00, 6) + return self.read(_REG_SHAR, 0x00, 6) @mac_address.setter def mac_address(self, address: Sequence[Union[int, bytes]]) -> None: @@ -353,7 +353,7 @@ def mac_address(self, address: Sequence[Union[int, bytes]]) -> None: :param tuple address: Hardware MAC address. """ - self.write(REG_SHAR, 0x04, address) + self.write(_REG_SHAR, 0x04, address) def pretty_mac( self, @@ -387,7 +387,7 @@ def remote_ip(self, socket_num: int) -> Union[str, bytearray]: 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 @@ -397,10 +397,10 @@ def link_status(self) -> int: :return int: 1 if the link is up, 0 if the link is down. """ if self._chip_type == "w5500": - data = self.read(REG_PHYCFGR, 0x00) + data = self.read(_REG_PHYCFGR, 0x00) return data[0] & 0x01 if self._chip_type == "w5100s": - data = self.read(REG_PHYCFGR_W5100S, 0x00) + data = self.read(_REG_PHYCFGR_W5100S, 0x00) return data[0] & 0x01 return 0 @@ -415,7 +415,7 @@ def remote_port(self, socket_num: int) -> Union[int, bytearray]: if socket_num >= self.max_sockets: return self._pbuff for octet in range(2): - self._pbuff[octet] = self._read_socket(socket_num, REG_SNDPORT + octet)[0] + self._pbuff[octet] = self._read_socket(socket_num, _REG_SNDPORT + octet)[0] return int((self._pbuff[0] << 8) | self._pbuff[0]) @property @@ -429,8 +429,8 @@ def ifconfig( The IP address, subnet mask, gateway address and DNS server address.""" return ( self.ip_address, - self.read(REG_SUBR, 0x00, 4), - self.read(REG_GAR, 0x00, 4), + self.read(_REG_SUBR, 0x00, 4), + self.read(_REG_GAR, 0x00, 4), self._dns, ) @@ -446,9 +446,9 @@ def ifconfig( """ ip_address, subnet_mask, gateway_address, dns_server = params - self.write(REG_SIPR, 0x04, ip_address) - self.write(REG_SUBR, 0x04, subnet_mask) - self.write(REG_GAR, 0x04, gateway_address) + self.write(_REG_SIPR, 0x04, ip_address) + self.write(_REG_SUBR, 0x04, subnet_mask) + self.write(_REG_GAR, 0x04, gateway_address) self._dns = dns_server @@ -483,7 +483,7 @@ def _detect_and_reset_w5500() -> bool: if self._read_mr()[0] != 0x00: return False - if self.read(REG_VERSIONR_W5500, 0x00)[0] != 0x04: + if self.read(_REG_VERSIONR_W5500, 0x00)[0] != 0x04: return False # self._chip_type = "w5500" # self._ch_base_msb = 0x10 @@ -499,7 +499,7 @@ def _detect_and_reset_w5100s() -> bool: self._chip_type = "w5100s" # sw reset assert self.sw_reset() == 0, "Chip not reset properly!" - if self.read(REG_VERSIONR_W5100S, 0x00)[0] != 0x51: + if self.read(_REG_VERSIONR_W5100S, 0x00)[0] != 0x51: return False self._ch_base_msb = 0x0400 @@ -512,7 +512,7 @@ def _detect_and_reset_w5100s() -> bool: # Detect if chip is Wiznet W5500 if _detect_and_reset_w5500(): # perform w5500 initialization - for i in range(0, W5200_W5500_MAX_SOCK_NUM): + for i in range(0, _W5200_W5500_MAX_SOCK_NUM): ctrl_byte = 0x0C + (i << 5) self.write(0x1E, ctrl_byte, 2) self.write(0x1F, ctrl_byte, 2) @@ -542,12 +542,12 @@ def sw_reset(self) -> int: def _read_mr(self) -> bytearray: """Read from the Mode Register (MR).""" - res = self.read(REG_MR, 0x00) + res = self.read(_REG_MR, 0x00) return res def _write_mr(self, data: int) -> None: """Write to the mode register (MR).""" - self.write(REG_MR, 0x04, data) + self.write(_REG_MR, 0x04, data) def read( self, @@ -613,7 +613,7 @@ def write( # Socket-Register API - def socket_available(self, socket_num: int, sock_type: int = SNMR_TCP) -> int: + def socket_available(self, socket_num: int, sock_type: int = _SNMR_TCP) -> int: """ Number of bytes available to be read from the socket. @@ -634,7 +634,7 @@ def socket_available(self, socket_num: int, sock_type: int = SNMR_TCP) -> int: res = self._get_rx_rcv_size(socket_num) - if sock_type == SNMR_TCP: + if sock_type == _SNMR_TCP: return res if res > 0: if self.udp_datasize[socket_num]: @@ -670,7 +670,7 @@ def socket_connect( socket_num: int, dest: Union[bytes, bytearray], port: int, - conn_mode: int = SNMR_TCP, + conn_mode: int = _SNMR_TCP, ) -> int: """ Open and verify a connection from a socket to a destination IP address @@ -699,9 +699,9 @@ def socket_connect( # set socket destination IP and port self._write_sndipr(socket_num, dest) self._write_sndport(socket_num, port) - self._send_socket_cmd(socket_num, CMD_SOCK_CONNECT) + self._send_socket_cmd(socket_num, _CMD_SOCK_CONNECT) - if conn_mode == SNMR_TCP: + if conn_mode == _SNMR_TCP: # wait for tcp connection establishment while self.socket_status(socket_num)[0] != SNSR_SOCK_ESTABLISHED: time.sleep(0.001) @@ -730,7 +730,7 @@ def get_socket(self) -> int: if self._debug: print("*** Get socket") - sock = SOCKET_INVALID + sock = _SOCKET_INVALID for _sock in range(self.max_sockets): status = self.socket_status(_sock)[0] if status == SNSR_SOCK_CLOSED: @@ -742,7 +742,7 @@ def get_socket(self) -> int: return sock def socket_listen( - self, socket_num: int, port: int, conn_mode: int = SNMR_TCP + self, socket_num: int, port: int, conn_mode: int = _SNMR_TCP ) -> None: """ Listen on a socket's port. @@ -767,10 +767,14 @@ def socket_listen( if res == 1: raise RuntimeError("Failed to initialize the socket.") # Send listen command - self._send_socket_cmd(socket_num, CMD_SOCK_LISTEN) + self._send_socket_cmd(socket_num, _CMD_SOCK_LISTEN) # Wait until ready status = [SNSR_SOCK_CLOSED] - while status[0] not in (SNSR_SOCK_LISTEN, SNSR_SOCK_ESTABLISHED, SNSR_SOCK_UDP): + while status[0] not in ( + SNSR_SOCK_LISTEN, + SNSR_SOCK_ESTABLISHED, + _SNSR_SOCK_UDP, + ): status = self._read_snsr(socket_num) if status[0] == SNSR_SOCK_CLOSED: raise RuntimeError("Listening socket closed.") @@ -802,7 +806,7 @@ def socket_accept( ) return next_socknum, (dest_ip, dest_port) - def socket_open(self, socket_num: int, conn_mode: int = SNMR_TCP) -> int: + def socket_open(self, socket_num: int, conn_mode: int = _SNMR_TCP) -> int: """ Open an IP socket. @@ -820,11 +824,11 @@ def socket_open(self, socket_num: int, conn_mode: int = SNMR_TCP) -> int: status = self._read_snsr(socket_num)[0] if status in ( SNSR_SOCK_CLOSED, - SNSR_SOCK_TIME_WAIT, + _SNSR_SOCK_TIME_WAIT, SNSR_SOCK_FIN_WAIT, - SNSR_SOCK_CLOSE_WAIT, - SNSR_SOCK_CLOSING, - SNSR_SOCK_UDP, + _SNSR_SOCK_CLOSE_WAIT, + _SNSR_SOCK_CLOSING, + _SNSR_SOCK_UDP, ): if self._debug: print("* Opening W5k Socket, protocol={}".format(conn_mode)) @@ -838,13 +842,13 @@ def socket_open(self, socket_num: int, conn_mode: int = SNMR_TCP) -> int: self._write_sock_port(socket_num, self.src_port) else: s_port = randint(49152, 65535) - while s_port in SRC_PORTS: + while s_port in _SRC_PORTS: s_port = randint(49152, 65535) self._write_sock_port(socket_num, s_port) - SRC_PORTS[socket_num] = s_port + _SRC_PORTS[socket_num] = s_port # open socket - self._write_sncr(socket_num, CMD_SOCK_OPEN) + self._write_sncr(socket_num, _CMD_SOCK_OPEN) self._read_sncr(socket_num) if self._read_snsr((socket_num))[0] not in [0x13, 0x22]: raise RuntimeError("Could not open socket in TCP or UDP mode.") @@ -859,7 +863,7 @@ def socket_close(self, socket_num: int) -> None: """ if self._debug: print("*** Closing socket #%d" % socket_num) - self._write_sncr(socket_num, CMD_SOCK_CLOSE) + self._write_sncr(socket_num, _CMD_SOCK_CLOSE) self._read_sncr(socket_num) def socket_disconnect(self, socket_num: int) -> None: @@ -870,7 +874,7 @@ def socket_disconnect(self, socket_num: int) -> None: """ if self._debug: print("*** Disconnecting socket #%d" % socket_num) - self._write_sncr(socket_num, CMD_SOCK_DISCON) + self._write_sncr(socket_num, _CMD_SOCK_DISCON) self._read_sncr(socket_num) def socket_read( # pylint: disable=too-many-branches @@ -900,7 +904,7 @@ def socket_read( # pylint: disable=too-many-branches 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 @@ -925,13 +929,13 @@ def socket_read( # pylint: disable=too-many-branches resp = self.read(ptr, ctrl_byte, ret) else: # if self._chip_type == "w5100s": - offset = ptr & SOCK_MASK - src_addr = offset + (socket_num * SOCK_SIZE + 0x6000) - if offset + ret > SOCK_SIZE: - size = SOCK_SIZE - offset + offset = ptr & _SOCK_MASK + src_addr = offset + (socket_num * _SOCK_SIZE + 0x6000) + if offset + ret > _SOCK_SIZE: + size = _SOCK_SIZE - offset resp1 = self.read(src_addr, 0x00, size) size = ret - size - src_addr = socket_num * SOCK_SIZE + 0x6000 + src_addr = socket_num * _SOCK_SIZE + 0x6000 resp2 = self.read(src_addr, 0x00, size) resp = resp1 + resp2 else: @@ -943,7 +947,7 @@ def socket_read( # pylint: disable=too-many-branches self._write_snrx_rd(socket_num, ptr) # Notify the W5k of the updated Sn_Rx_RD - self._write_sncr(socket_num, CMD_SOCK_RECV) + self._write_sncr(socket_num, _CMD_SOCK_RECV) self._read_sncr(socket_num) return ret, resp @@ -990,8 +994,8 @@ def socket_write( status = 0 ret = 0 free_size = 0 - if len(buffer) > SOCK_SIZE: - ret = SOCK_SIZE + if len(buffer) > _SOCK_SIZE: + ret = _SOCK_SIZE else: ret = len(buffer) stamp = time.monotonic() @@ -1001,7 +1005,7 @@ def socket_write( while free_size < ret: free_size = self._get_tx_free_size(socket_num) status = self.socket_status(socket_num)[0] - if status not in (SNSR_SOCK_ESTABLISHED, SNSR_SOCK_CLOSE_WAIT) or ( + if status not in (SNSR_SOCK_ESTABLISHED, _SNSR_SOCK_CLOSE_WAIT) or ( timeout and time.monotonic() - stamp > timeout ): ret = 0 @@ -1009,9 +1013,9 @@ def socket_write( # Read the starting address for saving the transmitting data. ptr = self._read_sntx_wr(socket_num) - offset = ptr & SOCK_MASK + offset = ptr & _SOCK_MASK if self._chip_type == "w5500": - dst_addr = offset + (socket_num * SOCK_SIZE + 0x8000) + dst_addr = offset + (socket_num * _SOCK_SIZE + 0x8000) txbuf = buffer[:ret] cntl_byte = 0x14 + (socket_num << 5) @@ -1019,15 +1023,15 @@ def socket_write( else: # if self._chip_type == "w5100s": - dst_addr = offset + (socket_num * SOCK_SIZE + 0x4000) + dst_addr = offset + (socket_num * _SOCK_SIZE + 0x4000) - if offset + ret > SOCK_SIZE: - size = SOCK_SIZE - offset + if offset + ret > _SOCK_SIZE: + size = _SOCK_SIZE - offset txbuf = buffer[0:size] self.write(dst_addr, 0x00, txbuf) txbuf = buffer[size:ret] size = ret - size - dst_addr = socket_num * SOCK_SIZE + 0x4000 + dst_addr = socket_num * _SOCK_SIZE + 0x4000 self.write(dst_addr, 0x00, txbuf) else: txbuf = buffer[:ret] @@ -1037,25 +1041,25 @@ def socket_write( ptr = (ptr + ret) & 0xFFFF self._write_sntx_wr(socket_num, ptr) - self._write_sncr(socket_num, CMD_SOCK_SEND) + 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: + self._read_socket(socket_num, _REG_SNIR)[0] & _SNIR_SEND_OK + ) != _SNIR_SEND_OK: if self.socket_status(socket_num)[0] in ( SNSR_SOCK_CLOSED, - SNSR_SOCK_TIME_WAIT, + _SNSR_SOCK_TIME_WAIT, SNSR_SOCK_FIN_WAIT, - SNSR_SOCK_CLOSE_WAIT, - SNSR_SOCK_CLOSING, + _SNSR_SOCK_CLOSE_WAIT, + _SNSR_SOCK_CLOSING, ) or (timeout and time.monotonic() - stamp > timeout): # self.socket_close(socket_num) return 0 time.sleep(0.01) - self._write_snir(socket_num, SNIR_SEND_OK) + self._write_snir(socket_num, _SNIR_SEND_OK) return ret # Socket-Register Methods @@ -1080,17 +1084,17 @@ def _get_tx_free_size(self, sock: int) -> int: return int.from_bytes(val, "big") def _read_snrx_rd(self, sock: int) -> int: - 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[0] = self._read_socket(sock, _REG_SNRX_RD)[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: int, data: int) -> None: - self._write_socket(sock, REG_SNRX_RD, data >> 8 & 0xFF) - self._write_socket(sock, REG_SNRX_RD + 1, data & 0xFF) + self._write_socket(sock, _REG_SNRX_RD, data >> 8 & 0xFF) + self._write_socket(sock, _REG_SNRX_RD + 1, data & 0xFF) def _write_sntx_wr(self, sock: int, data: int) -> None: - self._write_socket(sock, REG_SNTX_WR, data >> 8 & 0xFF) - self._write_socket(sock, REG_SNTX_WR + 1, data & 0xFF) + self._write_socket(sock, _REG_SNTX_WR, data >> 8 & 0xFF) + self._write_socket(sock, _REG_SNTX_WR + 1, data & 0xFF) def _read_sntx_wr(self, sock: int) -> int: self._pbuff[0] = self._read_socket(sock, 0x0024)[0] @@ -1098,50 +1102,50 @@ def _read_sntx_wr(self, sock: int) -> int: return self._pbuff[0] << 8 | self._pbuff[1] def _read_sntx_fsr(self, sock: int) -> Optional[bytearray]: - 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) + data += self._read_socket(sock, _REG_SNTX_FSR + 1) return data def _read_snrx_rsr(self, sock: int) -> Optional[bytearray]: - 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) + data += self._read_socket(sock, _REG_SNRX_RSR + 1) return data def _write_sndipr(self, sock: int, ip_addr: bytearray) -> None: """Write to socket destination IP Address.""" 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: int, port: int) -> None: """Write 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, port >> 8) + self._write_socket(sock, _REG_SNDPORT + 1, port & 0xFF) def _read_snsr(self, sock: int) -> Optional[bytearray]: """Read Socket n Status Register.""" - return self._read_socket(sock, REG_SNSR) + return self._read_socket(sock, _REG_SNSR) def _write_snmr(self, sock: int, protocol: int) -> None: """Write to Socket n Mode Register.""" - self._write_socket(sock, REG_SNMR, protocol) + self._write_socket(sock, _REG_SNMR, protocol) def _write_snir(self, sock: int, data: int) -> None: """Write to Socket n Interrupt Register.""" - self._write_socket(sock, REG_SNIR, data) + self._write_socket(sock, _REG_SNIR, data) def _write_sock_port(self, sock: int, port: int) -> None: """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, port >> 8) + self._write_socket(sock, _REG_SNPORT + 1, port & 0xFF) def _write_sncr(self, sock: int, data: int) -> None: - self._write_socket(sock, REG_SNCR, data) + self._write_socket(sock, _REG_SNCR, data) def _read_sncr(self, sock: int) -> Optional[bytearray]: - return self._read_socket(sock, REG_SNCR) + return self._read_socket(sock, _REG_SNCR) def _read_snmr(self, sock: int) -> Optional[bytearray]: - return self._read_socket(sock, REG_SNMR) + return self._read_socket(sock, _REG_SNMR) def _write_socket(self, sock: int, address: int, data: int) -> None: """Write to a W5k socket register.""" @@ -1151,7 +1155,7 @@ def _write_socket(self, sock: int, address: int, data: int) -> None: if self._chip_type == "w5100s": cntl_byte = 0 return self.write( - self._ch_base_msb + sock * CH_SIZE + address, cntl_byte, data + self._ch_base_msb + sock * _CH_SIZE + address, cntl_byte, data ) return None @@ -1162,5 +1166,5 @@ def _read_socket(self, sock: int, address: int) -> Optional[bytearray]: return self.read(address, cntl_byte) if self._chip_type == "w5100s": cntl_byte = 0 - return self.read(self._ch_base_msb + sock * CH_SIZE + address, cntl_byte) + return self.read(self._ch_base_msb + sock * _CH_SIZE + address, cntl_byte) return None diff --git a/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py b/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py index 864214c..5009594 100644 --- a/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py @@ -33,57 +33,57 @@ # 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_REREQUEST = const(0x04) -STATE_DHCP_RELEASE = const(0x05) -STATE_DHCP_WAIT = const(0x06) -STATE_DHCP_DISCONN = const(0x07) +_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_WAIT = const(0x06) +_STATE_DHCP_DISCONN = const(0x07) # DHCP wait time between attempts -DHCP_WAIT_TIME = const(60) +_DHCP_WAIT_TIME = const(60) # 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_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 Message OP Codes -DHCP_BOOT_REQUEST = const(0x01) -DHCP_BOOT_REPLY = const(0x02) +_DHCP_BOOT_REQUEST = const(0x01) +_DHCP_BOOT_REPLY = const(0x02) -DHCP_HTYPE10MB = const(0x01) -DHCP_HTYPE100MB = const(0x02) +_DHCP_HTYPE10MB = const(0x01) +_DHCP_HTYPE100MB = const(0x02) -DHCP_HLENETHERNET = const(0x06) -DHCP_HOPS = const(0x00) +_DHCP_HLENETHERNET = const(0x06) +_DHCP_HOPS = const(0x00) -MAGIC_COOKIE = b"c\x82Sc" # Four bytes 99.130.83.99 -MAX_DHCP_OPT = const(0x10) +_MAGIC_COOKIE = b"c\x82Sc" # Four bytes 99.130.83.99 +_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) +_DEFAULT_LEASE_TIME = const(900) +_BROADCAST_SERVER_ADDR = (255, 255, 255, 255) # DHCP Response Options -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 +_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 # Packet buffer _BUFF = bytearray(318) @@ -123,13 +123,13 @@ def __init__( self._sock = None # DHCP state machine - self._dhcp_state = STATE_DHCP_START + self._dhcp_state = _STATE_DHCP_START self._initial_xid = 0 self._transaction_id = 0 self._start_time = 0 # DHCP server configuration - self.dhcp_server_ip = BROADCAST_SERVER_ADDR + self.dhcp_server_ip = _BROADCAST_SERVER_ADDR self.local_ip = 0 self.gateway_ip = 0 self.subnet_mask = 0 @@ -168,13 +168,13 @@ def send_dhcp_message( """ _BUFF[:] = b"\x00" * len(_BUFF) # OP - _BUFF[0] = DHCP_BOOT_REQUEST + _BUFF[0] = _DHCP_BOOT_REQUEST # HTYPE - _BUFF[1] = DHCP_HTYPE10MB + _BUFF[1] = _DHCP_HTYPE10MB # HLEN - _BUFF[2] = DHCP_HLENETHERNET + _BUFF[2] = _DHCP_HLENETHERNET # HOPS - _BUFF[3] = DHCP_HOPS + _BUFF[3] = _DHCP_HOPS # Transaction ID (xid) self._initial_xid = htonl(self._transaction_id) @@ -203,7 +203,7 @@ def send_dhcp_message( # NOTE: 192 octets of 0's, BOOTP legacy # Magic Cookie - _BUFF[236:240] = MAGIC_COOKIE + _BUFF[236:240] = _MAGIC_COOKIE # Option - DHCP Message Type _BUFF[240] = 53 @@ -227,7 +227,7 @@ def send_dhcp_message( _BUFF[253] = hostname_len _BUFF[254:after_hostname] = self._hostname - if state == DHCP_REQUEST and not renew: + if state == _DHCP_REQUEST and not renew: # Set the parsed local IP addr _BUFF[after_hostname] = 50 _BUFF[after_hostname + 1] = 0x04 @@ -271,7 +271,7 @@ def parse_dhcp_response( # -- Parse Packet, FIXED -- # # Validate OP - if _BUFF[0] != DHCP_BOOT_REPLY: + if _BUFF[0] != _DHCP_BOOT_REPLY: raise RuntimeError( "Malformed Packet - \ DHCP message OP is not expected BOOT Reply." @@ -286,55 +286,55 @@ def parse_dhcp_response( if _BUFF[28:34] == b"\x00\x00\x00\x00\x00\x00": raise ValueError("No DHCP server ID in the response.") - if _BUFF[236:240] != MAGIC_COOKIE: + if _BUFF[236:240] != _MAGIC_COOKIE: raise ValueError("No DHCP Magic Cookie in the response.") # -- Parse Packet, VARIABLE -- # ptr = 240 - while _BUFF[ptr] != OPT_END: - if _BUFF[ptr] == MSG_TYPE: + while _BUFF[ptr] != _OPT_END: + if _BUFF[ptr] == _MSG_TYPE: ptr += 1 opt_len = _BUFF[ptr] ptr += opt_len msg_type = _BUFF[ptr] ptr += 1 - elif _BUFF[ptr] == SUBNET_MASK: + elif _BUFF[ptr] == _SUBNET_MASK: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 self.subnet_mask = tuple(_BUFF[ptr : ptr + opt_len]) ptr += opt_len - elif _BUFF[ptr] == DHCP_SERVER_ID: + elif _BUFF[ptr] == _DHCP_SERVER_ID: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 self.dhcp_server_ip = tuple(_BUFF[ptr : ptr + opt_len]) ptr += opt_len - elif _BUFF[ptr] == LEASE_TIME: + elif _BUFF[ptr] == _LEASE_TIME: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 self._lease_time = int.from_bytes(_BUFF[ptr : ptr + opt_len], "big") ptr += opt_len - elif _BUFF[ptr] == ROUTERS_ON_SUBNET: + elif _BUFF[ptr] == _ROUTERS_ON_SUBNET: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 self.gateway_ip = tuple(_BUFF[ptr : ptr + 4]) - ptr += opt_len # still increment even though we only read 1 addr. - elif _BUFF[ptr] == DNS_SERVERS: + ptr += opt_len + elif _BUFF[ptr] == _DNS_SERVERS: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 self.dns_server_ip = tuple(_BUFF[ptr : ptr + 4]) ptr += opt_len # still increment even though we only read 1 addr. - elif _BUFF[ptr] == T1_VAL: + elif _BUFF[ptr] == _T1_VAL: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 self._t1 = int.from_bytes(_BUFF[ptr : ptr + opt_len], "big") ptr += opt_len - elif _BUFF[ptr] == T2_VAL: + elif _BUFF[ptr] == _T2_VAL: ptr += 1 opt_len = _BUFF[ptr] ptr += 1 @@ -377,12 +377,12 @@ def _dhcp_state_machine(self) -> None: the non-blocking DHCP maintenance function. """ if self._eth.link_status: - if self._dhcp_state == STATE_DHCP_DISCONN: - self._dhcp_state = STATE_DHCP_START + if self._dhcp_state == _STATE_DHCP_DISCONN: + self._dhcp_state = _STATE_DHCP_START else: - if self._dhcp_state != STATE_DHCP_DISCONN: - self._dhcp_state = STATE_DHCP_DISCONN - self.dhcp_server_ip = BROADCAST_SERVER_ADDR + if self._dhcp_state != _STATE_DHCP_DISCONN: + self._dhcp_state = _STATE_DHCP_DISCONN + self.dhcp_server_ip = _BROADCAST_SERVER_ADDR self._last_lease_time = 0 reset_ip = (0, 0, 0, 0) self._eth.ifconfig = (reset_ip, reset_ip, reset_ip, reset_ip) @@ -390,7 +390,7 @@ def _dhcp_state_machine(self) -> None: self._sock.close() self._sock = None - if self._dhcp_state == STATE_DHCP_START: + if self._dhcp_state == _STATE_DHCP_START: self._start_time = time.monotonic() self._transaction_id = (self._transaction_id + 1) & 0x7FFFFFFF try: @@ -398,29 +398,29 @@ def _dhcp_state_machine(self) -> None: except RuntimeError: if self._debug: print("* DHCP: Failed to allocate socket") - self._dhcp_state = STATE_DHCP_WAIT + self._dhcp_state = _STATE_DHCP_WAIT else: self._sock.settimeout(self._response_timeout) self._sock.bind((None, 68)) - self._sock.connect((self.dhcp_server_ip, DHCP_SERVER_PORT)) + self._sock.connect((self.dhcp_server_ip, _DHCP_SERVER_PORT)) if self._last_lease_time == 0 or time.monotonic() > ( self._last_lease_time + self._lease_time ): if self._debug: print("* DHCP: Send discover to {}".format(self.dhcp_server_ip)) self.send_dhcp_message( - STATE_DHCP_DISCOVER, (time.monotonic() - self._start_time) + _STATE_DHCP_DISCOVER, (time.monotonic() - self._start_time) ) - self._dhcp_state = STATE_DHCP_DISCOVER + self._dhcp_state = _STATE_DHCP_DISCOVER else: if self._debug: print("* DHCP: Send request to {}".format(self.dhcp_server_ip)) self.send_dhcp_message( - DHCP_REQUEST, (time.monotonic() - self._start_time), True + _DHCP_REQUEST, (time.monotonic() - self._start_time), True ) - self._dhcp_state = STATE_DHCP_REQUEST + self._dhcp_state = _STATE_DHCP_REQUEST - elif self._dhcp_state == STATE_DHCP_DISCOVER: + elif self._dhcp_state == _STATE_DHCP_DISCOVER: if self._sock.available(): if self._debug: print("* DHCP: Parsing OFFER") @@ -430,7 +430,7 @@ def _dhcp_state_machine(self) -> None: if self._debug: print(error) else: - if msg_type == DHCP_OFFER: + if msg_type == _DHCP_OFFER: # Check if transaction ID matches, otherwise it may be an offer # for another device if htonl(self._transaction_id) == int.from_bytes(xid, "big"): @@ -444,9 +444,9 @@ def _dhcp_state_machine(self) -> None: self._transaction_id + 1 ) & 0x7FFFFFFF self.send_dhcp_message( - DHCP_REQUEST, (time.monotonic() - self._start_time) + _DHCP_REQUEST, (time.monotonic() - self._start_time) ) - self._dhcp_state = STATE_DHCP_REQUEST + self._dhcp_state = _STATE_DHCP_REQUEST else: if self._debug: print("* DHCP: Received OFFER with non-matching xid") @@ -454,7 +454,7 @@ def _dhcp_state_machine(self) -> None: if self._debug: print("* DHCP: Received DHCP Message is not OFFER") - elif self._dhcp_state == STATE_DHCP_REQUEST: + elif self._dhcp_state == _STATE_DHCP_REQUEST: if self._sock.available(): if self._debug: print("* DHCP: Parsing ACK") @@ -467,15 +467,15 @@ def _dhcp_state_machine(self) -> None: # Check if transaction ID matches, otherwise it may be # for another device if htonl(self._transaction_id) == int.from_bytes(xid, "big"): - if msg_type == DHCP_ACK: + if msg_type == _DHCP_ACK: if self._debug: print("* DHCP: Successful lease") self._sock.close() self._sock = None - self._dhcp_state = STATE_DHCP_LEASED + self._dhcp_state = _STATE_DHCP_LEASED self._last_lease_time = self._start_time if self._lease_time == 0: - self._lease_time = DEFAULT_LEASE_TIME + self._lease_time = _DEFAULT_LEASE_TIME if self._t1 == 0: # T1 is 50% of _lease_time self._t1 = self._lease_time >> 1 @@ -498,41 +498,41 @@ def _dhcp_state_machine(self) -> None: if self._debug: print("* DHCP: Received non-matching xid") - elif self._dhcp_state == STATE_DHCP_WAIT: - if time.monotonic() > (self._start_time + DHCP_WAIT_TIME): + elif self._dhcp_state == _STATE_DHCP_WAIT: + if time.monotonic() > (self._start_time + _DHCP_WAIT_TIME): if self._debug: print("* DHCP: Begin retry") - self._dhcp_state = STATE_DHCP_START + self._dhcp_state = _STATE_DHCP_START if time.monotonic() > (self._last_lease_time + self._rebind_in_sec): - self.dhcp_server_ip = BROADCAST_SERVER_ADDR + self.dhcp_server_ip = _BROADCAST_SERVER_ADDR if time.monotonic() > (self._last_lease_time + self._lease_time): reset_ip = (0, 0, 0, 0) self._eth.ifconfig = (reset_ip, reset_ip, reset_ip, reset_ip) - elif self._dhcp_state == STATE_DHCP_LEASED: + elif self._dhcp_state == _STATE_DHCP_LEASED: if time.monotonic() > (self._last_lease_time + self._renew_in_sec): - self._dhcp_state = STATE_DHCP_START + self._dhcp_state = _STATE_DHCP_START if self._debug: print("* DHCP: Time to renew lease") if self._dhcp_state in ( - STATE_DHCP_DISCOVER, - STATE_DHCP_REQUEST, + _STATE_DHCP_DISCOVER, + _STATE_DHCP_REQUEST, ) and time.monotonic() > (self._start_time + self._response_timeout): - self._dhcp_state = STATE_DHCP_WAIT + self._dhcp_state = _STATE_DHCP_WAIT if self._sock is not None: self._sock.close() self._sock = None def request_dhcp_lease(self) -> bool: """Request to renew or acquire a DHCP lease.""" - if self._dhcp_state in (STATE_DHCP_LEASED, STATE_DHCP_WAIT): - self._dhcp_state = STATE_DHCP_START + if self._dhcp_state in (_STATE_DHCP_LEASED, _STATE_DHCP_WAIT): + self._dhcp_state = _STATE_DHCP_START - while self._dhcp_state not in (STATE_DHCP_LEASED, STATE_DHCP_WAIT): + while self._dhcp_state not in (_STATE_DHCP_LEASED, _STATE_DHCP_WAIT): self._dhcp_state_machine() - return self._dhcp_state == STATE_DHCP_LEASED + return self._dhcp_state == _STATE_DHCP_LEASED def maintain_dhcp_lease(self) -> None: """Maintain DHCP lease""" diff --git a/adafruit_wiznet5k/adafruit_wiznet5k_dns.py b/adafruit_wiznet5k/adafruit_wiznet5k_dns.py index efe1a10..2359ba7 100644 --- a/adafruit_wiznet5k/adafruit_wiznet5k_dns.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k_dns.py @@ -29,22 +29,22 @@ import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket from adafruit_wiznet5k.adafruit_wiznet5k_socket import htons -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) -CLASS_IN = const(0x0001) -DATA_LEN = const(0x0004) +_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) -INVALID_RESPONSE = const(-4) +_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 class DNS: @@ -81,15 +81,15 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]: :return Union[int, bytes] The IPv4 address if successful, -1 otherwise. """ if self._dns_server is None: - return INVALID_SERVER + return _INVALID_SERVER self._host = hostname # build DNS request packet self._build_dns_header() self._build_dns_question() # Send DNS request packet - self._sock.bind((None, DNS_PORT)) - self._sock.connect((self._dns_server, DNS_PORT)) + self._sock.bind((None, _DNS_PORT)) + self._sock.connect((self._dns_server, _DNS_PORT)) if self._debug: print("* DNS: Sending request packet...") self._sock.send(self._pkt_buf) @@ -176,7 +176,7 @@ def _parse_dns_response( # Validate Query is Type A q_type = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "big") - if not q_type == TYPE_A: + if not q_type == _TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Query Type: ", q_type) return -1 @@ -184,7 +184,7 @@ def _parse_dns_response( # Validate Query is Type A q_class = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "big") - if not q_class == TYPE_A: + if not q_class == _TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Query Class: ", q_class) return -1 @@ -201,7 +201,7 @@ def _parse_dns_response( # Validate Answer Type A ans_type = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "big") - if not ans_type == TYPE_A: + if not ans_type == _TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Answer Type: ", ans_type) return -1 @@ -209,7 +209,7 @@ def _parse_dns_response( # Validate Answer Class IN ans_class = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "big") - if not ans_class == TYPE_A: + if not ans_class == _TYPE_A: if self._debug: print("* DNS ERROR: Incorrect Answer Class: ", ans_class) return -1 @@ -220,7 +220,7 @@ def _parse_dns_response( # Validate addr is IPv4 data_len = int.from_bytes(self._pkt_buf[ptr : ptr + 2], "big") - if not data_len == DATA_LEN: + if not data_len == _DATA_LEN: if self._debug: print("* DNS ERROR: Unexpected Data Length: ", data_len) return -1 @@ -267,8 +267,8 @@ def _build_dns_question(self) -> None: # end of the name self._pkt_buf.append(0x00) # Type A record - self._pkt_buf.append(htons(TYPE_A) & 0xFF) - self._pkt_buf.append(htons(TYPE_A) >> 8) + self._pkt_buf.append(htons(_TYPE_A) & 0xFF) + self._pkt_buf.append(htons(_TYPE_A) >> 8) # Class IN - self._pkt_buf.append(htons(CLASS_IN) & 0xFF) - self._pkt_buf.append(htons(CLASS_IN) >> 8) + self._pkt_buf.append(htons(_CLASS_IN) & 0xFF) + self._pkt_buf.append(htons(_CLASS_IN) >> 8) diff --git a/adafruit_wiznet5k/adafruit_wiznet5k_socket.py b/adafruit_wiznet5k/adafruit_wiznet5k_socket.py index b34cb08..ad327c7 100644 --- a/adafruit_wiznet5k/adafruit_wiznet5k_socket.py +++ b/adafruit_wiznet5k/adafruit_wiznet5k_socket.py @@ -70,10 +70,10 @@ def htons(x: int) -> int: SOCK_STREAM = const(0x21) # TCP -TCP_MODE = 80 +_TCP_MODE = 80 SOCK_DGRAM = const(0x02) # UDP AF_INET = const(3) -SOCKET_INVALID = const(255) +_SOCKET_INVALID = const(255) # pylint: disable=too-many-arguments, unused-argument @@ -169,7 +169,7 @@ def __init__( self._listen_port = None self._socknum = _the_interface.get_socket() - if self._socknum == SOCKET_INVALID: + if self._socknum == _SOCKET_INVALID: raise RuntimeError("Failed to allocate socket.") def __enter__(self): @@ -213,11 +213,13 @@ def connected(self) -> bool: :return bool: Whether connected. """ + # pylint: disable=protected-access + if self.socknum >= _the_interface.max_sockets: return False status = _the_interface.socket_status(self.socknum)[0] if ( - status == wiznet5k.adafruit_wiznet5k.SNSR_SOCK_CLOSE_WAIT + status == wiznet5k.adafruit_wiznet5k._SNSR_SOCK_CLOSE_WAIT and self.available() == 0 ): result = False @@ -225,7 +227,7 @@ def connected(self) -> bool: result = status not in ( wiznet5k.adafruit_wiznet5k.SNSR_SOCK_CLOSED, wiznet5k.adafruit_wiznet5k.SNSR_SOCK_LISTEN, - wiznet5k.adafruit_wiznet5k.SNSR_SOCK_TIME_WAIT, + wiznet5k.adafruit_wiznet5k._SNSR_SOCK_TIME_WAIT, wiznet5k.adafruit_wiznet5k.SNSR_SOCK_FIN_WAIT, ) if not result and status != wiznet5k.adafruit_wiznet5k.SNSR_SOCK_LISTEN: diff --git a/examples/wiznet5k_wsgiservertest.py b/examples/wiznet5k_wsgiservertest.py deleted file mode 100644 index 3d1c604..0000000 --- a/examples/wiznet5k_wsgiservertest.py +++ /dev/null @@ -1,138 +0,0 @@ -# SPDX-FileCopyrightText: 2021 Patrick Van Oosterwijck @ Silicognition LLC -# -# SPDX-License-Identifier: MIT -# -# This demo was tested with the PoE-FeatherWing, which contains a 24AA02E48 -# chip to provide a globally unique MAC address, but can also work without -# this chip for testing purposes by using a hard coded MAC. -# -# It also contains a `get_static_file` function that demonstrates how to -# use a generator to serve large static files without using up too much -# memory. To avoid having to put extra files in the repo, it just serves -# `code.py` which isn't very large, but to properly test it, adjust the code -# to serve an image of several 100 kB to see how it works. -# -# There's also an endpoint that demonstrates that `requests` can be used to -# get data from another socket and serve it. -# - -import board -import busio -import digitalio -import neopixel - -import adafruit_requests as requests -from adafruit_wsgi.wsgi_app import WSGIApp -from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K -import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket -import adafruit_wiznet5k.adafruit_wiznet5k_wsgiserver as server - - -print("Wiznet5k Web Server Test") - - -def get_mac(i2c_obj): - "Read MAC from 24AA02E48 chip and return it" - mac_addr = bytearray(6) - while not i2c_obj.try_lock(): - pass - i2c_obj.writeto(0x50, bytearray((0xFA,))) - i2c_obj.readfrom_into(0x50, mac_addr, start=0, end=6) - i2c_obj.unlock() - return mac_addr - - -def get_static_file(filename): - "Static file generator" - with open(filename, "rb") as f: - b = None - while b is None or len(b) == 2048: - b = f.read(2048) - yield b - - -# Status LED -led = neopixel.NeoPixel(board.NEOPIXEL, 1) -led.brightness = 0.3 -led[0] = (255, 0, 0) - -# Chip Select for PoE-FeatherWing and Adafruit Ethernet FeatherWing -cs = digitalio.DigitalInOut(board.D10) -# Chip Select for Particle Ethernet FeatherWing -# cs = digitalio.DigitalInOut(board.D5) - -# Initialize SPI bus -spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) - -try: - # Initialize the I2C bus to read the MAC - i2c = busio.I2C(board.SCL, board.SDA) - # Read the MAC from the 24AA02E48 chip - mac = get_mac(i2c) -except (RuntimeError, OSError): - # Hard coded MAC if there is no 24AA02E48 - mac = b"\xFE\xED\xDE\xAD\xBE\xEF" - -# Initialize Ethernet interface with DHCP -eth = WIZNET5K(spi_bus, cs, mac=mac) - -# Initialize a requests object with a socket and ethernet interface -requests.set_socket(socket, eth) - - -# Here we create our application, registering the -# following functions to be called on specific HTTP GET requests routes - -web_app = WSGIApp() - - -@web_app.route("/led///") -def led_on(request, r, g, b): # pylint: disable=unused-argument - print("LED handler") - led.fill((int(r), int(g), int(b))) - return ("200 OK", [], ["LED set!"]) - - -@web_app.route("/") -def root(request): # pylint: disable=unused-argument - print("Root WSGI handler") - return ("200 OK", [], ["Root document"]) - - -@web_app.route("/large") -def large(request): # pylint: disable=unused-argument - print("Large pattern handler") - return ("200 OK", [], ["*-.-" * 2000]) - - -@web_app.route("/code") -def code(request): # pylint: disable=unused-argument - print("Static file code.py handler") - return ("200 OK", [], get_static_file("code.py")) - - -@web_app.route("/btc") -def btc(request): # pylint: disable=unused-argument - print("BTC handler") - r = requests.get("http://api.coindesk.com/v1/bpi/currentprice/USD.json") - result = r.text - r.close() - return ("200 OK", [], [result]) - - -# Here we setup our server, passing in our web_app as the application -server.set_interface(eth) -wsgiServer = server.WSGIServer(80, application=web_app) - -print("Open this IP in your browser: ", eth.pretty_ip(eth.ip_address)) - -# Start the server -wsgiServer.start() -led[0] = (0, 0, 255) - -while True: - # Our main loop where we have the server poll for incoming requests - wsgiServer.update_poll() - # Maintain DHCP lease - eth.maintain_dhcp_lease() - # Could do any other background tasks here, like reading sensors diff --git a/tests/test_dhcp.py b/tests/test_dhcp.py index 005e20f..a7bb478 100644 --- a/tests/test_dhcp.py +++ b/tests/test_dhcp.py @@ -26,57 +26,57 @@ def wrench(mocker): class TestDHCPInit: def test_constants(self): # DHCP State Machine - assert wiz_dhcp.STATE_DHCP_START == const(0x00) - assert wiz_dhcp.STATE_DHCP_DISCOVER == const(0x01) - assert wiz_dhcp.STATE_DHCP_REQUEST == const(0x02) - assert wiz_dhcp.STATE_DHCP_LEASED == const(0x03) - assert wiz_dhcp.STATE_DHCP_REREQUEST == const(0x04) - assert wiz_dhcp.STATE_DHCP_RELEASE == const(0x05) - assert wiz_dhcp.STATE_DHCP_WAIT == const(0x06) - assert wiz_dhcp.STATE_DHCP_DISCONN == const(0x07) + assert wiz_dhcp._STATE_DHCP_START == const(0x00) + assert wiz_dhcp._STATE_DHCP_DISCOVER == const(0x01) + assert wiz_dhcp._STATE_DHCP_REQUEST == const(0x02) + assert wiz_dhcp._STATE_DHCP_LEASED == const(0x03) + assert wiz_dhcp._STATE_DHCP_REREQUEST == const(0x04) + assert wiz_dhcp._STATE_DHCP_RELEASE == const(0x05) + assert wiz_dhcp._STATE_DHCP_WAIT == const(0x06) + assert wiz_dhcp._STATE_DHCP_DISCONN == const(0x07) # DHCP wait time between attempts - assert wiz_dhcp.DHCP_WAIT_TIME == const(60) + assert wiz_dhcp._DHCP_WAIT_TIME == const(60) # DHCP Message Types - assert wiz_dhcp.DHCP_DISCOVER == const(1) - assert wiz_dhcp.DHCP_OFFER == const(2) - assert wiz_dhcp.DHCP_REQUEST == const(3) - assert wiz_dhcp.DHCP_DECLINE == const(4) - assert wiz_dhcp.DHCP_ACK == const(5) - assert wiz_dhcp.DHCP_NAK == const(6) - assert wiz_dhcp.DHCP_RELEASE == const(7) - assert wiz_dhcp.DHCP_INFORM == const(8) + assert wiz_dhcp._DHCP_DISCOVER == const(1) + assert wiz_dhcp._DHCP_OFFER == const(2) + assert wiz_dhcp._DHCP_REQUEST == const(3) + assert wiz_dhcp._DHCP_DECLINE == const(4) + assert wiz_dhcp._DHCP_ACK == const(5) + assert wiz_dhcp._DHCP_NAK == const(6) + assert wiz_dhcp._DHCP_RELEASE == const(7) + assert wiz_dhcp._DHCP_INFORM == const(8) # DHCP Message OP Codes - assert wiz_dhcp.DHCP_BOOT_REQUEST == const(0x01) - assert wiz_dhcp.DHCP_BOOT_REPLY == const(0x02) + assert wiz_dhcp._DHCP_BOOT_REQUEST == const(0x01) + assert wiz_dhcp._DHCP_BOOT_REPLY == const(0x02) - assert wiz_dhcp.DHCP_HTYPE10MB == const(0x01) - assert wiz_dhcp.DHCP_HTYPE100MB == const(0x02) + assert wiz_dhcp._DHCP_HTYPE10MB == const(0x01) + assert wiz_dhcp._DHCP_HTYPE100MB == const(0x02) - assert wiz_dhcp.DHCP_HLENETHERNET == const(0x06) - assert wiz_dhcp.DHCP_HOPS == const(0x00) + assert wiz_dhcp._DHCP_HLENETHERNET == const(0x06) + assert wiz_dhcp._DHCP_HOPS == const(0x00) - assert wiz_dhcp.MAGIC_COOKIE == b"c\x82Sc" - assert wiz_dhcp.MAX_DHCP_OPT == const(0x10) + assert wiz_dhcp._MAGIC_COOKIE == b"c\x82Sc" + assert wiz_dhcp._MAX_DHCP_OPT == const(0x10) # Default DHCP Server port - assert wiz_dhcp.DHCP_SERVER_PORT == const(67) + assert wiz_dhcp._DHCP_SERVER_PORT == const(67) # DHCP Lease Time, in seconds - assert wiz_dhcp.DEFAULT_LEASE_TIME == const(900) - assert wiz_dhcp.BROADCAST_SERVER_ADDR == (255, 255, 255, 255) + assert wiz_dhcp._DEFAULT_LEASE_TIME == const(900) + assert wiz_dhcp._BROADCAST_SERVER_ADDR == (255, 255, 255, 255) # DHCP Response Options - assert wiz_dhcp.MSG_TYPE == 53 - assert wiz_dhcp.SUBNET_MASK == 1 - assert wiz_dhcp.ROUTERS_ON_SUBNET == 3 - assert wiz_dhcp.DNS_SERVERS == 6 - assert wiz_dhcp.DHCP_SERVER_ID == 54 - assert wiz_dhcp.T1_VAL == 58 - assert wiz_dhcp.T2_VAL == 59 - assert wiz_dhcp.LEASE_TIME == 51 - assert wiz_dhcp.OPT_END == 255 + assert wiz_dhcp._MSG_TYPE == 53 + assert wiz_dhcp._SUBNET_MASK == 1 + assert wiz_dhcp._ROUTERS_ON_SUBNET == 3 + assert wiz_dhcp._DNS_SERVERS == 6 + assert wiz_dhcp._DHCP_SERVER_ID == 54 + assert wiz_dhcp._T1_VAL == 58 + assert wiz_dhcp._T2_VAL == 59 + assert wiz_dhcp._LEASE_TIME == 51 + assert wiz_dhcp._OPT_END == 255 # Packet buffer assert wiz_dhcp._BUFF == bytearray(318) @@ -102,12 +102,12 @@ def test_dhcp_setup_default(self, mocker, wiznet, wrench, mac_address): assert dhcp_client._mac_address == mac_address wrench.set_interface.assert_called_once_with(wiznet) assert dhcp_client._sock is None - assert dhcp_client._dhcp_state == wiz_dhcp.STATE_DHCP_START + assert dhcp_client._dhcp_state == wiz_dhcp._STATE_DHCP_START assert dhcp_client._initial_xid == 0 mock_randint.assert_called_once() assert dhcp_client._transaction_id == 0x1234567 assert dhcp_client._start_time == 0 - assert dhcp_client.dhcp_server_ip == wiz_dhcp.BROADCAST_SERVER_ADDR + assert dhcp_client.dhcp_server_ip == wiz_dhcp._BROADCAST_SERVER_ADDR assert dhcp_client.local_ip == 0 assert dhcp_client.gateway_ip == 0 assert dhcp_client.subnet_mask == 0 @@ -219,7 +219,7 @@ def test_send_with_defaults(self, wiznet, wrench): ( (4, 5, 6, 7, 8, 9), None, - wiz_dhcp.STATE_DHCP_DISCOVER, + wiz_dhcp._STATE_DHCP_DISCOVER, 23.4, False, 0, @@ -229,7 +229,7 @@ def test_send_with_defaults(self, wiznet, wrench): ( (24, 35, 46, 57, 68, 79), "bert.co.uk", - wiz_dhcp.STATE_DHCP_REQUEST, + wiz_dhcp._STATE_DHCP_REQUEST, 35.5, False, (192, 168, 3, 4), @@ -239,7 +239,7 @@ def test_send_with_defaults(self, wiznet, wrench): ( (255, 97, 36, 101, 42, 99), "clash.net", - wiz_dhcp.STATE_DHCP_REQUEST, + wiz_dhcp._STATE_DHCP_REQUEST, 35.5, True, (10, 10, 10, 43), @@ -412,7 +412,7 @@ def test_parsing_failures(self, wiznet, wrench): self.BAD_DATA[0] = 0 dhcp_client._transaction_id = 0x7FFFFFFF dhcp_client._initial_xid = dhcp_client._transaction_id.to_bytes(4, "little") - with pytest.raises(ValueError): + with pytest.raises(RuntimeError): dhcp_client.parse_dhcp_response() self.BAD_DATA[0] = 2 # Reset to good value # No server ID. @@ -430,13 +430,13 @@ class TestStateMachine: @pytest.mark.parametrize( "dhcp_state, socket_state", ( - (wiz_dhcp.STATE_DHCP_START, "Socket"), - (wiz_dhcp.STATE_DHCP_DISCOVER, None), - (wiz_dhcp.STATE_DHCP_REQUEST, None), - (wiz_dhcp.STATE_DHCP_LEASED, None), - (wiz_dhcp.STATE_DHCP_REREQUEST, None), - (wiz_dhcp.STATE_DHCP_RELEASE, None), - (wiz_dhcp.STATE_DHCP_WAIT, None), + (wiz_dhcp._STATE_DHCP_START, "Socket"), + (wiz_dhcp._STATE_DHCP_DISCOVER, None), + (wiz_dhcp._STATE_DHCP_REQUEST, None), + (wiz_dhcp._STATE_DHCP_LEASED, None), + (wiz_dhcp._STATE_DHCP_REREQUEST, None), + (wiz_dhcp._STATE_DHCP_RELEASE, None), + (wiz_dhcp._STATE_DHCP_WAIT, None), ), ) def test_link_is_down_state_not_disconnected( @@ -461,7 +461,7 @@ def test_link_is_down_state_not_disconnected( # Test. dhcp_client._dhcp_state_machine() # DHCP state machine in correct state. - assert dhcp_client._dhcp_state == wiz_dhcp.STATE_DHCP_DISCONN + assert dhcp_client._dhcp_state == wiz_dhcp._STATE_DHCP_DISCONN # Check that configurations are returned to defaults. assert dhcp_client._eth.ifconfig == ( (0, 0, 0, 0), @@ -470,7 +470,7 @@ def test_link_is_down_state_not_disconnected( (0, 0, 0, 0), ) assert dhcp_client._last_lease_time == 0 - assert dhcp_client.dhcp_server_ip == wiz_dhcp.BROADCAST_SERVER_ADDR + assert dhcp_client.dhcp_server_ip == wiz_dhcp._BROADCAST_SERVER_ADDR assert dhcp_client._sock is None def test_link_is_down_state_disconnected(self, wiznet): @@ -485,11 +485,11 @@ def test_link_is_down_state_disconnected(self, wiznet): dhcp_client._last_lease_time = 1 dhcp_client.dhcp_server_ip = (192, 234, 1, 75) dhcp_client._sock = "socket" - dhcp_client._dhcp_state = wiz_dhcp.STATE_DHCP_DISCONN + dhcp_client._dhcp_state = wiz_dhcp._STATE_DHCP_DISCONN # Test. dhcp_client._dhcp_state_machine() # DHCP state machine in correct state. - assert dhcp_client._dhcp_state == wiz_dhcp.STATE_DHCP_DISCONN + assert dhcp_client._dhcp_state == wiz_dhcp._STATE_DHCP_DISCONN # Check that configurations are not altered because state has not changed. assert dhcp_client._eth.ifconfig == ( (1, 1, 1, 1), @@ -505,8 +505,8 @@ def test_link_is_up_state_disconnected(self, wiznet, wrench): dhcp_client = wiz_dhcp.DHCP(wiznet, (1, 2, 3, 4, 5, 6)) wrench.socket.side_effect = [RuntimeError] dhcp_client._eth.link_status = True - dhcp_client._dhcp_state = wiz_dhcp.STATE_DHCP_DISCONN + dhcp_client._dhcp_state = wiz_dhcp._STATE_DHCP_DISCONN # Test. dhcp_client._dhcp_state_machine() # Assume state is set to START then becomes WAIT after START fails to set a socket - assert dhcp_client._dhcp_state == wiz_dhcp.STATE_DHCP_WAIT + assert dhcp_client._dhcp_state == wiz_dhcp._STATE_DHCP_WAIT