diff --git a/adafruit_portalbase/network.py b/adafruit_portalbase/network.py index 9c4f7ec..091c70f 100644 --- a/adafruit_portalbase/network.py +++ b/adafruit_portalbase/network.py @@ -316,11 +316,16 @@ def wget(self, url, filename, *, chunk_size=12000): if not content_length == os.stat(filename)[6]: raise RuntimeError - def connect(self): + def connect(self, max_attempts=10): """ Connect to WiFi using the settings found in secrets.py + + :param max_attempts: The maximum number of of attempts to connect to WiFi before + failing or use None to disable. Defaults to 10. + """ self._wifi.neo_status(STATUS_CONNECTING) + attempt = 1 while not self._wifi.is_connected: # secrets dictionary must contain 'ssid' and 'password' at a minimum print("Connecting to AP", self._secrets["ssid"]) @@ -340,8 +345,13 @@ def connect(self): self._wifi.connect(self._secrets["ssid"], self._secrets["password"]) self.requests = self._wifi.requests except RuntimeError as error: + if max_attempts is not None and attempt >= max_attempts: + raise OSError( + "Maximum number of attempts reached when trying to connect to WiFi" + ) from error print("Could not connect to internet", error) print("Retrying in 3 seconds...") + attempt += 1 time.sleep(3) gc.collect()