|
14 | 14 | import coloredlogs, logging |
15 | 15 | import re |
16 | 16 | from typing import List, Tuple, Optional |
| 17 | +import sys |
| 18 | +import serial |
| 19 | + |
| 20 | +serial_busy_msg = ( |
| 21 | + "Port is busy or disconnected. Please ensure no other program is using the serial port." |
| 22 | +) |
| 23 | + |
| 24 | +timeout_msg = ( |
| 25 | + "Unable to communicate with device. Please check that:\n" |
| 26 | + "- The correct serial port is selected\n" |
| 27 | + "- Your project has one of these two options enabled:\n" |
| 28 | + " * AT Host Library (CONFIG_AT_HOST_LIBRARY)\n" |
| 29 | + " * AT Shell (CONFIG_AT_SHELL)" |
| 30 | +) |
17 | 31 |
|
18 | 32 | logger = logging.getLogger(__name__) |
19 | 33 |
|
@@ -93,15 +107,23 @@ def set_shell_mode(self, shell: bool): |
93 | 107 | self.shell = shell |
94 | 108 |
|
95 | 109 | def detect_shell_mode(self): |
96 | | - """Detect if the device is in shell mode or not.""" |
97 | | - for cmd, shell_mode in [("at AT+CGSN", True), ("AT+CGSN", False)]: |
98 | | - for _ in range(3): |
99 | | - self.write_raw(cmd) |
100 | | - result, output = self.comms.expect_response("OK", "ERROR", "", suppress_errors=True, timeout=2) |
101 | | - if result and len(re.findall("[0-9]{15}", output)) > 0: |
102 | | - self.set_shell_mode(shell_mode) |
103 | | - return |
104 | | - raise TimeoutError("Failed to detect shell mode. Device does not respond to AT commands.") |
| 110 | + """Detect if the device is in shell mode or not. """ |
| 111 | + try: |
| 112 | + for cmd, shell_mode in [("at AT+CGSN", True), ("AT+CGSN", False)]: |
| 113 | + for _ in range(3): |
| 114 | + self.write_raw(cmd) |
| 115 | + result, output = self.comms.expect_response("OK", "ERROR", "", suppress_errors=True, timeout=2) |
| 116 | + if result and len(re.findall("[0-9]{15}", output)) > 0: |
| 117 | + self.set_shell_mode(shell_mode) |
| 118 | + return |
| 119 | + except serial.SerialException as e: |
| 120 | + # Port is busy or disconnected (likely due to multiple access) |
| 121 | + logger.error(serial_busy_msg) |
| 122 | + sys.exit(13) # ERR_SERIAL |
| 123 | + |
| 124 | + # Timeout: no valid response received |
| 125 | + logger.error(timeout_msg) |
| 126 | + sys.exit(12) # ERR_TIMEOUT |
105 | 127 |
|
106 | 128 | def enable_error_codes(self): |
107 | 129 | """Enable error codes in the AT client""" |
|
0 commit comments