Skip to content

Commit 42644e6

Browse files
authored
Merge pull request #63 from bablokb/fix-retries
Consolidate retry-logic
2 parents 0102b95 + 7f117e7 commit 42644e6

File tree

2 files changed

+60
-54
lines changed

2 files changed

+60
-54
lines changed

adafruit_espatcontrol/adafruit_espatcontrol.py

Lines changed: 49 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -135,34 +135,39 @@ def begin(self) -> None:
135135
except OKError:
136136
pass # retry
137137

138-
def connect(self, secrets: Dict[str, Union[str, int]]) -> None:
138+
def connect(
139+
self, secrets: Dict[str, Union[str, int]], timeout: int = 15, retries: int = 3
140+
) -> None:
139141
"""Repeatedly try to connect to an access point with the details in
140142
the passed in 'secrets' dictionary. Be sure 'ssid' and 'password' are
141143
defined in the secrets dict! If 'timezone' is set, we'll also configure
142144
SNTP"""
143145
# Connect to WiFi if not already
144-
retries = 3
145-
while True:
146-
try:
147-
if not self._initialized or retries == 0:
148-
self.begin()
149-
retries = 3
150-
AP = self.remote_AP # pylint: disable=invalid-name
151-
print("Connected to", AP[0])
152-
if AP[0] != secrets["ssid"]:
153-
self.join_AP(secrets["ssid"], secrets["password"])
154-
if "timezone" in secrets:
155-
tzone = secrets["timezone"]
156-
ntp = None
157-
if "ntp_server" in secrets:
158-
ntp = secrets["ntp_server"]
159-
self.sntp_config(True, tzone, ntp)
160-
print("My IP Address:", self.local_ip)
161-
return # yay!
162-
except (RuntimeError, OKError) as exp:
163-
print("Failed to connect, retrying\n", exp)
164-
retries -= 1
165-
continue
146+
try:
147+
if not self._initialized:
148+
self.begin()
149+
AP = self.remote_AP # pylint: disable=invalid-name
150+
if AP[0] != secrets["ssid"]:
151+
self.join_AP(
152+
secrets["ssid"],
153+
secrets["password"],
154+
timeout=timeout,
155+
retries=retries,
156+
)
157+
print("Connected to", secrets["ssid"])
158+
if "timezone" in secrets:
159+
tzone = secrets["timezone"]
160+
ntp = None
161+
if "ntp_server" in secrets:
162+
ntp = secrets["ntp_server"]
163+
self.sntp_config(True, tzone, ntp)
164+
print("My IP Address:", self.local_ip)
165+
else:
166+
print("Already connected to", AP[0])
167+
return # yay!
168+
except (RuntimeError, OKError) as exp:
169+
print("Failed to connect\n", exp)
170+
raise
166171

167172
# *************************** SOCKET SETUP ****************************
168173

@@ -462,7 +467,9 @@ def remote_AP(self) -> List[Union[int, str, None]]: # pylint: disable=invalid-n
462467
return reply
463468
return [None] * 4
464469

465-
def join_AP(self, ssid: str, password: str) -> None: # pylint: disable=invalid-name
470+
def join_AP( # pylint: disable=invalid-name
471+
self, ssid: str, password: str, timeout: int = 15, retries: int = 3
472+
) -> None:
466473
"""Try to join an access point by name and password, will return
467474
immediately if we're already connected and won't try to reconnect"""
468475
# First make sure we're in 'station' mode so we can connect to AP's
@@ -472,17 +479,18 @@ def join_AP(self, ssid: str, password: str) -> None: # pylint: disable=invalid-
472479
router = self.remote_AP
473480
if router and router[0] == ssid:
474481
return # we're already connected!
475-
for _ in range(3):
476-
reply = self.at_response(
477-
'AT+CWJAP="' + ssid + '","' + password + '"', timeout=15, retries=3
478-
)
479-
if b"WIFI CONNECTED" not in reply:
480-
print("no CONNECTED")
481-
raise RuntimeError("Couldn't connect to WiFi")
482-
if b"WIFI GOT IP" not in reply:
483-
print("no IP")
484-
raise RuntimeError("Didn't get IP address")
485-
return
482+
reply = self.at_response(
483+
'AT+CWJAP="' + ssid + '","' + password + '"',
484+
timeout=timeout,
485+
retries=retries,
486+
)
487+
if b"WIFI CONNECTED" not in reply:
488+
print("no CONNECTED")
489+
raise RuntimeError("Couldn't connect to WiFi")
490+
if b"WIFI GOT IP" not in reply:
491+
print("no IP")
492+
raise RuntimeError("Didn't get IP address")
493+
return
486494

487495
def scan_APs( # pylint: disable=invalid-name
488496
self, retries: int = 3
@@ -578,7 +586,12 @@ def at_response(self, at_cmd: str, timeout: int = 5, retries: int = 3) -> bytes:
578586
# special case, ping also does not return an OK
579587
if "AT+PING" in at_cmd and b"ERROR\r\n" in response:
580588
return response
581-
if response[-4:] != b"OK\r\n":
589+
# special case, does return OK but in fact it is busy
590+
if (
591+
"AT+CIFSR" in at_cmd
592+
and b"busy" in response
593+
or response[-4:] != b"OK\r\n"
594+
):
582595
time.sleep(1)
583596
continue
584597
return response[:-4]

adafruit_espatcontrol/adafruit_espatcontrol_wifimanager.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def __init__(
4141
:param dict secrets: The WiFi and Adafruit IO secrets dict (See examples)
4242
:param status_pixel: (Optional) The pixel device - A NeoPixel or DotStar (default=None)
4343
:type status_pixel: NeoPixel or DotStar
44-
:param int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2)
44+
:param int attempts: (Optional) Unused, only for compatibility for old code
4545
"""
4646
# Read the settings
4747
self._esp = esp
@@ -60,26 +60,19 @@ def reset(self) -> None:
6060
print("Resetting ESP")
6161
self._esp.hard_reset()
6262

63-
def connect(self) -> None:
63+
def connect(self, timeout: int = 15, retries: int = 3) -> None:
6464
"""
6565
Attempt to connect to WiFi using the current settings
6666
"""
67-
failure_count = 0
68-
while not self._esp.is_connected:
69-
try:
70-
if self.debug:
71-
print("Connecting to AP...")
72-
self.pixel_status((100, 0, 0))
73-
self._esp.connect(self.secrets)
74-
failure_count = 0
75-
self.pixel_status((0, 100, 0))
76-
except (ValueError, RuntimeError) as error:
77-
print("Failed to connect, retrying\n", error)
78-
failure_count += 1
79-
if failure_count >= self.attempts:
80-
failure_count = 0
81-
self.reset()
82-
continue
67+
try:
68+
if self.debug:
69+
print("Connecting to AP...")
70+
self.pixel_status((100, 0, 0))
71+
self._esp.connect(self.secrets, timeout=timeout, retries=retries)
72+
self.pixel_status((0, 100, 0))
73+
except (ValueError, RuntimeError) as error:
74+
print("Failed to connect\n", error)
75+
raise
8376

8477
def get(self, url: str, **kw: Any) -> requests.Response:
8578
"""

0 commit comments

Comments
 (0)