Skip to content

Commit 3343670

Browse files
committed
fix: Improve exception handling in reconnect example to prevent resource leaks and eliminate code duplication
- Add proper interface cleanup in BLEError handler to prevent resource leaks - Centralize retry logic to eliminate code duplication across exception handlers - Use try/except/finally pattern to ensure consistent cleanup - Add sys import for exception handling
1 parent ee88b61 commit 3343670

1 file changed

Lines changed: 14 additions & 10 deletions

File tree

examples/reconnect_example.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
The application can then listen for this event and attempt to create a new
1111
BLEInterface instance to re-establish the connection, as shown in this example.
1212
"""
13+
import sys
1314
import threading
1415
import time
1516

@@ -57,23 +58,26 @@ def main():
5758

5859
# We must explicitly close the old interface before creating a new one
5960
iface.close()
60-
print("Interface closed. Reconnecting in 5 seconds...")
61-
time.sleep(5)
61+
print("Disconnected normally.")
6262

63-
except meshtastic.ble_interface.BLEInterface.BLEError as e:
64-
print(f"Connection failed: {e}")
65-
print("Retrying in 5 seconds...")
66-
time.sleep(5)
6763
except KeyboardInterrupt:
6864
print("Exiting...")
69-
# Make sure to close the interface on exit
70-
if iface:
71-
iface.close()
7265
break
66+
except meshtastic.ble_interface.BLEInterface.BLEError as e:
67+
print(f"Connection failed: {e}")
7368
except Exception as e:
7469
print(f"An unexpected error occurred: {e}")
75-
if iface:
70+
finally:
71+
# Close the interface on any exception to prevent resource leaks
72+
# (except KeyboardInterrupt which breaks the loop)
73+
current_exception = sys.exc_info()[1]
74+
if iface and current_exception and not isinstance(current_exception, KeyboardInterrupt):
7675
iface.close()
76+
print("Interface closed.")
77+
78+
# If we get here and didn't break due to KeyboardInterrupt, retry
79+
current_exception = sys.exc_info()[1]
80+
if not current_exception or isinstance(current_exception, (meshtastic.ble_interface.BLEInterface.BLEError, Exception)):
7781
print("Retrying in 5 seconds...")
7882
time.sleep(5)
7983

0 commit comments

Comments
 (0)