Skip to content

Commit

Permalink
Merge pull request #87 from BiffoBear/Standardise_Sockets
Browse files Browse the repository at this point in the history
Standardise sockets
  • Loading branch information
FoamyGuy authored Jan 25, 2023
2 parents f71584b + bb60e7c commit c8fabd0
Show file tree
Hide file tree
Showing 7 changed files with 382 additions and 293 deletions.
25 changes: 12 additions & 13 deletions adafruit_wiznet5k/adafruit_wiznet5k.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@
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_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)
Expand Down Expand Up @@ -266,11 +266,13 @@ def get_host_by_name(self, hostname: str) -> bytes:
:return Union[int, bytes]: a 4 bytearray.
"""
if self._debug:
print("* Get host by name")
print(f"* Get host by name : {hostname}")
if isinstance(hostname, str):
hostname = bytes(hostname, "utf-8")
# Return IP assigned by DHCP
_dns_client = dns.DNS(self, self._dns, debug=self._debug)
_dns_client = dns.DNS(
self, self.pretty_ip(bytearray(self._dns)), debug=self._debug
)
ret = _dns_client.gethostbyname(hostname)
if self._debug:
print("* Resolved IP: ", ret)
Expand Down Expand Up @@ -824,9 +826,9 @@ 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_CLOSE_WAIT,
_SNSR_SOCK_CLOSING,
_SNSR_SOCK_UDP,
):
Expand Down Expand Up @@ -904,7 +906,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
Expand Down Expand Up @@ -991,9 +993,6 @@ def socket_write(
if not self.link_status:
raise ConnectionError("Ethernet cable disconnected!")
assert socket_num <= self.max_sockets, "Provided socket exceeds max_sockets."
status = 0
ret = 0
free_size = 0
if len(buffer) > _SOCK_SIZE:
ret = _SOCK_SIZE
else:
Expand All @@ -1005,7 +1004,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
Expand Down Expand Up @@ -1050,9 +1049,9 @@ def socket_write(
) != _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_CLOSE_WAIT,
_SNSR_SOCK_CLOSING,
) or (timeout and time.monotonic() - stamp > timeout):
# self.socket_close(socket_num)
Expand Down
13 changes: 8 additions & 5 deletions adafruit_wiznet5k/adafruit_wiznet5k_dhcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,9 @@ def parse_dhcp_response(
:return Tuple[int, bytearray]: DHCP packet type and ID.
"""
global _BUFF # pylint: disable=global-statement
# store packet in buffer
_BUFF = self._sock.recv()
_BUFF = bytearray(self._sock.recv(len(_BUFF)))
if self._debug:
print("DHCP Response: ", _BUFF)

Expand Down Expand Up @@ -401,8 +402,10 @@ def _dhcp_state_machine(self) -> None:
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.bind(("", 68))
self._sock.connect(
(".".join(map(str, self.dhcp_server_ip)), _DHCP_SERVER_PORT)
)
if self._last_lease_time == 0 or time.monotonic() > (
self._last_lease_time + self._lease_time
):
Expand All @@ -421,7 +424,7 @@ def _dhcp_state_machine(self) -> None:
self._dhcp_state = _STATE_DHCP_REQUEST

elif self._dhcp_state == _STATE_DHCP_DISCOVER:
if self._sock.available():
if self._sock._available(): # pylint: disable=protected-access
if self._debug:
print("* DHCP: Parsing OFFER")
try:
Expand Down Expand Up @@ -455,7 +458,7 @@ def _dhcp_state_machine(self) -> None:
print("* DHCP: Received DHCP Message is not OFFER")

elif self._dhcp_state == _STATE_DHCP_REQUEST:
if self._sock.available():
if self._sock._available(): # pylint: disable=protected-access
if self._debug:
print("* DHCP: Parsing ACK")
try:
Expand Down
12 changes: 7 additions & 5 deletions adafruit_wiznet5k/adafruit_wiznet5k_dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,6 @@ def __init__(
socket.set_interface(iface)
self._sock = socket.socket(type=socket.SOCK_DGRAM)
self._sock.settimeout(1)

self._dns_server = dns_address
self._query_id = 0 # Request ID.
self._query_length = 0 # Length of last query.
Expand All @@ -245,13 +244,14 @@ 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
# build DNS request packet
self._query_id, self._query_length, buffer = _build_dns_query(hostname)

# Send DNS request packet
self._sock.bind((None, _DNS_PORT))
self._sock.bind(("", _DNS_PORT))
self._sock.connect((self._dns_server, _DNS_PORT))
_debug_print(debug=self._debug, message="* DNS: Sending request packet...")
self._sock.send(buffer)
Expand All @@ -261,9 +261,11 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]:
for _ in range(5):
# wait for a response
socket_timeout = time.monotonic() + 1.0
packet_size = self._sock.available()
packet_size = self._sock._available() # pylint: disable=protected-access
while packet_size == 0:
packet_size = self._sock.available()
packet_size = (
self._sock._available() # pylint: disable=protected-access
)
if time.monotonic() > socket_timeout:
_debug_print(
debug=self._debug,
Expand All @@ -273,7 +275,7 @@ def gethostbyname(self, hostname: bytes) -> Union[int, bytes]:
return -1
time.sleep(0.05)
# recv packet into buf
buffer = self._sock.recv()
buffer = self._sock.recv(512) # > UDP payload length
_debug_print(
debug=self._debug,
message="DNS Packet Received: {}".format(buffer),
Expand Down
2 changes: 1 addition & 1 deletion adafruit_wiznet5k/adafruit_wiznet5k_ntp.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def get_time(self) -> time.struct_time:
self._sock.sendto(self._pkt_buf_, (self._ntp_server, 123))
end_time = time.monotonic() + 0.2 * 2**retry
while time.monotonic() < end_time:
data = self._sock.recv()
data = self._sock.recv(64) # NTP returns a 48 byte message.
if data:
sec = data[40:44]
int_cal = int.from_bytes(sec, "big")
Expand Down
Loading

0 comments on commit c8fabd0

Please sign in to comment.