|
| 1 | +/* This example demonstrates the following features in a native module: |
| 2 | + - defining a simple function exposed to Python |
| 3 | + - defining a local, helper C function |
| 4 | + - getting and creating integer objects |
| 5 | +*/ |
| 6 | + |
| 7 | +// Include the header file to get access to the MicroPython API |
| 8 | +#include "py/dynruntime.h" |
| 9 | +// Include esp-idf include files |
| 10 | +#include "esp_system.h" |
| 11 | + |
| 12 | +// This is the function which will be called from Python, as free_heap() |
| 13 | +STATIC mp_obj_t free_heap() { |
| 14 | + // calling an ESP-IDF function |
| 15 | + uint32_t f = esp_get_free_heap_size(); |
| 16 | + // sample debug printf |
| 17 | + mp_printf(&mp_plat_print, "esp_get_free_heap_size returned %d\n", f); |
| 18 | + // return integer as MP small int object |
| 19 | + return mp_obj_new_int(f); |
| 20 | +} |
| 21 | +// Define a Python reference to the function above |
| 22 | +STATIC MP_DEFINE_CONST_FUN_OBJ_0(free_heap_obj, free_heap); |
| 23 | + |
| 24 | +// This a function that only exists in esp-idf-v4, it will raise in esp-idf-v3. |
| 25 | +STATIC mp_obj_t flash_encryption_mode() { |
| 26 | + // calling an ESP-IDF function that doesn't exist in v3 |
| 27 | + extern uint32_t esp_get_flash_encryption_mode(); |
| 28 | + uint32_t f = esp_get_flash_encryption_mode(); |
| 29 | + // return integer as MP small int object |
| 30 | + return mp_obj_new_int(f); |
| 31 | +} |
| 32 | +// Define a Python reference to the function above |
| 33 | +STATIC MP_DEFINE_CONST_FUN_OBJ_0(flash_encryption_mode_obj, flash_encryption_mode); |
| 34 | + |
| 35 | +// This is the entry point and is called when the module is imported |
| 36 | +mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) { |
| 37 | + // This must be first, it sets up the globals dict and other things |
| 38 | + MP_DYNRUNTIME_INIT_ENTRY |
| 39 | + |
| 40 | + // Make the functions available in the module's namespace |
| 41 | + mp_store_global(MP_QSTR_free_heap, MP_OBJ_FROM_PTR(&free_heap_obj)); |
| 42 | + mp_store_global(MP_QSTR_flash_encryption_mode, MP_OBJ_FROM_PTR(&flash_encryption_mode_obj)); |
| 43 | + |
| 44 | + // This must be last, it restores the globals dict |
| 45 | + MP_DYNRUNTIME_INIT_EXIT |
| 46 | +} |
0 commit comments