Skip to content

Commit ae05258

Browse files
authored
Merge pull request #46 from makermelissa/main
Added a maximum number of attempts for connecting to WiFi
2 parents a62c68d + 0550f86 commit ae05258

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

adafruit_portalbase/network.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,11 +316,16 @@ def wget(self, url, filename, *, chunk_size=12000):
316316
if not content_length == os.stat(filename)[6]:
317317
raise RuntimeError
318318

319-
def connect(self):
319+
def connect(self, max_attempts=10):
320320
"""
321321
Connect to WiFi using the settings found in secrets.py
322+
323+
:param max_attempts: The maximum number of of attempts to connect to WiFi before
324+
failing or use None to disable. Defaults to 10.
325+
322326
"""
323327
self._wifi.neo_status(STATUS_CONNECTING)
328+
attempt = 1
324329
while not self._wifi.is_connected:
325330
# secrets dictionary must contain 'ssid' and 'password' at a minimum
326331
print("Connecting to AP", self._secrets["ssid"])
@@ -340,8 +345,13 @@ def connect(self):
340345
self._wifi.connect(self._secrets["ssid"], self._secrets["password"])
341346
self.requests = self._wifi.requests
342347
except RuntimeError as error:
348+
if max_attempts is not None and attempt >= max_attempts:
349+
raise OSError(
350+
"Maximum number of attempts reached when trying to connect to WiFi"
351+
) from error
343352
print("Could not connect to internet", error)
344353
print("Retrying in 3 seconds...")
354+
attempt += 1
345355
time.sleep(3)
346356
gc.collect()
347357

0 commit comments

Comments
 (0)