Skip to content

Examples and tests for debugging #168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
911445d
Make these connection errors distinct from other error types.
dannystaple May 10, 2022
4455889
Another OSError derived error here.
dannystaple May 10, 2022
de04df1
These now derive also from OSError types - without timeouts being spe…
dannystaple May 10, 2022
5abca8d
More error specificity
dannystaple May 10, 2022
6605027
These are now in the OSError heirarchy
dannystaple May 10, 2022
d17790c
Make these more specific too
dannystaple May 10, 2022
c961c09
This now accepts the same set of errors - atlhough it could be more d…
dannystaple May 10, 2022
19e47fd
Make the suggested change for handling valueerrors.
dannystaple May 17, 2022
fa311a1
These are definitely valueerrors.
dannystaple May 17, 2022
1756c81
Swap those runtime errors for OSerrors - most will be.
dannystaple May 17, 2022
39c672d
More runtime error catches
dannystaple May 17, 2022
71f3856
The parts that can raise assertion errors are not recoverable.
dannystaple May 17, 2022
df4112a
These are OSErrors - or connection errors, we got an unexpected respo…
dannystaple May 17, 2022
6bf4973
The value errors caught in these wouldn't be recoverable, but the OS …
dannystaple May 17, 2022
0f3b266
This tool, aimed at the pico, just establishes contact with the devic…
dannystaple May 19, 2022
e3e0f1e
Merge branch 'main' into use-connection-errors
dannystaple May 22, 2022
491d014
Merge branch 'main' into examples_and_tests_for_debugging
dannystaple May 22, 2022
bf913f9
First attempt at socket stress test
dannystaple May 22, 2022
17f5369
Needs to be reopening the socket to match the server
dannystaple May 22, 2022
9e32e8a
Further stress tests
dannystaple May 30, 2022
619771c
Black formatted
dannystaple May 30, 2022
d6e0f7b
Fix linter issues
dannystaple May 30, 2022
6c126e9
Unexpected reformat here
dannystaple May 30, 2022
33ba623
Merge branch 'use-connection-errors' into examples_and_tests_for_debu…
dannystaple May 30, 2022
0a5b15b
Merge branch 'adafruit:main' into examples_and_tests_for_debugging
dannystaple May 30, 2022
9b737e0
Update adafruit_esp32spi/adafruit_esp32spi.py
dannystaple Jun 1, 2022
afbe492
Update adafruit_esp32spi/adafruit_esp32spi.py
dannystaple Jun 1, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 47 additions & 47 deletions adafruit_esp32spi/adafruit_esp32spi.py

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions adafruit_esp32spi/adafruit_esp32spi_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
"""Given a hostname and a port name, return a 'socket.getaddrinfo'
compatible list of tuples. Honestly, we ignore anything but host & port"""
if not isinstance(port, int):
raise RuntimeError("Port must be an integer")
raise ValueError("Port must be an integer")
ipaddr = _the_interface.get_host_by_name(host)
return [(AF_INET, socktype, proto, "", (ipaddr, port))]

Expand All @@ -56,7 +56,7 @@ 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")
raise ValueError("Only AF_INET family supported")
self._type = type
self._buffer = b""
self._socknum = socknum if socknum else _the_interface.get_socket()
Expand All @@ -74,7 +74,7 @@ def connect(self, address, conntype=None):
if not _the_interface.socket_connect(
self._socknum, host, port, conn_mode=conntype
):
raise RuntimeError("Failed to connect to host", host)
raise ConnectionError("Failed to connect to host", host)
self._buffer = b""

def send(self, data): # pylint: disable=no-self-use
Expand Down Expand Up @@ -105,7 +105,7 @@ def readline(self, eol=b"\r\n"):
self._buffer += _the_interface.socket_read(self._socknum, avail)
elif self._timeout > 0 and time.monotonic() - stamp > self._timeout:
self.close() # Make sure to close socket so that we don't exhaust sockets.
raise RuntimeError("Didn't receive full response, failing out")
raise OSError("Didn't receive full response, failing out")
firstline, self._buffer = self._buffer.split(eol, 1)
gc.collect()
return firstline
Expand Down
6 changes: 3 additions & 3 deletions adafruit_esp32spi/adafruit_esp32spi_wifimanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def connect_normal(self):
self.esp.connect_AP(bytes(ssid, "utf-8"), bytes(password, "utf-8"))
failure_count = 0
self.pixel_status((0, 100, 0))
except (ValueError, RuntimeError) as error:
except OSError as error:
print("Failed to connect, retrying\n", error)
failure_count += 1
if failure_count >= self.attempts:
Expand Down Expand Up @@ -173,7 +173,7 @@ def create_ap(self):
self.esp.create_AP(bytes(self.ssid, "utf-8"), None)
failure_count = 0
self.pixel_status((0, 100, 0))
except (ValueError, RuntimeError) as error:
except OSError as error:
print("Failed to create access point\n", error)
failure_count += 1
if failure_count >= self.attempts:
Expand Down Expand Up @@ -203,7 +203,7 @@ def connect_enterprise(self):
failure_count = 0
self.pixel_status((0, 100, 0))
sleep(1)
except (ValueError, RuntimeError) as error:
except OSError as error:
print("Failed to connect, retrying\n", error)
failure_count += 1
if failure_count >= self.attempts:
Expand Down
34 changes: 16 additions & 18 deletions adafruit_esp32spi/adafruit_esp32spi_wsgiserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def update_poll(self):

def finish_response(self, result):
"""
Called after the application callbile returns result data to respond with.
Called after the application callable returns result data to respond with.
Creates the HTTP Response payload from the response_headers and results data,
and sends it back to client.

Expand Down Expand Up @@ -138,23 +138,21 @@ def client_available(self):
:rtype: Socket
"""
sock = None
if self._server_sock.socknum != NO_SOCK_AVAIL:
if self._client_sock.socknum != NO_SOCK_AVAIL:
# check previous received client socket
if self._debug > 2:
print("checking if last client sock still valid")
if self._client_sock.connected() and self._client_sock.available():
sock = self._client_sock
if not sock:
# check for new client sock
if self._debug > 2:
print("checking for new client sock")
client_sock_num = _the_interface.socket_available(
self._server_sock.socknum
)
sock = socket.socket(socknum=client_sock_num)
else:
print("Server has not been started, cannot check for clients!")
if self._server_sock.socknum == NO_SOCK_AVAIL:
raise ValueError("Server has not been started, cannot check for clients!")

if self._client_sock.socknum != NO_SOCK_AVAIL:
# check previous received client socket
if self._debug > 2:
print("checking if last client sock still valid")
if self._client_sock.connected() and self._client_sock.available():
sock = self._client_sock
if not sock:
# check for new client sock
if self._debug > 2:
print("checking for new client sock")
client_sock_num = _the_interface.socket_available(self._server_sock.socknum)
sock = socket.socket(socknum=client_sock_num)

if sock and sock.socknum != NO_SOCK_AVAIL:
if self._debug > 2:
Expand Down
4 changes: 2 additions & 2 deletions adafruit_esp32spi/digitalio.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def init(self, mode=IN):
self._mode = self.OUT
self._esp.set_pin_mode(self.pin_id, 1)
else:
raise RuntimeError("Invalid mode defined")
raise ValueError("Invalid mode defined")

def value(self, val=None):
"""Sets ESP32 Pin GPIO output mode.
Expand All @@ -76,7 +76,7 @@ def value(self, val=None):
self._value = val
self._esp.set_digital_write(self.pin_id, 1)
else:
raise RuntimeError("Invalid value for pin")
raise ValueError("Invalid value for pin")
else:
raise NotImplementedError(
"digitalRead not currently implemented in esp32spi"
Expand Down
2 changes: 1 addition & 1 deletion examples/esp32spi_aio_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
response.close()
counter = counter + 1
print("OK")
except (ValueError, RuntimeError) as e:
except OSError as e:
print("Failed to get data, retrying\n", e)
wifi.reset()
continue
Expand Down
2 changes: 1 addition & 1 deletion examples/esp32spi_cheerlights.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
value = value[key]
print(value)
response.close()
except (ValueError, RuntimeError) as e:
except OSError as e:
print("Failed to get data, retrying\n", e)
wifi.reset()
continue
Expand Down
33 changes: 33 additions & 0 deletions examples/esp32spi_get_board_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import board
import busio

from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi

print("ESP32 SPI hardware test")

# PyPortal or similar; edit pins as needed

spi = busio.SPI(board.GP14, board.GP11, board.GP12)
esp32_cs = DigitalInOut(board.GP10)
esp32_ready = DigitalInOut(board.GP9)
esp32_reset = DigitalInOut(board.GP8)
esp = adafruit_esp32spi.ESP_SPIcontrol(
spi, esp32_cs, esp32_ready, esp32_reset, debug=True
)

# Fetch and print status
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
print("ESP32 found and in idle mode")
print("Firmware version.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address])

time.sleep(5)

for ap in esp.scan_networks():
print("\t%s\t\tRSSI: %d" % (str(ap["ssid"], "utf-8"), ap["rssi"]))
print("Done!")
2 changes: 1 addition & 1 deletion examples/esp32spi_ipconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
except RuntimeError as e:
except OSError as e:
print("could not connect to AP, retrying: ", e)
continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
Expand Down
2 changes: 1 addition & 1 deletion examples/esp32spi_localtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
print("Fetching json from", TIME_API)
response = wifi.get(TIME_API)
break
except (ValueError, RuntimeError) as e:
except OSError as e:
print("Failed to get data, retrying\n", e)
continue

Expand Down
2 changes: 1 addition & 1 deletion examples/esp32spi_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
except RuntimeError as e:
except OSError as e:
print("could not connect to AP, retrying: ", e)
continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
Expand Down
2 changes: 1 addition & 1 deletion examples/esp32spi_simpletest_rp2040.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
except RuntimeError as e:
except OSError as e:
print("could not connect to AP, retrying: ", e)
continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
Expand Down
2 changes: 1 addition & 1 deletion examples/esp32spi_wpa2ent_aio_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
response.close()
counter = counter + 1
print("OK")
except (ValueError, RuntimeError) as e:
except OSError as e:
print("Failed to get data, retrying\n", e)
wifi.reset()
continue
Expand Down
8 changes: 4 additions & 4 deletions examples/gpio/esp32spi_gpio.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def esp_init_pin_modes(din, dout):
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
esp_d_r_val = esp.set_digital_read(ESP_D_R_PIN)
print("--> ESP read:", esp_d_r_val)
except (RuntimeError, AssertionError) as e:
except OSError as e:
print("ESP32 Error", e)
esp_reset_all()

Expand All @@ -104,7 +104,7 @@ def esp_init_pin_modes(din, dout):
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
esp.set_digital_write(ESP_D_W_PIN, esp_d_w_val)
print("ESP wrote:", esp_d_w_val, "--> Red LED")
except (RuntimeError) as e:
except OSError as e:
print("ESP32 Error", e)
esp_reset_all()

Expand All @@ -121,7 +121,7 @@ def esp_init_pin_modes(din, dout):
"v)",
sep="",
)
except (RuntimeError, AssertionError) as e:
except OSError as e:
print("ESP32 Error", e)
esp_reset_all()

Expand Down Expand Up @@ -166,7 +166,7 @@ def esp_init_pin_modes(din, dout):
sep="",
)

except (RuntimeError) as e:
except OSError as e:
print("ESP32 Error", e)
esp_reset_all()

Expand Down
4 changes: 2 additions & 2 deletions examples/server/esp32spi_wsgiserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def led_color(environ): # pylint: disable=unused-argument
static
)
)
except (OSError) as e:
except OSError as e:
raise RuntimeError(
"""
This example depends on a static asset directory.
Expand All @@ -240,7 +240,7 @@ def led_color(environ): # pylint: disable=unused-argument
try:
wsgiServer.update_poll()
# Could do any other background tasks here, like reading sensors
except (ValueError, RuntimeError) as e:
except OSError as e:
print("Failed to update server, restarting ESP32\n", e)
wifi.reset()
continue
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import struct
import board
import busio
from digitalio import DigitalInOut

from adafruit_esp32spi import adafruit_esp32spi
import adafruit_esp32spi.adafruit_esp32spi_socket as socket

# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise

print("ESP32 SPI socket count client test")

TIMEOUT = 5
# edit host and port to match server
HOST = "192.168.1.149"
PORT = 8981

esp32_cs = DigitalInOut(board.GP10)
esp32_ready = DigitalInOut(board.GP9)
esp32_reset = DigitalInOut(board.GP8)
spi = busio.SPI(board.GP14, board.GP11, board.GP12)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

# connect to wifi AP
esp.connect(secrets)

# test for connectivity to server
print("Server ping:", esp.ping(HOST), "ms")

# create the socket
socket.set_interface(esp)
socketaddr = socket.getaddrinfo(HOST, PORT)[0][4]
s = socket.socket()
s.settimeout(TIMEOUT)


while True:
print("Connecting")
s.connect(socketaddr)
# get a count from the Socket. lets receive this as 4 bytes - unpack as an int.
data = s.recv(4)
# print it
print(f"Data length {len(data)}. Data: ", end="")
print(struct.unpack("!I", data))
time.sleep(0.01)
s.close()
Loading