--- kind: error_handling name: "MicroPython C Extension and Python-Layer Error Handling: OSError/ValueError, Exception Catching, and Boot Fault Tolerance" category: error_handling scope: - '**' source_files: - esp32s3/firmware/builtins/machine_i2c_extmod.c - esp32s3/firmware/builtins/machine_i2c.c - esp32s3/firmware/builtins/machine_pin.c - firmware/port/builtins/modmachine.c - esp32s3/firmware/boards/labplus_Ledong_v2/modules/_boot.py - esp32s3/firmware/boards/labplus_Ledong_v2/modules/mpython.py - esp32s3/firmware/boards/labplus_Ledong_v2/modules/educore/mpython_ble/advertising/__init__.py - docs/examples/network/http_server.py - docs/examples/network/tcpClient.py - docs/examples/network/udp_client.py - docs/examples/network/clock/AnalogClock.py - docs/examples/network/clock/DigitalClock.py --- # 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) and `esp32s3/firmware/builtins/` (ESP32-S3 boards); raises Python exceptions via MicroPython's `mp_raise_*` API. - **Python layer (loaded at runtime)**: Located in `firmware/port/modules/`, `esp32s3/firmware/boards/*/modules/`, and `docs/examples/`; uses `try/except` to catch standard exceptions such as `OSError` and `ValueError`, 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 Python `OSError`. Typical location: all I2C read/write failure paths in `esp32s3/firmware/builtins/machine_i2c_extmod.c` (such as `machine_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 as `machine_i2c_init`/`start`/`stop`/`read`/`write` raising `OSError("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 as `invalid pin`, `pin can only be input`, `bad wake value`, `no resources`, and `invalid pin for wake` in `machine_pin.c`; `I2C(%d) doesn't exist` in `machine_i2c.c`; and `machine_freq` in `modmachine.c` raising `frequency must be 20MHz, 40MHz, 80Mhz, 160MHz or 240MHz` for disallowed frequencies. - `mp_raise_TypeError` / `mp_raise_RuntimeError`: In `machine_sleep_helper` in `modmachine.c`, raises `RuntimeError("esp_sleep_enable_touchpad_wakeup() failed")` when touch wake-up configuration fails. ## 2.2 Error Source Mapping | C File | Main Responsibility | Typical Errors | |---|---|---| | `esp32s3/firmware/builtins/machine_i2c_extmod.c` | Generic machine.I2C protocol binding | I2C operation not supported, hardware returns negative errno | | `esp32s3/firmware/builtins/machine_i2c.c` | Hardware I2C instantiation and argument validation | Invalid I2C id | | `esp32s3/firmware/builtins/machine_pin.c` | GPIO Pin construction and irq/wake configuration | Invalid pin, incompatible mode, wake resource conflict | | `firmware/port/builtins/modmachine.c` | System-level features (freq/sleep/reset/unique_id) | Illegal frequency, sleep/wake failure, soft reset | ## 2.3 Restart and Recovery - `machine_reset()`: Calls `esp_restart()` for a direct hard restart. - `machine_soft_reset()`: Sets `pyexec_system_exit = PYEXEC_FORCED_EXIT` and raises `SystemExit`, implementing a MicroPython interpreter-level soft reset. - `machine_reset_cause()`: Maps ESP-IDF's `esp_reset_reason()` to constants such as `MP_PWRON_RESET`, `MP_WDT_RESET`, `MP_DEEPSLEEP_RESET`, `MP_HARD_RESET`, and `MP_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 `OSError` when mounting the file system fails and falls back to `inisetup.setup()` to rebuild the VFS. - Operations such as obtaining the machine model and MAC address are all wrapped in `try/except`; on failure they print `Unknown machine` / `Unknown mac` instead 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 < 5` loop. - Inside, a bare `try:` catches all exceptions (including the `OSError` raised by the low-level I2C); on failure, `retry += 1`. - After retries are exhausted, `raise Exception("i2c read/write error!")` raises a **generic `Exception` with no specific type**, rather than an `OSError` or 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) | `esp32s3/firmware/builtins/*.c` | `mp_raise_OSError` / `mp_raise_ValueError` | Strictly follows the MicroPython exception system; error messages are provided via `MP_ERROR_TEXT` | | System interface layer (C) | `firmware/port/builtins/modmachine.c` | `mp_raise_*` + reset constants | Exposes system capabilities such as `reset_cause`, `soft_reset`, and `sleep` | | Board-level Python module | `esp32s3/firmware/boards/*/modules/mpython.py` | `try/except` + retry + `raise Exception(...)` | Wraps low-level I2C with retries, but the top level still raises a generic `Exception` | | Boot script | `*_boot.py` | `try/except OSError` | Ensures a robust boot process, degrading gracefully on failure | | User examples | `docs/examples/*` | `try/except OSError` | Teaching examples uniformly catch `OSError` | # 5. Constraints and Standards (Summarized from Code Behavior) 1. **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. 2. **I2C errors are always mapped to `OSError`**: All negative return values in `machine_i2c_extmod.c` are uniformly converted via `mp_raise_OSError(-ret)`, allowing the Python layer to handle them uniformly with `except OSError`. 3. **Argument-validation errors use `ValueError`**: Invalid pins, illegal frequencies, illegal wake values, etc. all raise `ValueError`, making it easy to distinguish "argument errors" from "runtime I/O errors". 4. **The boot phase must tolerate exceptions**: `_boot.py` adds `try/except` around all initialization steps that might fail, ensuring the boot continues even if some service is unavailable. 5. **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 untyped `Exception("i2c read/write error!")` is raised -- this is a simplified design with no dedicated exception type defined. 6. **The restart cause is exposed via constants**: `modmachine.c` maps ESP-IDF restart reasons to five integer constants -- `MP_PWRON_RESET`, `MP_WDT_RESET`, `MP_DEEPSLEEP_RESET`, `MP_HARD_RESET`, and `MP_SOFT_RESET` -- for querying by the Python layer's `machine.reset_cause()`. 7. **The BLE subsystem has an independent exception namespace**: `BLEError` in `advertising/__init__.py` is 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 layer - `esp32s3/firmware/builtins/machine_i2c.c` -- I2C instantiation argument validation - `esp32s3/firmware/builtins/machine_pin.c` -- GPIO pin and wake configuration errors - `firmware/port/builtins/modmachine.c` -- System restart, sleep, frequency errors, and restart causes - `esp32s3/firmware/boards/labplus_Ledong_v2/modules/_boot.py` -- Boot fault-tolerance template - `esp32s3/firmware/boards/labplus_Ledong_v2/modules/mpython.py` -- Sensor I2C retry and generic Exception pattern - `esp32s3/firmware/boards/labplus_Ledong_v2/modules/educore/mpython_ble/advertising/__init__.py` -- BLE custom exception `BLEError` - `docs/examples/network/http_server.py`, `tcpClient.py`, `udp_client.py`, `AnalogClock.py`, `DigitalClock.py` -- Example-layer `try/except OSError` convention