1. Overall Approach
This repository is based on MicroPython for ESP32 (ESP32 port) and ESP-IDF v5.x; error handling is divided into two levels:
C layer (compiled into the firmware): Located in
firmware/port/builtins/(ESP32 boards) andesp32s3/firmware/builtins/(ESP32-S3 boards); raises Python exceptions via MicroPython’smp_raise_*API.Python layer (loaded at runtime): Located in
firmware/port/modules/,esp32s3/firmware/boards/*/modules/, anddocs/examples/; usestry/exceptto catch standard exceptions such asOSErrorandValueError, and some modules also define custom Exception subclasses.
The project has no unified error-code enumeration or middleware-style error handler; errors propagate bottom-up in the manner of “the low-level C raises an exception -> the upper-level Python try/except catches it”.
2. C-Layer Error Model
2.1 MicroPython Exception Types Used
mp_raise_OSError(-ret): Used for I/O-type errors, converting the negative errno returned by ESP-IDF into a PythonOSError. Typical location: all I2C read/write failure paths inesp32s3/firmware/builtins/machine_i2c_extmod.c(such asmachine_i2c_start,machine_i2c_stop,machine_i2c_readinto,machine_i2c_write,machine_i2c_readfrom,machine_i2c_writeto,machine_i2c_writevto, etc.). This is the unified error exit of the I2C subsystem.mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("...")): Used for semantic errors, such asmachine_i2c_init/start/stop/read/writeraisingOSError("I2C operation not supported")when the corresponding function pointer is NULL.mp_raise_ValueError(...)/mp_raise_msg_varg(&mp_type_ValueError, ...): Used for argument-validation errors, such asinvalid pin,pin can only be input,bad wake value,no resources, andinvalid pin for wakeinmachine_pin.c;I2C(%d) doesn't existinmachine_i2c.c; andmachine_freqinmodmachine.craisingfrequency must be 20MHz, 40MHz, 80Mhz, 160MHz or 240MHzfor disallowed frequencies.mp_raise_TypeError/mp_raise_RuntimeError: Inmachine_sleep_helperinmodmachine.c, raisesRuntimeError("esp_sleep_enable_touchpad_wakeup() failed")when touch wake-up configuration fails.
2.2 Error Source Mapping
C File |
Main Responsibility |
Typical Errors |
|---|---|---|
|
Generic machine.I2C protocol binding |
I2C operation not supported, hardware returns negative errno |
|
Hardware I2C instantiation and argument validation |
Invalid I2C id |
|
GPIO Pin construction and irq/wake configuration |
Invalid pin, incompatible mode, wake resource conflict |
|
System-level features (freq/sleep/reset/unique_id) |
Illegal frequency, sleep/wake failure, soft reset |
2.3 Restart and Recovery
machine_reset(): Callsesp_restart()for a direct hard restart.machine_soft_reset(): Setspyexec_system_exit = PYEXEC_FORCED_EXITand raisesSystemExit, implementing a MicroPython interpreter-level soft reset.machine_reset_cause(): Maps ESP-IDF’sesp_reset_reason()to constants such asMP_PWRON_RESET,MP_WDT_RESET,MP_DEEPSLEEP_RESET,MP_HARD_RESET, andMP_SOFT_RESET, allowing the Python layer to diagnose the restart cause.
3. Python-Layer Error-Handling Conventions
3.1 Boot-Phase Fault Tolerance (_boot.py)
esp32s3/firmware/boards/labplus_Ledong_v2/modules/_boot.py demonstrates a typical boot fault-tolerance pattern:
Catches
OSErrorwhen mounting the file system fails and falls back toinisetup.setup()to rebuild the VFS.Operations such as obtaining the machine model and MAC address are all wrapped in
try/except; on failure they printUnknown machine/Unknown macinstead of interrupting the boot.Immediately turns off the RGB LED after power-on to prevent random lighting, part of an “initialize first, then attempt business logic” fault-tolerance strategy.
3.2 Retry + Explicit Exception in the Sensor/I2C Device Wrapper Layer
The magnetometer/accelerometer-related code in esp32s3/firmware/boards/labplus_Ledong_v2/modules/mpython.py exhibits a fixed pattern:
Each I2C read/write sequence is wrapped in an outer
retry < 5loop.Inside, a bare
try:catches all exceptions (including theOSErrorraised by the low-level I2C); on failure,retry += 1.After retries are exhausted,
raise Exception("i2c read/write error!")raises a genericExceptionwith no specific type, rather than anOSErroror a custom exception class. This pattern appears in several methods such as_get_raw,_get_temperature,_get_id, and_judge_id.
3.3 BLE Custom Exception
esp32s3/firmware/boards/labplus_Ledong_v2/modules/educore/mpython_ble/advertising/__init__.py defines class BLEError(Exception):, the only custom exception class observed in the repository, used for the BLE subsystem.
3.4 Network Error Handling in Example Code
The examples under docs/examples/network/ (http_server.py, tcpClient.py, udp_client.py, AnalogClock.py, DigitalClock.py, etc.) commonly use the try: ... except OSError: pattern to catch network I/O errors, reflecting the tutorial code’s convention of treating OSError as the network error.
4. Architecture and Layering Conventions
Layer |
Location |
Error Mechanism |
Description |
|---|---|---|---|
Hardware driver layer (C) |
|
|
Strictly follows the MicroPython exception system; error messages are provided via |
System interface layer (C) |
|
|
Exposes system capabilities such as |
Board-level Python module |
|
|
Wraps low-level I2C with retries, but the top level still raises a generic |
Boot script |
|
|
Ensures a robust boot process, degrading gracefully on failure |
User examples |
|
|
Teaching examples uniformly catch |
5. Constraints and Standards (Summarized from Code Behavior)
The C layer must not return error codes to Python: All low-level I2C/PIN operation failures are immediately converted into Python exceptions via
mp_raise_*; callers need not check return values.I2C errors are always mapped to
OSError: All negative return values inmachine_i2c_extmod.care uniformly converted viamp_raise_OSError(-ret), allowing the Python layer to handle them uniformly withexcept OSError.Argument-validation errors use
ValueError: Invalid pins, illegal frequencies, illegal wake values, etc. all raiseValueError, making it easy to distinguish “argument errors” from “runtime I/O errors”.The boot phase must tolerate exceptions:
_boot.pyaddstry/exceptaround all initialization steps that might fail, ensuring the boot continues even if some service is unavailable.The sensor wrapper layer uses a “retry + generic Exception” pattern: In
mpython.py, failed I2C access is retried up to 5 times, after which an untypedException("i2c read/write error!")is raised – this is a simplified design with no dedicated exception type defined.The restart cause is exposed via constants:
modmachine.cmaps ESP-IDF restart reasons to five integer constants –MP_PWRON_RESET,MP_WDT_RESET,MP_DEEPSLEEP_RESET,MP_HARD_RESET, andMP_SOFT_RESET– for querying by the Python layer’smachine.reset_cause().The BLE subsystem has an independent exception namespace:
BLEErrorinadvertising/__init__.pyis the only custom exception class, indicating that the BLE module intentionally isolates its error domain.
6. Key Files
esp32s3/firmware/builtins/machine_i2c_extmod.c– Unified error exit of the I2C protocol layeresp32s3/firmware/builtins/machine_i2c.c– I2C instantiation argument validationesp32s3/firmware/builtins/machine_pin.c– GPIO pin and wake configuration errorsfirmware/port/builtins/modmachine.c– System restart, sleep, frequency errors, and restart causesesp32s3/firmware/boards/labplus_Ledong_v2/modules/_boot.py– Boot fault-tolerance templateesp32s3/firmware/boards/labplus_Ledong_v2/modules/mpython.py– Sensor I2C retry and generic Exception patternesp32s3/firmware/boards/labplus_Ledong_v2/modules/educore/mpython_ble/advertising/__init__.py– BLE custom exceptionBLEErrordocs/examples/network/http_server.py,tcpClient.py,udp_client.py,AnalogClock.py,DigitalClock.py– Example-layertry/except OSErrorconvention