Porównaj commity

...

361 Commity

Autor SHA1 Wiadomość Data
Angus Gratton c3301da176 docs/library/machine.USBDevice: Update note about packages in mp-lib.
Also fix a small typo.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-05-09 15:48:26 +10:00
Angus Gratton 9a43989a86 shared/tinyusb: Stall the CDC IN endpoint while disconnecting.
Only when dynamic USB devices are enabled.

The issue here is that when the USB reset triggers, the dynamic USB device
reset callback is called from inside the TinyUSB task.

If that callback tries to print something then it'll call through to
tud_cdc_write_flush(), but TinyUSB hasn't finished updating state yet to
know it's no longer configured. Subsequently it may try to queue a transfer
and then the low-level DCD layer panics.

By explicitly stalling the endpoint first, usbd_edpt_claim() will fail and
tud_cdc_write_flush() returns immediately.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-05-09 15:22:31 +10:00
Jared Hancock 8762fe8b4c extmod/network_wiznet5k: Properly enable socket buffers for W5100(S).
The W5100 and W5100S only have 4 available sockets and 16kB of socket
buffer.  Allocating 16kB to either the receive or transmit buffer of a
single socket is not allowed, so the current setup does not change the
allocation for socket 0 from the reset default.  ctlwizchip is returning -1
to indicate the error, but the response isn't being inspected and probably
doesn't need to be.

Signed-off-by: Jared Hancock <jared@greezybacon.me>
2024-05-07 17:42:34 +10:00
Rick Sorensen 63c30a2dfc esp32/modesp32: Add mcu_temperature() function for C3/S2/S3 devices.
For ESP32C3/S2/S3 IDFv5 exposes new internal temperature API which is
different to the base ESP32, IDFv4.

Thanks to @robert-hh for cleaner code and testing sensor capability in
these devices.

See discussion #10443.

Signed-off-by: Rick Sorensen <rick.sorensen@gmail.com>
2024-05-07 17:29:22 +10:00
Rick Sorensen 595f86155a docs/esp32/quickref: Add note about different ESP32 varieties.
Signed-off-by: Rick Sorensen <rick.sorensen@gmail.com>
2024-05-07 17:28:25 +10:00
Damien George be1ecb54e6 webassembly/api: Resolve thenables returned from runPythonAsync.
JavaScript semantics are such that the caller of an async function does not
need to await that function for it to run to completion.  This commit makes
that behaviour also apply to top-level async Python code run via
`runPythonAsync()`.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-07 11:33:05 +10:00
Damien George c056840ee8 webassembly/objpyproxy: Implement JS iterator protocol for Py iterables.
This allows using JavaScript for..of on Python iterables.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-07 00:20:56 +10:00
Damien George e860e32e24 webassembly/objjsproxy: Fix proxying in arguments to JS new function.
Signed-off-by: Damien George <damien@micropython.org>
2024-05-06 14:47:05 +10:00
Damien George 50b43fec1a webassembly/proxy_c: Only proxy across resolve/reject funs when needed.
To improve efficiency.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-06 14:04:22 +10:00
Damien George 9da63a343e webassembly/proxy_c: Reject promises with a PythonError instance.
The `reason` in a rejected promise should be an instance of `Error`.  That
leads to better error messages on the JavaScript side.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-06 14:04:13 +10:00
Damien George 9681a66c6b webassembly/api: Fix importing micropython.mjs module from node REPL.
Fixes issue #14363.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-06 13:53:58 +10:00
Damien George a521df27dc stm32/i2c: Fix clock enable for I2C4 on STM32F7 MCUs.
This was broken by 5aec051f9f when adding
support for I2C4 on H7 MCUs.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-03 17:22:22 +10:00
Damien George a7d34b6f7c stm32/mboot: Buffer the correct amount of bytes for a flash write.
Different MCUs have different requirements for the minimum number of bytes
that can be written to internal flash.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-01 22:49:38 +10:00
Damien George d3fe0a06e8 stm32/flash: Fix writing final words to flash on H5 and H7 MCUs.
The calculations `num_word32 / 4` and `num_word32 / 8` were rounding down
the number of words to program to flash, and therefore possibly truncating
the data (eg mboot could miss writing the final few words of the firmware).

That's fixed in this commit by adding extra logic to program any remaining
words.  And the logic for H5 and H7 is combined.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-01 22:49:38 +10:00
Damien George 64f28dc1eb stm32/boards/LEGO_HUB_NO7: Add robust update logic to mboot.
Following change in 899592ac34

Signed-off-by: Damien George <damien@micropython.org>
2024-05-01 16:16:33 +10:00
Damien George b896fa9b1f stm32/boards/LEGO_HUB_NO6: Write key after writing elements.
In case there is a power failure after during this operation, the key must
be the last thing that is written, to indicate valid data.

Signed-off-by: Damien George <damien@micropython.org>
2024-05-01 15:44:32 +10:00
Matt Trentini b1ac266bb5 docs/develop/optimizations: Fix typo identified in issue 14391.
Signed-off-by: Matt Trentini <matt.trentini@gmail.com>
2024-04-29 09:20:28 +10:00
Damien George e60e8079a7 nrf/mpconfigport: Enable MICROPY_NLR_THUMB_USE_LONG_JUMP on nRF51xx.
Signed-off-by: Damien George <damien@micropython.org>
2024-04-26 11:15:59 +10:00
J. Neuschäfer 7b050b366b py/nlrthumb: Make non-Thumb2 long-jump workaround opt-in.
Although the original motivation given for the workaround[1] is correct,
nlr.o and nlrthumb.o are linked with a small enough distance that the
problem does not occur, and the workaround isn't necessary. The distance
between the b instruction and its target (nlr_push_tail) is just 64
bytes[2], well within the ±2046 byte range addressable by an
unconditional branch instruction in Thumb mode.

The workaround induces a relocation in the text section (textrel), which
isn't supported everywhere, notably not on musl-libc[3], where it causes
a crash on start-up. With the workaround removed, micropython works on an
ARMv5T Linux system built with musl-libc.

This commit changes nlrthumb.c to use a direct jump by default, but
leaves the long jump workaround as an option for those cases where it's
actually needed.

[1]: commit dd376a239d

Author: Damien George <damien.p.george@gmail.com>
Date:   Fri Sep 1 15:25:29 2017 +1000

    py/nlrthumb: Get working again on standard Thumb arch (ie not Thumb2).

    "b" on Thumb might not be long enough for the jump to nlr_push_tail so
    it must be done indirectly.

[2]: Excerpt from objdump -d micropython:

000095c4 <nlr_push_tail>:
    95c4:       b510            push    {r4, lr}
    95c6:       0004            movs    r4, r0
    95c8:       f02d fd42       bl      37050 <mp_thread_get_state>
    95cc:       6943            ldr     r3, [r0, #20]
    95ce:       6023            str     r3, [r4, #0]
    95d0:       6144            str     r4, [r0, #20]
    95d2:       2000            movs    r0, #0
    95d4:       bd10            pop     {r4, pc}

000095d6 <nlr_pop>:
    95d6:       b510            push    {r4, lr}
    95d8:       f02d fd3a       bl      37050 <mp_thread_get_state>
    95dc:       6943            ldr     r3, [r0, #20]
    95de:       681b            ldr     r3, [r3, #0]
    95e0:       6143            str     r3, [r0, #20]
    95e2:       bd10            pop     {r4, pc}

000095e4 <nlr_push>:
    95e4:       60c4            str     r4, [r0, #12]
    95e6:       6105            str     r5, [r0, #16]
    95e8:       6146            str     r6, [r0, #20]
    95ea:       6187            str     r7, [r0, #24]
    95ec:       4641            mov     r1, r8
    95ee:       61c1            str     r1, [r0, #28]
    95f0:       4649            mov     r1, r9
    95f2:       6201            str     r1, [r0, #32]
    95f4:       4651            mov     r1, sl
    95f6:       6241            str     r1, [r0, #36]   @ 0x24
    95f8:       4659            mov     r1, fp
    95fa:       6281            str     r1, [r0, #40]   @ 0x28
    95fc:       4669            mov     r1, sp
    95fe:       62c1            str     r1, [r0, #44]   @ 0x2c
    9600:       4671            mov     r1, lr
    9602:       6081            str     r1, [r0, #8]
    9604:       e7de            b.n     95c4 <nlr_push_tail>

[3]: https://www.openwall.com/lists/musl/2020/09/25/4

Signed-off-by: J. Neuschäfer <j.ne@posteo.net>
2024-04-25 16:06:28 +10:00
Damien George 49af8cad49 webassembly/api: Inject asyncio.run if needed by the script.
This allows a simple way to run the existing asyncio tests under the
webassembly port, which doesn't support `asyncio.run()`.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 16:24:00 +10:00
Damien George 8a3546b3bd webassembly: Add JavaScript-based asyncio support.
This commit adds a significant portion of the existing MicroPython asyncio
module to the webassembly port, using parts of the existing asyncio code
and some custom JavaScript parts.

The key difference to the standard asyncio is that this version uses the
JavaScript runtime to do the actual scheduling and waiting on events, eg
Promise fulfillment, timeouts, fetching URLs.

This implementation does not include asyncio.run(). Instead one just uses
asyncio.create_task(..) to start tasks and then returns to the JavaScript.
Then JavaScript will run the tasks.

The implementation here tries to reuse as much existing asyncio code as
possible, and gets all the semantics correct for things like cancellation
and asyncio.wait_for.  An alternative approach would reimplement Task,
Event, etc using JavaScript Promise's.  That approach is very difficult to
get right when trying to implement cancellation (because it's not possible
to cancel a JavaScript Promise).

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 16:24:00 +10:00
Damien George 84d6f8e8cb webassembly/modjsffi: Add jsffi.async_timeout_ms.
This function exposes `setTimeout()` as an async function.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 16:24:00 +10:00
Damien George 967ad38ac7 extmod/modasyncio: Make mp_asyncio_context variable public.
So it can be accessed by a port if needed, for example to see if asyncio
has been imported.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 16:23:59 +10:00
Damien George d998ca78c8 webassembly/proxy_c: Fix then-continue to convert reason to throw value.
When a Promise is rejected on the JavaScript side, the reject reason should
be thrown into the encapsulating generator on the Python side.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 16:23:42 +10:00
Damien George 92b3b69648 webassembly/proxy_c: Fix proxy then reject handling.
An exception on the Python side should be passed to the Promise reject
callback on the JavaScript side.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 16:14:17 +10:00
Damien George 4c3f5f552b webassembly/objjsproxy: Fix handling of thrown value into JS generator.
Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 16:07:00 +10:00
Damien George 9c7f0659e2 webassembly/api: Allocate code data on C heap when running Python code.
Otherwise Emscripten allocates it on the Emscripten C stack, which will
overflow for large amounts of code.

Fixes issue #14307.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 13:15:54 +10:00
Damien George 45848f77ca webassembly/api: Fix waiting for Emscripten module to be loaded.
In modularize mode, the `_createMicroPythonModule()` constructor must be
await'ed on, before `Module` is ready to use.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-24 13:15:54 +10:00
Damien George 49ce7a6075 github/workflows: Run code size workflow on shared or port code changes.
To get more insight to firmware size changes when code changes.

Signed-off-by: Damien George <damien@micropython.org>
2024-04-22 12:38:29 +10:00
Angus Gratton 6877987002 tests/cpydiff: Add a note about risk of resizing memoryview targets.
This a stop-gap until there is a proper fix for this.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-04-22 11:51:18 +10:00
Angus Gratton 4bed614e70 py/objarray: Fix use-after-free if extending a bytearray from itself.
Two cases, one assigning to a slice.
Closes https://github.com/micropython/micropython/issues/13283

Second is extending a slice from itself, similar logic.

In both cases the problem occurs when m_renew causes realloc to move the
buffer, leaving a dangling pointer behind.

There are more complex and hard to fix cases when either argument is a
memoryview into the buffer, currently resizing to a new address breaks
memoryviews into that object.

Reproducing this bug and confirming the fix was done by running the unix
port under valgrind with GC-aware extensions.

Note in default configurations with GIL this bug exists but has no impact
(the free buffer won't be reused while the function is still executing, and
is no longer referenced after it returns).

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-04-22 11:50:52 +10:00
Vonasmic ce491ab0d1 py/obj: Fix initialiser order in MP_DEFINE_CONST_OBJ_TYPE_NARGS_ macros.
This commit swaps the order of the `flags` and `name` struct initialisers
for `mp_obj_type_t`, to fix an incompatibility with C++.  The original
order of the initialiser didn't match the definition of the type, and
although that's still legal C, it's not legal C++.

Signed-off-by: Vonasmic <kasarkal123@gmail.com>
2024-04-22 11:10:23 +10:00
stijn 40f7e9ce20 py/objfun: Fix C++ compatibility with casting in inline functions.
Explicit casts are needed.

Fixes recent changes from 648a7578da and
9400229766.

Signed-off-by: stijn <stijn@ignitron.net>
2024-04-22 10:34:01 +10:00
Michiel W. Beijen 3129b69e0f rp2/README: Fix typo, improve sentence about building with other boards.
Signed-off-by: Michiel W. Beijen <mb@x14.nl>
2024-04-22 10:20:54 +10:00
Simon Wood 19844b4983 rp2/modmachine: Prevent lock-up when lightsleep() called within thread.
When `lightsleep()` is called from within a thread the interrupts may not
be enabled on current core, and thus the call to `lightsleep()` never
completes.

Fixes issue #14092.

Signed-off-by: Simon Wood <simon@mungewell.org>
2024-04-22 10:09:30 +10:00
J. Neuschäfer f76cf29402 github/workflows: Update coverage workflow to codecov-action@v4.
Fixes: https://github.com/micropython/micropython/issues/14340

Signed-off-by: J. Neuschäfer <j.ne@posteo.net>
2024-04-20 19:43:50 +02:00
Angus Gratton d11ca092f7 shared/tinyusb: Fix dynamic USB control callbacks for wLength==0.
In the case where an OUT control transfer triggers with wLength==0 (i.e.
all data sent in the SETUP phase, and no additional data phase) the
callbacks were previously implemented to return b"" (i.e. an empty buffer
for the data phase).

However this didn't actually work as intended because b"" can't provide a
RW buffer (needed for OUT transfers with a data phase to write data into),
so actually the endpoint would stall.

The symptom was often that the device process the request (if processing
it in the SETUP phase when all information was already available), but the
host sees the endpoint stall and eventually returns an error.

This commit changes the behaviour so returning True from the SETUP phase of
a control transfer queues a zero length status response.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-04-17 12:39:47 +10:00
iabdalkader 53d0050255 lib/arduino-lib: Update submodule to the latest.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-04-11 17:04:10 +02:00
Damien George 5114f2c1ea webassembly/proxy_js: Allow a Python proxy of a function to be undone.
This optimises the case where a Python function is, for example, stored to
a JavaScript attribute and then later retrieved from Python.  The Python
function no longer needs to be a proxy with double proxying needed for the
call from Python -> JavaScript -> Python.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-30 13:13:51 +11:00
Damien George 7c62fbe3f2 webassembly/proxy_js: Promote Python thenable to a Promise.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-30 13:13:51 +11:00
Damien George 3997532186 webassembly/proxy_c: Ensure return value of async fun is passed to JS.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-30 13:13:51 +11:00
iabdalkader 87d821ab49 mimxrt: Add support for OpenAMP.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-29 17:59:29 +11:00
iabdalkader 23d7a915c1 stm32/mpremoteprocport: Use metal logging functions.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-29 17:59:18 +11:00
iabdalkader 8936d3af46 extmod/modopenamp: Use metal logging functions exclusively.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-29 17:59:04 +11:00
iabdalkader aa0f3ebe93 extmod/modopenamp: Set a default log handler for ports.
Use the existing metal log handling mechanism instead of overriding the
metal_log, which causes build issues when logging is enabled.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-29 17:58:18 +11:00
Damien George b829450359 samd/mcu: Guard static function with appropriate #if.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-29 17:48:06 +11:00
Damien George 20a86eff53 tests/net_inet: Add simpler tls sites test, and skip existing on axtls.
Ports that use axtls cannot run the `test_tls_sites.py` test because the
sites it connects to use advanced ciphers.  So skip this test on such
ports, and add a new, simpler test that doesn't require certificate
verification and works with axtls.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-29 10:46:09 +11:00
Damien George c3e37d1fac extmod/modtls_axtls: Add verify_mode and CERT_NONE constant.
Supporting `verify_mode` and `CERT_NONE` is required for the new `ssl.py`
code, as well as `requests` to work.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-28 17:36:13 +11:00
Damien George 628a37e6cf docs/reference/mpyfiles: Document change in .mpy sub-version.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-28 16:21:35 +11:00
Damien George bdbc869f9e py/persistentcode: Bump .mpy sub-version to 6.3.
This is required because the .mpy native ABI was changed by the
introduction of `mp_proto_fun_t`, see commits:
- 416465d81e
- 5e3006f117
- e2ff00e811

And three `mp_binary` functions were added to `mp_fun_table` in
commit d2276f0d41.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-28 16:18:26 +11:00
Damien George 8b0efde927 examples/natmod/framebuf: Enable FrameBuffer.poly method.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-28 16:18:09 +11:00
Damien George d2276f0d41 py/dynruntime: Add mp_binary_get_size/get_val_array/set_val_array.
These are needed to read/write array.array objects, which is useful in
native code to provide fast extensions that work with big arrays of data.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-28 16:18:09 +11:00
robert-hh 4662a71f44 drivers/memory: Add IS25LPWP064D chip to list of external flash devices.
Confirguration provided by by @ironss-iotec.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-28 15:52:40 +11:00
robert-hh d9b9e88899 samd/samd_qspiflash: Avoid reading status byte 2 when not available.
Change provided by @ironss-iotec.

Tested with Adafruit, SEEED and MiniFig boards for non-interference.

Fixes issue #14190.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-28 15:52:40 +11:00
robert-hh 3980b36173 samd/samd_spiflash: Allow configuring the flash SPI baudrate.
Using a define for MICROPY_HW_SPIFLASH_BAUDRATE in mpconfigboard.h.  If not
defined the default is 24MHz.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-28 15:52:28 +11:00
robert-hh e8e9a39a6d samd/mcu: Update clock config after changes to USB.
For all MCUs: run the test for USB clock recovery mode fallback after USB
has been started.

For samd21: change DFLL48 config from the open loop mode variant to sync
with the XOSC32KULP.  Matches better the 48MHz value.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-28 15:49:41 +11:00
robert-hh b41360d119 samd/boards: Enable MICROPY_HW_DFLL_USB_SYNC on appropriate boards.
For the boards ADAFRUIT_TRINKET_M0 and MINISAM_M4.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-28 15:37:01 +11:00
robert-hh 328b6df058 samd/README: Fix incorrect port directory name.
At a single place, STM32 was used instead of SAMD.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-28 15:36:26 +11:00
iabdalkader e8dd519e2d esp32/network_wlan: Add interface and security WLAN constants.
Following the same change to extmod network interfaces.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-28 13:01:55 +11:00
iabdalkader 81dff08bf2 esp8266/network_wlan: Add interface and security WLAN constants.
Following the same change to extmod network interfaces.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-28 13:01:55 +11:00
iabdalkader 7753045a8f extmod: Add interface and security constants at WLAN class level.
Other constants such as `machine.Pin.OUT` are defined on the class that
uses them, rather than at the module level.  This commit makes that the
case for WLAN network interfaces, adding IF_xxx and SEC_xxx constants.

The SEC_xxx constants are named as such to match the `security` keyword
that they are used with.  And the IF_xxx constants have IF as a prefix so
they are grouped together as names.

This scheme of putting constants on the class means that only the available
features (eg security configurations) are made available as constants.  It
also means that different network interfaces (eg WLAN vs LAN) can keep
their own specific constants within their class, such as PHY_xxx for LAN.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-28 12:52:28 +11:00
iabdalkader 5a7d78c732 mimxrt,stm32: Set the security mode for the default WiFi AP.
The default CYW43 WiFi AP settings were missing the security mode, leaving
the AP in open mode by default.  That's changed by this commit to use
WPA/WPA2 by default.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-28 12:51:50 +11:00
Matt Trentini db1b5df16c stm32/README: Update list of supported STM32 series.
Signed-off-by: Matt Trentini <matt.trentini@gmail.com>
2024-03-28 12:34:46 +11:00
Damien George 35e8d184b1 shared/tinyusb: Increase default string descr max length to 40 chars.
When defining custom USB devices, longer strings may be needed.  Eventually
the memory for string descriptors can be allocated on demand, but for now
this bigger value should be reasonable.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-27 23:57:57 +11:00
Angus Gratton 0f16ae92c0 shared/tinyusb: Update some code comments for runtime USB.
Updates a few code comments that were out of date or poorly worded. No code
changes.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-27 23:55:41 +11:00
Angus Gratton 935f5391b5 shared/tinyusb: Don't disconnect on soft reset unless USB was active.
Previously, constructing the singleton USBDevice object was enough to
trigger a USB disconnect on soft reset. Now it also has to be active.

The only case where this changes the behaviour is if the USBDevice object
has been constructed but never set to active (no more disconnect in this
case). Otherwise, behaviour is the same.

This change was requested by hippy on the raspberrypi forums.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-27 23:54:12 +11:00
Damien George 79edaddf50 rp2/CMakeLists: Apply O2 optimisation to map, mpz and vm source code.
Enabling this optimisation increases the RPI_PICO firmware by +3344 bytes.

Performace change is:

diff of scores (higher is better)
N=100 M=100             rpi-base -> rpi-opt      diff      diff% (error%)
bm_chaos.py               196.56 ->  215.26 :  +18.70 =  +9.514% (+/-0.05%)
bm_fannkuch.py             52.47 ->   54.37 :   +1.90 =  +3.621% (+/-0.05%)
bm_fft.py                1476.74 -> 1530.06 :  +53.32 =  +3.611% (+/-0.01%)
bm_float.py              2305.65 -> 2444.11 : +138.46 =  +6.005% (+/-0.08%)
bm_hexiom.py               32.83 ->   35.09 :   +2.26 =  +6.884% (+/-0.05%)
bm_nqueens.py            2335.85 -> 2259.78 :  -76.07 =  -3.257% (+/-0.06%)
bm_pidigits.py            366.23 ->  465.81 :  +99.58 = +27.191% (+/-0.04%)
bm_wordcount.py            41.20 ->   41.87 :   +0.67 =  +1.626% (+/-0.01%)
core_import_mpy_multi.py  327.44 ->  335.24 :   +7.80 =  +2.382% (+/-0.08%)
core_import_mpy_single.py  63.41 ->   64.98 :   +1.57 =  +2.476% (+/-0.21%)
core_locals.py             27.24 ->   29.19 :   +1.95 =  +7.159% (+/-0.01%)
core_qstr.py              137.31 ->  140.84 :   +3.53 =  +2.571% (+/-0.03%)
core_str.py                18.44 ->   18.10 :   -0.34 =  -1.844% (+/-0.03%)
core_yield_from.py        221.69 ->  211.72 :   -9.97 =  -4.497% (+/-0.01%)
misc_aes.py               303.38 ->  308.72 :   +5.34 =  +1.760% (+/-0.02%)
misc_mandel.py           1501.00 -> 1746.60 : +245.60 = +16.362% (+/-0.04%)
misc_pystone.py          1348.22 -> 1456.75 : +108.53 =  +8.050% (+/-0.07%)
misc_raytrace.py          223.81 ->  246.16 :  +22.35 =  +9.986% (+/-0.07%)
viper_call0.py            331.05 ->  331.10 :   +0.05 =  +0.015% (+/-0.00%)
viper_call1a.py           323.34 ->  323.39 :   +0.05 =  +0.015% (+/-0.00%)
viper_call1b.py           241.01 ->  241.04 :   +0.03 =  +0.012% (+/-0.00%)
viper_call1c.py           242.88 ->  242.92 :   +0.04 =  +0.016% (+/-0.00%)
viper_call2a.py           318.41 ->  318.46 :   +0.05 =  +0.016% (+/-0.00%)
viper_call2b.py           211.27 ->  211.30 :   +0.03 =  +0.014% (+/-0.00%)

And the test `tests/basics/builtin_pow3_intbig.py` now passes (it uses a
lot of mpz code and previously took longer than 10 seconds to run on
RPI_PICO, which would lead to a timeout in the test runner).

Signed-off-by: Damien George <damien@micropython.org>
2024-03-27 12:16:30 +11:00
Jim Mussared d694ac6e1b py/makeqstrdata.py: Ensure that scope names get low qstr values.
Originally implemented in a patch file provided by @ironss-iotec.

Fixes issue #14093.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2024-03-26 22:52:25 +11:00
Amirreza Hamzavi 57de9da352 docs/library/machine.RTC: Add docs for RTC.memory() method.
Co-Authored-By: glenn20 <glenn20@users.noreply.github.com>

Signed-off-by: Amirreza Hamzavi <amirrezahamzavi2000@gmail.com>
2024-03-26 17:59:06 +11:00
Jim Mussared a0d31e54ae esp8266/Makefile: Add support for C++ user C modules.
This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2024-03-26 17:41:34 +11:00
iabdalkader fa6ccc7e72 renesas-ra/boards/ARDUINO_PORTENTA_C33: Add Arduino's external library.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-26 17:03:56 +11:00
iabdalkader da09646eab stm32/boards/ARDUINO_PORTENTA_H7: Add Arduino's external library.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-26 17:03:56 +11:00
iabdalkader 723cd03aeb stm32/boards/ARDUINO_NICLA_VISION: Add Arduino's external library.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-26 17:03:56 +11:00
iabdalkader 27aa3c19bf stm32/boards/ARDUINO_GIGA: Add Arduino's external library.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-26 17:03:56 +11:00
iabdalkader 438e522911 lib/arduino-lib: Add Arduino's external library.
This library contains external modules for Arduino boards.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-26 17:03:56 +11:00
Andrew Leech 994021e1e0 nrf/Makefile: Clean up dangling LIBS declaration.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2024-03-26 16:54:21 +11:00
Andrew Leech 34c4625dcc nrf/main: Fix build of microbit when SD is enabled.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2024-03-26 16:49:40 +11:00
robert-hh 4dd288ff62 nrf/modules/machine/pwm: Tag a PWM device as used in the constructor.
When PWM constructor was created without specifying a device or setting
both freq and duty rate, it was not tagged as used, and further calls to
get a PWM object may get the same PWM device assigned.

Fixes #13494.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-26 16:41:08 +11:00
Christian Walther 5e926b2222 nrf/modules/machine: Catch exceptions from pin interrupts.
Exceptions in pin interrupt handlers would end up crashing MicroPython with
a "FATAL: uncaught exception".

In addition, MicroPython would get stuck trying to output this error
message, or generally any print output from inside a pin interrupt handler,
through the UART after the first character, so that only "F" was visible.
The reason was a matching interrupt priority between the running pin
interrupt and the UARTE interrupt signaling completion of the output
operation.  Fix that by increasing the UARTE interrupt priority.

Code taken from the stm32 port and adapted.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2024-03-26 15:21:01 +11:00
Christian Walther b10182bbcc nrf: Fix non-running LFCLK.
Under some circumstances, after a hard reset, the low-frequency clock would
not be running.  This caused time.ticks_ms() to return 0, time.sleep_ms()
to get stuck, and other misbehavior.  A soft reboot would return it to a
working state.

The cause was a race condition that was hit when the bootloader would
itself turn LFCLK on, but turn it off again shortly before launching the
main application (this apparently happens with the Adafruit bootloader
from https://github.com/fanoush/ds-d6/tree/master/micropython).  Stopping
the clock is an asynchronous operation and it continues running for a short
time after the stop command is given.  When MicroPython checked whether to
start it by looking at the LFCLKSTAT register (nrf_clock_lf_is_running)
during that time, it would mistakenly not be started again.  What
MicroPython should be looking at is not whether the clock is running at
this time, but whether a start/stop command has been given, which is
indicated by the LFCLKRUN register (nrf_clock_lf_start_task_status_get).
It is not clearly documented, but empirically LFCLKRUN is not just set when
the LFCLKSTART task is triggered, but also cleared when the LFCLKSTOP task
is triggered, which is exactly what we need.

The matter is complicated by the fact that the nRF52832 has an anomaly
(see [errata](https://infocenter.nordicsemi.com/topic/errata_nRF52832_Rev3/ERR/nRF52832/Rev3/latest/anomaly_832_132.html?cp=5_2_1_0_1_33))
where starting the LFCLK will not work between 66µs and 138µs after it last
stopped. Apply a workaround for that.  See nrfx_clock_lfclk_start() in
micropython/lib/nrfx/drivers/src/nrfx_clock.c for reference, but we are not
using that because it also does other things and makes the code larger.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2024-03-26 13:03:57 +11:00
Christian Walther be89d4376b nrf/modules/machine: Enable code formatting.
It destroys a few manual alignments, but these seem minor compared to
the benefit of automated code style consistency.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2024-03-26 12:49:09 +11:00
Christian Walther d1a3e7d292 nrf/Makefile: Allow external board definitions.
Trying to use an external board definition according to
https://github.com/micropython/micropython-example-boards on the nrf port
failed with "Invalid BOARD specified".  Replacing all ocurrences of
"boards/$(BOARD)" with "$(BOARD_DIR)" following the example of
stm32/Makefile fixes that.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2024-03-26 12:32:56 +11:00
Damien George 51d05c442a tools/manifestfile.py: Fix freeze() when script is an empty iterable.
The documentation for `freeze()` says that:
- If `script` is `None`, all files in `path` will be frozen.
- If `script` is an iterable then `freeze()` is called on all items of the
  iterable.

This commit makes sure this behaviour is followed when an empty tuple/list
is passed in for `script` (previously an empty tuple/list froze all files).

Fixes issue #14125.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-25 13:41:37 +11:00
Jared Hancock 086d4d127d extmod/network_wiznet5k: Properly enable interrupt signal on w5100s.
According to the datasheet, the IEN bit to enable the interrupt is in the
MR2 register, not the MR register.

This is just cleanup as the interrupt appears to be enabled by default
after resetting the chip.

Tested on W5100S_EVB_PICO.
2024-03-25 13:25:19 +11:00
Daniël van de Giessen fcaf109917 top: Skip codespell for IDF managed components.
During a build the ESP-IDF downloads managed components in the
ports/esp32/managed_components directory, which shouldn't be spellchecked.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-03-25 12:32:29 +11:00
Daniël van de Giessen a0efe2d368 esp32/main: Check if main GC heap allocation failed.
If the heap allocation fails we will crash if we continue, so at least we
can show a clear error message so one can figure out memory allocation was
the problem (instead of just seeing some arbitrary null pointer error
later).

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-03-25 12:19:00 +11:00
Damien George 35f3f0a87d py/nlr: Add "memory" to asm clobbers list in nlr_jump.
Newer versions of gcc (14 and up) have more sophisticated dead-code
detection, and the asm clobbers list needs to contain "memory" to inform
the compiler that the asm code actually does something.

Tested that adding this "memory" line does not change the generated code on
ARM Thumb2, x86-64 and Xtensa targets (using gcc 13.2).

Fixes issue #14115.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-25 11:52:26 +11:00
Damien George 35b2edfc24 github/workflows: Add Biome workflow for JavaScript formatting/linting.
Enable Biome on all of webassembly port and tests.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George badc0106bd tools/ci.sh: Update webassembly CI tests.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George c1513a078d tests/ports/webassembly: Add webassembly JS tests.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George e41b571a29 tests/run-tests.py: Support running webassembly tests via node.
This allows running tests with a .js/.mjs suffix, and also .py tests using
node and the webassembly port.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George c2cf58befc webassembly/library: Fix formatting and style for Biome.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George 26d6969fef webassembly: Update README.md to describe latest changes.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George b9eb74e73b webassembly/variants/pyscript: Add pyscript variant.
This commit adds a pyscript variant for use in https://pyscript.net/.

The configuration is:
- No ASYNCIFY, in order to keep the WASM size down and have good
  performance.
- MICROPY_CONFIG_ROM_LEVEL_FULL_FEATURES to enable most features.
- Custom manifest that includes many of the python-stdlib libraries.
- MICROPY_GC_SPLIT_HEAP_AUTO to increase GC heap size instead of doing a
  collection when memory is exhausted.  This is needed because ASYNCIFY is
  disabled.  Instead the GC collection is run at the top-level before
  executing any Python code.
- No MICROPY_VARIANT_ENABLE_JS_HOOK because there is no asynchronous
  keyboard input to interrupt a running script.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George 6ff3e356e2 webassembly: Implement replInit() and replProcessChar().
This is the JavaScript API for starting and running a REPL.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George 625b17a410 webassembly: Implement runCLI() for a Node-based CLI.
This allows running MicroPython webassembly from the command line using:

    node micropython.mjs

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 14:31:25 +11:00
Damien George 9b090603a0 webassembly: Implement runPythonAsync() for top-level async code.
With this commit, `interpreter.runPythonAsync(code)` can now be used to run
Python code that uses `await` at the top level.  That will yield up to
JavaScript and produce a thenable, which the JavaScript runtime can then
resume.  Also implemented is the ability for Python code to await on
JavaScript promises/thenables.  For example, outer JavaScript code can
await on `runPythonAsync(code)` which then runs Python code that does
`await js.fetch(url)`.  The entire chain of calls will be suspended until
the fetch completes.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:37:47 +11:00
Damien George 39bd0b8a0a webassembly: Add JavaScript proxying, and js and jsffi modules.
This commit improves the webassembly port by adding:

- Proxying of Python objects to JavaScript with a PyProxy type that lives
  on the JavaScript side.  PyProxy implements JavaScript Proxy traps such
  as has, get, set and ownKeys, to make Python objects have functionality
  on the JavaScript side.

- Proxying of JavaScript objects to Python with a JsProxy type that lives
  on the Python side.  JsProxy passes through calls, attributes,
  subscription and iteration from Python to JavaScript.

- A top-level API on the JavaScript side to construct a MicroPython
  interpreter instance via `loadMicroPython()`.  That function returns an
  object that can be used to execute Python code, access the Python globals
  dict, access the Emscripten filesystem, and other things.  This API is
  based on the API provided by Pyodide (https://pyodide.org/).  As part of
  this, the top-level file is changed from `micropython.js` to
  `micropython.mjs`.

- A Python `js` module which can be used to access all JavaScript-side
  symbols, for example the DOM when run within a browser.

- A Python `jsffi` module with various helper functions like
  `create_proxy()` and `to_js()`.

- A dedenting lexer which automatically dedents Python source code if every
  non-empty line in that source starts with a common whitespace prefix.
  This is very helpful when Python source code is indented within a string
  within HTML or JavaScript for formatting reasons.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:37:47 +11:00
Damien George 691cd3a56d webassembly: Clean up Makefile and add variant support.
This commit cleans up and generalises the Makefile, adds support for
variants (following the unix port) and adds the "standard" variant as the
default variant.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:37:09 +11:00
Damien George 98a8ff7a1a webassembly: Add support for enabling MICROPY_GC_SPLIT_HEAP_AUTO.
When enabled the GC will not reclaim any memory on a call to
`gc_collect()`.  Instead it will grow the heap.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:10:05 +11:00
Damien George ae6bcc9d23 webassembly: Use POSIX write for output and add stderr.
All output is now handled by Emscripten's stdio facility.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:06:39 +11:00
Damien George 8e3b701dee webassembly: Enable time localtime, gmtime, time, time_ns.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:05:54 +11:00
Damien George 76898cbfa1 webassembly: Implement MICROPY_PY_RANDOM_SEED_INIT_FUNC.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:05:54 +11:00
Damien George 8282bd93a2 webassembly: Move MP_JS_EPOCH init to library postset.
This eliminates the need for wrapper.js to run to set up the time.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:05:54 +11:00
Damien George ff15dfcaa8 webassembly: Include lib in sys.path.
Following other ports.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:05:54 +11:00
Damien George 2b8e88c563 py/compile: Add option to allow compiling top-level await.
Enabled by MICROPY_COMPILE_ALLOW_TOP_LEVEL_AWAIT.  When enabled, this means
that scope such as module-level functions and REPL statements can yield.
The outer C code must then handle this yielded generator.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-22 13:05:25 +11:00
Jim Mussared acbdbcd95e esp32: Workaround IDF issue placing ISR ringbuf functions in IRAM.
This workaround makes sure that all ringbuf functions that may be called
from an ISR are placed in IRAM.  See
https://github.com/espressif/esp-idf/issues/13378

Note that this means that all esp32-og builds get non-ISR ringbuf functions
placed in flash now, whereas previously it was just the spiram variant.
This might be a good thing (e.g. free up some IRAM for native/viper).

Fixes issue #14005.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2024-03-22 12:14:27 +11:00
Angus Gratton 71044a4186 py/parse: Zero out dangling parse tree pointer to fix potential GC leak.
This fixes a bug where a random Python object may become
un-garbage-collectable until an enclosing Python file (compiled on device)
finishes executing.

Details:

The mp_parse_tree_t structure is stored on the stack in top-level functions
such as parse_compile_execute() in pyexec.c (and others).

Although it quickly falls out of scope in these functions, it is usually
still in the current stack frame when the compiled code executes. (Compiler
dependent, but usually it's one stack push per function.)

This means if any Python object happens to allocate at the same address as
the (freed) root parse tree chunk, it's un-garbage-collectable as there's a
(dangling) pointer up the stack referencing this same address.

As reported by @GitHubsSilverBullet here:
https://github.com/orgs/micropython/discussions/14116#discussioncomment-8837214

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-22 10:49:20 +11:00
Damien George 9d27183bde tests/float/float_struct_e.py: Add specific test for struct 'e' type.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-20 14:13:49 +11:00
Damien George b80607ecaf unix/variants: Don't use native _Float16 type.
Using it increases code size by about 2k.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-20 14:13:49 +11:00
Damien George 0c800cefea stm32/stm32.mk: Enable _Float16 support on MCUs with hardware floats.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-20 14:13:49 +11:00
Matthias Urlichs e520fa2e0f py/binary: Support half-float 'e' format in struct pack/unpack.
This commit implements the 'e' half-float format: 10-bit mantissa, 5-bit
exponent.  It uses native _Float16 if supported by the compiler, otherwise
uses custom bitshifting encoding/decoding routines.

Signed-off-by: Matthias Urlichs <matthias@urlichs.de>
Signed-off-by: Damien George <damien@micropython.org>
2024-03-20 14:13:49 +11:00
Nicko van Someren 77f08b72ca docs/library/rp2.DMA: Add documentation for rp2 DMA support.
Signed-off-by: Nicko van Someren <nicko@nicko.org>
2024-03-19 17:10:54 +11:00
Felix Dörre 1c6012b0b5 extmod/modnetwork: Implement IPv6 API to set and get NIC configuration.
This commit implements a new <AbstractNIC>.ipconfig() function for the NIC
classes that use lwIP, to set and retrieve network configuration for a NIC.
Currently this method supports:
- ipconfig("addr4"): obtain a tuple (addr, netmask) of the currently
  configured ipv4 address
- ipconfig("addr6"): obtain a list of tuples (addr, state,
  prefered_lifetime, valid_lifetime) of all currently active ipv6
  addresses; this includes static, slaac and link-local addresses
- ipconfig("has_dhcp4"): whether ipv4 dhcp has supplied an address
- ipconfig("has_autoconf6"): if there is a valid, non-static ipv6 address
- ipconfig(addr4="1.2.3.4/24"): to set the ipv4 address and netmask
- ipconfig(addr6="2a01::2"): to set a static ipv6 address; note that this
  does not configure an interface route, as this does not seem supported by
  lwIP
- ipconfig(autoconf6=True): to enable ipv6 network configuration with slaac
- ipconfig(gw4="1.2.3.1"): to set the ipv4 gateway
- ipconfig(dhcp4=True): enable ipv4 dhcp; this sets ipv4 address, netmask,
  gateway and a dns server
- ipconfig(dhcp4=False): stops dhcp, releases the ip, and clears the
  configured ipv4 address.
- ipconfig(dhcp6=True): enable stateless dhcpv6 to obtain a dns server

There is also a new global configuration function network.ipconfig() that
supports the following:
- network.ipconfig(dns="2a01::2"): set the primary dns server (can be a
  ipv4 or ipv6 address)
- network.ipconfig(prefer=6): to prefer ipv6 addresses to be returned as
  dns responses (falling back to ipv4 if the host does not have an ipv6
  address); note that this does not flush the dns cache, so if a host is
  already in the dns cache with its v4 address, subsequent lookups will
  return that address even if prefer=6 is set

This interface replaces NIC.ifconfig() completely, and ifconfig() should be
marked as deprecated and removed in a future version.

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-03-19 16:42:10 +11:00
Damien George 52c678c6f8 stm32/boards/LEGO_HUB_NO6: Use a raw filesystem for mboot to update fw.
The C-based SPI flash driver is needed because the
`_copy_file_to_raw_filesystem()` function must copy from a filesystem (eg
FAT) to another part of flash, and the same C code must be used for both
reading (from FAT) and writing (to flash).

Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 11:41:55 +11:00
Damien George 899592ac34 stm32/boards/LEGO_HUB_NO6: Move robust logic to mboot.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 11:40:14 +11:00
Damien George 9651046edd stm32/mboot: Add support for a raw filesystem.
This is enabled by default if MBOOT_FSLOAD is enabled, although a board
can explicitly disable it by `#define MBOOT_VFS_RAW (0)`.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 11:38:36 +11:00
Damien George 3c445f6636 py/emitnative: Implement viper unary ops positive, negative and invert.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 10:31:36 +11:00
Damien George b50efbd0e3 py/asmxtensa: Optimise asm_xtensa_mov_reg_i32_optimised() for tiny ints.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 10:31:36 +11:00
Damien George f52b0d0ff1 py/asm: Add ASM_NOT_REG and ASM_NEG_REG macros for unary ops.
ASM_NOT_REG is optional, it can be synthesised by xor(reg, -1).
ASM_NEG_REG can also be synthesised with a subtraction, but most
architectures have a dedicated instruction for it.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 10:31:36 +11:00
Damien George d92dff881c docs/library/collections: Update deque docs to describe new features.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 10:09:11 +11:00
Damien George c9016b4979 tests/basics: Split MicroPython-specific deque tests to separate file.
So that the MicroPython-specific behaviour can be isolated, and the CPython
compatible test don't need a .exp file.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 10:08:32 +11:00
Damien George bf18ddd989 tools/mpy-tool.py: Fix merging of more than 128 mpy files.
The argument to MP_BC_MAKE_FUNCTION (raw code index) was being encoded as a
byte instead of a variable unsigned int.  That meant that if there were
more than 128 merged mpy files the encoding would be invalid.

Fix that by using `mp_encode_uint(idx)` to encode the raw code index.  And
also use `Opcode` constants for the opcode values to make it easier to
understand the code.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-19 10:08:05 +11:00
Dash Peters 7dff38fdc1 py/objdeque: Expand implementation to be doubly-ended and support iter.
Add `pop()`, `appendleft()`, and `extend()` methods, support iteration
and indexing, and initializing from an existing sequence.

Iteration and indexing (subscription) have independent configuration flags
to enable them.  They are enabled by default at the same level that
collections.deque is enabled (the extra features level).

Also add tests for checking new behavior.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-18 14:10:14 +11:00
Damien George cd8eea2ae9 all: Update extmod, ports, examples to build with new berkeley-db lib.
This provides a MicroPython-specific berkeley-db configuration in
extmod/berkeley-db/berkeley_db_config_port.h, and cleans up the include
path for this library.

Fixes issue #13092.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-16 12:19:12 +11:00
Damien George 305707b281 lib/berkeley-db-1.xx: Update submodule URL and version.
This updates the berkeley-db-1.xx submodule URL to a repository hosted
under the micropython organisation, and makes the following changes:

- Moves the berkeley-db header files to a single directory within the
  submodule, and references all these headers with a much fuller path,
  which prevents symbol clashes (eg with esp32 and queue.h).

- Removes unused/non-working files from berkeley-db, which removes all
  symlinks in that repo (symlinks don't play well under Windows).

- Allows injecting an external configuration header into berkeley-db, so
  the configuration doesn't have to be provided by -Dxx=yy flags to the
  compiler (and possibly clashing with other symbols).

- Removes the advertising clause from the BSD 4-clause license of
  berkeley-db (see relevant commit and README.Impt.License.Change for
  details).

Signed-off-by: Damien George <damien@micropython.org>
2024-03-16 12:12:48 +11:00
Felix Dörre 01c31ea804 extmod/os_dupterm: Handle exception properly when it occurs in parallel.
When an exception is handled and the stream is closed, but while this
happens, another exception occurs or dupterm is deactivated for another
reason, the initial deactivation crashes, because its dupterm is removed.

Co-authored-by: Damien George <damien@micropython.org>

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-03-16 10:59:03 +11:00
Damien George fb3820e3d6 nrf/boards: Enable MICROPY_HW_ENABLE_USBDEV on boards with USB CDC.
These boards were broken by 9d0d262be0.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-16 00:40:39 +11:00
Damien George df2ff0c355 LICENSE: Add libmetal and open-amp to 3rd-party license list.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-15 18:11:28 +11:00
iabdalkader 486ca3a688 tools/ci.sh: Add Arduino GIGA to stm32 CI build.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader e5ca06a06f docs/library/openamp: Document the new openamp module.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader 864e4596bf stm32/boards/ARDUINO_PORTENTA_H7: Enable OpenAMP.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader fc97343639 stm32/boards/ARDUINO_NICLA_VISION: Enable OpenAMP.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader c859978da3 stm32/boards/ARDUINO_GIGA: Enable OpenAMP.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader 09eb4caccb stm32: Implement port backend for OpenAMP's remoteproc.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader 13297d8c3a stm32: Implement port backend for libmetal.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader 81aba8253a extmod/modopenamp_remoteproc: Add new OpenAMP RemoteProc class.
RemoteProc provides an API to load firmware and control remote processors.

Note: port-specific operations must be implemented to support this class.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader 14dae42fe7 extmod/modopenamp: Add new OpenAMP module.
This module implements OpenAMP's basic initialization and shared resources
support, and provides support for OpenAMP's RPMsg component, by providing
an `endpoint` type (a logical connection on top of RPMsg channel) which can
be used to communicate with the remote core.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader 162054be85 stm32/mpu: Add MPU config for shared, uncached memory region.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
Damien George b726022509 py/stream: Factor stream implementations.
So there's only one location that does the ioctl(MP_STREAM_SEEK) call.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-15 18:11:28 +11:00
iabdalkader 85028aadab py/stream: Add mp_stream_seek() helper function.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader 61ee59ad89 extmod/libmetal: Add MicroPython platform for libmetal.
Add a MicroPython platform for libmetal, based on the generic platform.
The MicroPython platform uses common mp_hal_xxx functions and allows ports
to customize default configurations for libmetal.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 18:11:28 +11:00
iabdalkader f6213ffc5c lib/libmetal: Add libmetal submodule.
libmetal provides an abstraction of the underlying hardware, to support
other OpenAMP components.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 17:35:39 +11:00
iabdalkader 5bed292c06 lib/open-amp: Add OpenAMP submodule.
OpenAMP framework provides a standard inter processor communications
infrastructure for RTOS and bare metal environments. There are 3 major
components in OpenAMP: libmetal, remoteproc and RPMsg. libmetal provides
abstraction of the low-level underlying hardware, remoteproc is used for
processor Life Cycle Management (LCM) like loading firmware, starting,
stopping a core etc., and RPMsg is a bus infrastructure that enables Inter
Processor Communications (IPC) between different cores.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-15 17:35:13 +11:00
Angus Gratton 7f5d8c4605 samd: Enable support for Python USB devices.
This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-15 14:24:52 +11:00
Angus Gratton 0baa3b5528 rp2: Enable support for Python USB devices.
This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-15 14:24:52 +11:00
Angus Gratton 9d0d262be0 extmod/machine_usb_device: Add support for Python USB devices.
This new machine-module driver provides a "USBDevice" singleton object and
a shim TinyUSB "runtime" driver that delegates the descriptors and all of
the TinyUSB callbacks to Python functions.  This allows writing arbitrary
USB devices in pure Python.  It's also possible to have a base built-in
USB device implemented in C (eg CDC, or CDC+MSC) and a Python USB device
added on top of that.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-15 14:22:11 +11:00
Angus Gratton 43904acea8 mimxrt: Define the MICROPY_HW_ENABLE_USBDEV macro.
Previously USB was always enabled, but this created some conflicts when
adding guards to other files on other ports.

Note the configuration with USB disabled hasn't been tested and probably
won't build or run without further work.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-15 13:37:42 +11:00
Angus Gratton 47e84751fb py/objstr: Add a macro to define a bytes object at compile time.
This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-15 13:37:31 +11:00
Kwabena W. Agyeman fff66c3069 mimxrt/mpconfigport: Enable cryptolib and hashlib md5.
Signed-off-by: Kwabena W. Agyeman <kwagyeman@live.com>
2024-03-15 13:24:23 +11:00
Daniël van de Giessen 58a596f4a9 extmod/nimble: Check for active before setting address mode.
`BLE().config(addr_mode=...)` is not safe to call if the NimBLE stack is
not yet active (because it tries to acquire mutexes which should be
initialized first).

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-03-15 12:59:58 +11:00
Damien George bfc3dde2c9 extmod/modmachine: Add MICROPY_PY_MACHINE_RESET configuration option.
Disabled by default, but enabled on all boards that previously had
`MICROPY_PY_MACHINE_BARE_METAL_FUNCS` enabled.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-15 12:04:37 +11:00
Damien George dd134e4836 extmod/modmachine: Add MICROPY_PY_MACHINE_MEMX configuration option.
Enabled by default.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-15 12:04:34 +11:00
Damien George 23ccbcf230 extmod/modmachine: Add MICROPY_PY_MACHINE_SIGNAL configuration option.
Enabled by default.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-15 12:04:25 +11:00
iabdalkader c231c89651 extmod/network_ninaw10: Fix error messages.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-14 18:26:41 +01:00
iabdalkader 2b6f81f2b9 extmod/network_ninaw10: Set the proper security mode if none provided.
If no security mode is provided, use WPA for station and WEP for AP.  Note
only WEP is supported in AP mode.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-14 17:40:25 +11:00
iabdalkader 8b4a21cd64 extmod/network_ninaw10: Activate the NIC on demand.
Activate the NIC on calls to connect() or config() if it's not already
active. This change makes the NINA NIC more in line with CYW43 and other
NICs, which allow configuring the NIC before or after it is activated.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-03-14 17:40:18 +11:00
Damien George d712feb68a stm32/sdram: Fix MPU config to use MPU_CONFIG_NOACCESS.
Followup to 2345c1a04e.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-09 10:50:43 +11:00
Stanislav Ponomarev bedb649edf esp32/boards/ESP32_GENERIC_S3: Add 4MiB partitioning board variant.
Added a 4MiB flash partitioning variant for ESP32S3: adds support for 4MiB
discrete flash boards or ESP32-S3FH4R2 with embedded 4MiB flash based ones.

Tested on the waveshare ESP32-S3 Mini w/ESP32-S3FH4R2.

Signed-off-by: Stanislav Ponomarev <me@stasponomarev.com>
2024-03-09 10:37:46 +11:00
Daniël van de Giessen 20f85fb26e esp32/machine_uart: Always configure timeout_char setting in init().
If the `timeout_char` parameter is not given, we should still configure the
UART to ensure the UART is always initialized consistently.  So the default
of 0 gets applied correctly, or if, for example, the baudrate was changed
the char timeout isn't still based on the old baudrate causing weird
behaviour, etc.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-03-08 17:09:17 +11:00
robert-hh cdfc6c159f esp32/network_lan: Add a separate argument to set PHY power pin.
Prior to this commit, the pin defined for power would be used by the
esp_idf driver to reset the PHY.  That worked, but sometimes the MDIO
configuration started before the power was fully settled, leading to an
error.

With the change in this commit, the power for the PHY is independently
enabled in network_lan.c with a 100ms delay to allow the power to settle.
A separate define for a reset pin is provided, even if the PHY reset
pin is rarely connected.

Fixes issue #14013.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-08 16:55:08 +11:00
Trent Piepho af67be7adc esp32/modmachine: Support bootloader on ESP32-S2/S3/C2/C3.
On these targets it's possible to enter the bootloader by setting a bit in
an RTC register before resetting.

Structure it in a way that a board can still provide a custom bootloader
handler.  The handler here will be the default if none is provided, for any
board based on the supported targets.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2024-03-08 15:55:17 +11:00
Trent Piepho 9fc450689b esp32/mpconfigport: Don't hang when machine.bootloader isn't supported.
Currently only the Arduino Nano ESP32 defines a machine.bootloader handler
for ESP32.  All other boards will intentionally hang.

There is no error message, nor is a NotImplementedError raised.  There's no
indication if Micropython has crashed, or if the bootloader was entered but
USB is not working, which is a real problem the ESP32 bootloader has.  It's
not possible escape from this hang with ^C or any other means besides
physical access to the reset pin or the ability to cycle power.

Change this to only define an implementation of machine.bootloader() when
there is a handler for it.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2024-03-08 15:54:44 +11:00
Daniël van de Giessen 27279e69b4 esp32: Add IDF-version-specific sdkconfig.
The new IDF v5.2 deprecated the task cleanup callback we use, so support
for the new option has been implemented in the previous commit.  This also
requires a change in the sdkconfig, via a new variable
${SDKCONFIG_IDF_VERSION_SPECIFIC} which is used in all mpconfigboard.cmake
files to include an extra sdkconfig file based on the IDF version in use.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-03-08 14:05:39 +11:00
Daniël van de Giessen d6176c1f5e esp32: Add support for IDF version v5.2.
Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-03-08 14:05:38 +11:00
Daniël van de Giessen c92683d67c esp32: Add support for IDF version v5.0.5.
Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-03-08 14:05:15 +11:00
MikeTeachman 0b145fdc2d esp32/machine_i2s: Integrate new I2S IDF driver.
The legacy I2S "shim" is removed and replaced by the new I2S driver.  The
new driver fixes a bug where mono audio plays only in one channel.

Application code size is reduced by 2672 bytes with this change.  Tested on
ESP32, ESP32+spiram, ESP32-S3 using example code from
https://github.com/miketeachman/micropython-i2s-examples

Signed-off-by: Mike Teachman <mike.teachman@gmail.com>
2024-03-08 13:31:02 +11:00
Sebastian Romero 4dc262c8fd renesas-ra/boards: Add named pins for Arduino Portenta C33.
Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2024-03-08 13:10:55 +11:00
Sebastian Romero 5c5fe87821 nrf/boards: Add named pins for Arduino Nano 33 BLE.
Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2024-03-08 13:10:43 +11:00
Sebastian Romero 27c0992343 esp32/boards: Add missing named digital pins for Arduino Nano ESP32.
Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2024-03-08 13:10:30 +11:00
Sebastian Romero ed29a4123f rp2/boards: Add named digital pins for Arduino Nano RP2040 Connect.
Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2024-03-08 13:10:13 +11:00
Sebastian Romero 32623d3d19 stm32/boards: Add named digital and analog pins for Arduino boardrs.
Adds Dx and Ax named pins for Arduino Gigi, Arduino Nicla Vision and
Arduino Portenta H7.  The analog pins include the dual-pad _C pins.

Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2024-03-08 13:08:38 +11:00
Damien George a9efffca96 stm32: Add support for dual-analog-pad "_C" pins on H7 MCUs.
This commit adds support for the dual-analog-pads on STM32H7 parts.  These
pads/pins are called PA0_C/PA1_C/PC2_C/PC3_C in the datasheet.  They each
have an analog switch that can optionally connect them to their normal pin
(eg PA0).  When the switch is open, the normal and _C pin are independent
pins/pads.

The approach taken in this commit to make these _C pins available to Python
is:
- put them in their own, independent row in the stm32h7_af.csv definition
  file, with only the ADC column defined (they are separate machine.Pin
  entities, and doing it this way keeps make-pins.py pretty clean)
- allow a board to reference these pins in the board's pins.csv file by the
  name PA0_C etc (so a board can alias them, for example)
- these pins (when enabled in pins.csv) now become available like any other
  machine.Pin through both machine.Pin.board and machine.Pin.cpu
- BUT these _C pins have a separate pin type which doesn't have any
  methods, because they don't have any functionality
- these _C pins can be used with machine.ADC to construct the appropriate
  ADC object, either by passing the string as machine.ADC("PA0_C") or by
  passing the object as machine.ADC(machine.Pin.cpu.PA0_C)
- if a board defines both the normal and _C pin (eg both PA0 and PA0_C) in
  pins.csv then it must not define the analog switch to be closed (this is
  a sanity check for the build, because it doesn't make sense to close the
  switch and have two separate pins)

Signed-off-by: Damien George <damien@micropython.org>
2024-03-08 12:38:00 +11:00
Angus Gratton 7fd8a6d4bc stm32/dma: Add D-cache protection for DMA RX operations, including SPI.
This new DMA API corrects possible cache coherency issues on chips with
D-Cache, when working with buffers at arbitrary memory locations (i.e.
supplied by Python code).

The API is used by SPI to fix an issue with corrupt data when reading from
SPI using DMA in certain cases.  A regression test is included (it depends
on external hardware connection).

Explanation:

1) It's necessary to invalidate D-Cache after a DMA RX operation completes
   in case the CPU reads (or speculatively reads) from the DMA RX region
   during the operation.  This seems to have been the root cause of issue
   #13471 (only when src==dest for this case).

2) More generally, it is also necessary to temporarily mark the first and
   last cache lines of a DMA RX operation as "uncached", in case the DMA
   buffer shares this cache line with unrelated data.  The CPU could
   otherwise write the other data at any time during the DMA operation (for
   example from an interrupt handler), creating a dirty cache line that's
   inconsistent with the DMA result.

Fixes issue #13471.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-08 12:19:48 +11:00
Angus Gratton 2345c1a04e stm32/mpu: Rename MPU_CONFIG_DISABLE to MPU_CONFIG_NOACCESS.
The existing MPU_CONFIG_DISABLE macro enables the MPU region but disables
all access to it.

The rename is necessary to support an MPU_CONFIG_DISABLE macro that
actually disables the MPU region entirely.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-08 10:39:02 +11:00
Angus Gratton 5fe99013b6 stm32: Simplify D-cache clean and invalidate macros.
The inline functions that these are wrappers around already account for
cache line size.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-08 10:38:35 +11:00
robert-hh bf68bb95f9 stm32/network_lan: Add the phy_type=x keyword option to network.LAN().
With LAN8742, LAN8720, LAN83825 and DP83848 as possible options, and the
symbols PHY_LAN8720, PHY_LAN8742, PHY_DP83825 and PHY_DP8348.  The default
is PHY_LAN8742 which is the existing behaviour.

The eth_init() parameters for the Portenta H7 board are set to phy_addr=0
and phy_type=LAN8742, which matches the previous defaults and the
schematics.

Tested with LAN8720 and DP83848 breakout boards at 10M Duplex and 100M
Duplex modes.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-07 17:54:56 +11:00
robert-hh 085e3244f0 stm32/eth: Remove redundant ETH clock enable code.
The MAC clock was initialized both in eth_init() and eth_mac_init().  The
latter is not required.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-07 17:54:04 +11:00
robert-hh 185ae18360 stm32/network_lan: Allow defining phy_addr in the LAN constructor.
The default value is 0, which is compatible with the existing behaviour.
Implementing that required changes to eth.c as well.  The value of phy_addr
is added to the eth_t data type.

Tested with a STM32F767 and a STM32H750 device.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-03-07 17:54:02 +11:00
Damien George b3c62f3169 top: Update .git-blame-ignore-revs for latest format/spell commits.
Signed-off-by: Damien George <damien@micropython.org>
2024-03-07 16:29:46 +11:00
Phil Howard dda9b9c6da all: Prune trailing whitespace.
Prune trailing whitespace across the whole project (almost), done
automatically with:

    grep -IUrl --color "[[:blank:]]$" --exclude-dir=.git --exclude=*.exp |\
        xargs sed -i 's/[[:space:]]*$//'

Exceptions:
- Skip third-party code in lib/ and drivers/cc3100/
- Skip generated code in bluetooth_init_cc2564C_1.5.c
- Preserve command output whitespace in docs, eg:
  docs/esp8266/tutorial/repl.rst

Signed-off-by: Phil Howard <phil@gadgetoid.com>
2024-03-07 16:25:17 +11:00
Angus Gratton decf8e6a8b all: Remove the "STATIC" macro and just use "static" instead.
The STATIC macro was introduced a very long time ago in commit
d5df6cd44a.  The original reason for this was
to have the option to define it to nothing so that all static functions
become global functions and therefore visible to certain debug tools, so
one could do function size comparison and other things.

This STATIC feature is rarely (if ever) used.  And with the use of LTO and
heavy inline optimisation, analysing the size of individual functions when
they are not static is not a good representation of the size of code when
fully optimised.

So the macro does not have much use and it's simpler to just remove it.
Then you know exactly what it's doing.  For example, newcomers don't have
to learn what the STATIC macro is and why it exists.  Reading the code is
also less "loud" with a lowercase static.

One other minor point in favour of removing it, is that it stops bugs with
`STATIC inline`, which should always be `static inline`.

Methodology for this commit was:

1) git ls-files | egrep '\.[ch]$' | \
   xargs sed -Ei "s/(^| )STATIC($| )/\1static\2/"

2) Do some manual cleanup in the diff by searching for the word STATIC in
   comments and changing those back.

3) "git-grep STATIC docs/", manually fixed those cases.

4) "rg -t python STATIC", manually fixed codegen lines that used STATIC.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-07 14:20:42 +11:00
Damien George b3f2f18f92 renesas-ra: Fix spelling mistakes found by codespell.
And enable codespell for this port in `pyproject.toml`.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-07 14:15:49 +11:00
Damien George ab6d59d7bd lib/cyw43-driver: Update driver to latest version v1.0.3.
Includes various bug fixes.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-07 14:07:53 +11:00
Damien George 90e517862d webassembly/Makefile: Remove --memory-init-file from linker options.
It's no longer supported by Emscripten (at least at 3.1.55).  And it's not
needed when the output is WASM, which it is by default.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-04 11:33:07 +11:00
Damien George 7d5f697c38 py/emitglue: Add explicit cast of proto_fun to uint8_t pointer.
Otherwise C++ compilers may complain when this header is included in an
extern "C" block.

Signed-off-by: Damien George <damien@micropython.org>
2024-03-04 10:27:07 +11:00
Daniël van de Giessen bc424ddc41
py/modthread: Move thread state initialisation to shared function.
Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-02-29 14:28:58 +01:00
Daniël van de Giessen 678707c8b0 docs/library/bluetooth: Add note that ESP32 supports pairing/bonding.
Pairing and bonding was fixed for the ESP32 in the two previous commits.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-02-29 14:33:22 +11:00
Daniël van de Giessen d1e15b9281 extmod/nimble: Enable key distribution to support bonding.
This sets the BLE key distribution parameters at runtime. This isn't
needed in most ports since we already set the default values in
`extmod/nimble/syscfg/syscfg.h`; however in the ESP32 port that
headerfile is not used, and the default values in the ESP-IDF don't
enable key distribution nor can we change those defaults via
`sdkconfig`. Thus we're setting these values explicitly at runtime.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-02-29 14:25:59 +11:00
Daniël van de Giessen 3460b48a6d extmod/nimble: Override configuration options set in nimble_port_init.
This moves the runtime initialisation of `ble_hs_cfg` to happen after
`nimble_port_init()`. That is consistent with the order used in NimBLE
examples. On the ESP32 port this is needed because the ESP-IDF sets up
the default RAM secret store callbacks in its implementation of
`nimble_port_init()` (specifically, it calls `esp_nimble_init()` which
in turn calls `ble_store_ram_init()`). We want to override those with
our own callbacks to implement the `IRQ_[GS]ET_SECRET` events in Python.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2024-02-29 14:25:59 +11:00
Damien George 56f9dcb580 tests/multi_bluetooth: Move ble_deepsleep to stress_deepsleep_reconnect.
This test cannot run on boards that have a native USB REPL, so rename it to
indicate that its "special".  This makes it easier to run a subset of
tests, for example:

    ./run-multitests.py multi_bluetooth/ble*.py
    ./run-multitests.py multi_bluetooth/perf*.py
    ./run-multitests.py multi_bluetooth/stress*.py

Signed-off-by: Damien George <damien@micropython.org>
2024-02-29 14:16:05 +11:00
Damien George a30c29398a ports: Don't include mpthread.h in mpthreadport.h.
Because `mpthreadport.h` is included by `mpthread.h`.

Also remove unnecessary include of `mpthreadport.h` in esp32's `main.c`.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-29 13:35:36 +11:00
Damien George b91b2a7fe9 py/mpstate: Don't declare mp_thread_get_state().
It's instead declared by the include of `py/mpthread.h`.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-29 13:33:51 +11:00
Damien George 9a4be7d7b3 py/emitbc: Remove call to adjust Python stack by 0 entries.
This call used to be needed when there was an `emit_bc_pre()` function that
needed to be called at the start of each emitted bytecode.  But in
8e7745eb31 that function was removed and now
the call to `mp_emit_bc_adjust_stack_size()` does nothing when adjusting by
0 entries, so it can be removed.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-29 11:15:37 +11:00
Damien George 8692d2602a extmod/asyncio: Make current_task raise exception when there is no task.
Matches CPython behaviour.

Fixes issue #11530.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-28 15:48:51 +11:00
robert-hh 8fdcc25eb0 py/mpconfig: Change the default enable level for the vfs module.
For boards with MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES and up.
This gets samd21 boards working (which need the vfs module in _boot.py),
B_L072Z_LRWAN1, and nrf boards with smaller MCUs that use CORE or BASIC
feature levels.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-02-26 12:43:24 +11:00
Felix Dörre d2bcb8597e extmod/modlwip: Add back support for empty IP addresses.
Prior to commit 628abf8f25 which added IPv6
support, binding a socket with

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", PORT))

was possible.  But, the empty string is not regarded as a valid IP address
by lwip.  This commit adds a special case for the empty IP string,
restoring the previous CPython-compatible behaviour.

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-02-26 12:34:59 +11:00
Felix Dörre 8547a78275 extmod/modwebsocket: Fix websocket to send correct close frame.
When the websocket closes currently, it does not send a proper
"close"-frame, but rather encodes the 0x8800-sequence inside a binary
packet, which is wrong.  The close packet is a different kind of websocket
frame, according to https://www.rfc-editor.org/rfc/rfc6455.

This change resolves an error in Firefox when the websocket closes.

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-02-26 12:20:40 +11:00
iabdalkader b5edaf68cd stm32/sdram: Support remapping FMC memory banks.
The patch enables SDRAM banks 1 and 2 to be accessible at 0xC0000000 and
0xD0000000 respectively (default mapping) or remapped to addresses
0x60000000 and 0x70000000.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-02-26 12:13:44 +11:00
Angus Gratton 4f7d0df9bc github/ISSUE_TEMPLATE: Convert issue templates to forms.
Allows giving more specific advice, provides more links to other places to
ask questions, check details, etc.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-02-24 20:02:51 +11:00
Damien George 9e5b6972c7 py/emitglue: Make mp_emit_glue_assign_native's fun_data arg a const ptr.
It will only ever be read from, and in some cases (eg on esp8266) can
actually be in ROM.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-22 11:27:33 +11:00
Damien George 01f4e85f1b extmod/modmachine: Remove MICROPY_PY_MACHINE guard from header.
So this header file can expose declarations for contents of the `machine`
module even if that module is disabled.  Other parts of the system -- or
third-party code -- may need these declarations, for example when a single
component like MICROPY_PY_MACHINE_UART is enabled with MICROPY_PY_MACHINE
disabled.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-21 12:00:41 +11:00
Damien George 31e718a6ac stm32/mpbthciport: Allow building with MICROPY_PY_MACHINE_UART disabled.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-21 11:57:17 +11:00
Damien George 27670729a5 py/compile: Remove TODO about name mangling.
This TODO is now covered by the tests/cpydiff/core_class_name_mangling.py
test.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-21 11:42:35 +11:00
Trent Warlaven 3deeabe6e8 tests/cpydiff: Add new CPy diff test for class name mangling.
Adds new tests/documentation for missing name mangling for private class
members.

Signed-off-by: Trent Warlaven <trwbox@gmail.com>
2024-02-21 11:42:35 +11:00
Andrew Leech 2962e24167 extmod/vfs_posix_file: Ensure file object has safe default fd.
With this commit, if file open fails, the object will have fd = -1 (closed)
and the finaliser will not attempt to close anything.

Fixes issue #13672.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2024-02-21 09:51:52 +11:00
Trent Piepho 31e131bd71 esp32/machine_hw_spi: Combine argument parsing for constructor and init.
This combines the argument parsing and checking for the machine.SPI.init()
and machine.SPI() interfaces.

The only real difference was unspecified arguments in init() mean to keep
the same value, while in new they get default values.

Behavior has changed for passing the "id" argument to init().  On other
ports this isn't allowed.  But on esp32 it would change the SPI controller
of the static SPI instance to the new id.  This results in multiple static
spi objects for the same controller and they would fight over which one has
inconsistent mpy vs esp-idf state.  This has been changed to not allow "id"
with init(), like other ports.

In a few causes, a loop is used over arguments that are handled the same
way instead of cut & pasting the same stanza of code for each argument.

The init_internal function had a lot of arguments, which is not efficient
to pass.  Pass the args mp_arg_val_t array instead as a single argument.
This reduced both the number of C lines and the compiled code size.

Summary of code size change:  Two argument lists of 72 bytes are replaced
by a single shared 72 byte list.  New shared argument parsing code is small
enough to be inlined, but is still efficient enough to shrink the overall
code size by 349 bytes of the three argument handlering functions.

add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-349 (-349)
Function                                     old     new   delta
machine_hw_spi_make_new                      255     203     -52
machine_hw_spi_init                          122      67     -55
machine_hw_spi_init_internal                 698     456    -242
Total: Before=1227667, After=1227318, chg -0.03%
add/remove: 2/0 grow/shrink: 0/2 up/down: 92/-144 (-52)
Data                                         old     new   delta
spi_allowed_args                               -      72     +72
defaults$0                                     -      20     +20
allowed_args$1                               240     168     -72
allowed_args$0                              1080    1008     -72
Total: Before=165430, After=165378, chg -0.03%
add/remove: 0/0 grow/shrink: 0/0 up/down: 0/0 (0)

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2024-02-20 16:55:09 +11:00
IhorNehrutsa d9944983cb esp32/machine_i2c: Fix build warnings when I2C is disabled.
Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2024-02-20 16:38:49 +11:00
Damien George 802a88c3b1 stm32/mboot: Generate FLASH_LAYOUT_STR at runtime on H5 MCUs.
The size of the flash varies among MCU variants.  Instead of requiring a
build-time variable to configure this, compute it at runtime using the
special device information word accessible through the FLASH_SIZE macro.

This feature is currently only implemented for H5 MCUs, but can be extended
to others.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 12:32:45 +11:00
Damien George 3db29103a4 py/builtinevex: Fix setting globals for native functions in compile().
Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 12:12:28 +11:00
Damien George 916ceecaef py/emitglue: Remove n_pos_args from DEBUG_printf.
This argument was renamed in 39bf055d23.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 11:31:34 +11:00
Damien George 717e3dca1b py/objfun: Inline mp_obj_code_get_name() into mp_obj_fun_get_name().
The former is static and does not need to be a separate function.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 11:29:46 +11:00
Damien George 0c7ccb8807 py/objfun: Support __name__ on native functions and generators.
This is now easy to support, since the first machine-word of a native
function tells how to find the prelude, from which the function name can be
extracted in the same way as for bytecode.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 10:56:24 +11:00
Damien George 6d403eb697 py/emitnative: Simplify layout and loading of native function prelude.
Now native functions and native generators have similar behaviour: the
first machine-word of their code is an index to get to the prelude.  This
simplifies the handling of these types of functions, and also reduces the
size of the emitted native machine code by no longer requiring special code
at the start of the function to load a pointer to the prelude.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 10:56:24 +11:00
Damien George 9400229766 py/objfun: Split viper fun type out to separate mp_type_fun_viper type.
Viper functions are quite different to native functions and benefit from
being a separate type.  For example, viper functions don't have a bytecode-
style prelude, and don't support generators or default arguments.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 10:56:24 +11:00
Damien George 648a7578da py/objfun: Make mp_obj_new_fun_native/mp_obj_new_fun_asm static-inline.
To reduce code size, since they are only used once by py/emitglue.c.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 10:50:03 +11:00
Damien George 9716171966 py/misc: Remove m_new_obj[_var]_with_finaliser macros.
They are no longer used.  The new `mp_obj_malloc_with_finaliser()` macros
should be used instead, which force the setting of the `base.type` field.
And there's always `m_malloc_with_finaliser()` if needed.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 10:33:09 +11:00
Damien George cae690d047 all: Use mp_obj_malloc_with_finaliser everywhere it's applicable.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 10:32:55 +11:00
Damien George 4133c03040 py/obj: Introduce mp_obj_malloc_with_finaliser to allocate and set type.
Following 709e8328d9.

Using this helps to reduce code size.  And it ensure that the type is
always set as soon as the object is allocated, which is important for the
GC to function correctly.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-20 10:32:51 +11:00
Damien George 2423493774 py/obj: Change sizeof to offsetof in mp_obj_malloc_var macro.
Following b6a9778484, to properly calculate
the size of the variable-length allocation.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-19 23:40:54 +11:00
Damien George 9242e3d16d py/makeversionhdr.py: Reinstate MICROPY_GIT_HASH in mpversion.h.
MICROPY_GIT_HASH was removed in 69e34b6b6b
but it is useful for, and used by, third-party code to tell which hash of
MicroPython is used.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-19 23:36:25 +11:00
Angus Gratton 1ef2944b98 tools/manifestfile.py: Add --unix-ffi option.
Follow up to 35dd959133, allows explicitly
adding the unix-ffi library path from the command line.

This option is needed when building unix-ffi manifests in micropython-lib
CI.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-02-19 13:32:23 +11:00
Damien George def6ad4742 py/emitglue: Include fun_data_len in mp_raw_code_t only when saving.
Reduces the size of mp_raw_code_t in the case when MICROPY_DEBUG_PRINTERS
is enabled.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 14:17:01 +11:00
Damien George 5a3dd8c791 tests/ports/unix: Add coverage test for frozen functions and generators.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 14:17:01 +11:00
Damien George a3a73b64a3 tools/mpy-tool.py: Skip generating frozen mp_raw_code_t when possible.
This reduces frozen code size by using the bytecode directly as the
`mp_proto_fun_t`.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 14:17:01 +11:00
Damien George e2ff00e811 py/emitglue: Introduce mp_proto_fun_t as a more general mp_raw_code_t.
Allows bytecode itself to be used instead of an mp_raw_code_t in the simple
and common cases of a bytecode function without any children.

This can be used to further reduce frozen code size, and has the potential
to optimise other areas like importing.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 14:17:01 +11:00
Damien George 5e3006f117 py/emitglue: Simplify mp_raw_code_t's kind and scope_flags members.
To simplify their access and reduce code size.

The `scope_flags` member is only ever used to determine if a function is a
generator or not, so make it reflect that fact as a bool type.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 12:48:02 +11:00
Damien George 416465d81e py/emitglue: Provide a truncated mp_raw_code_t for non-asm code.
The `asm_n_pos_args` and `asm_type_sig` members of `mp_raw_code_t` are only
used for raw codes of type MP_CODE_NATIVE_ASM, which are rare, for example
in frozen code.  So using a truncated `mp_raw_code_t` in these cases helps
to reduce frozen code size on targets that have MICROPY_EMIT_INLINE_ASM
enabled.

With this, change in firmware size of RPI_PICO builds is -648.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 12:48:02 +11:00
Damien George 39bf055d23 py/emitglue: Reorder and resize members of mp_raw_code_t.
The mp_raw_code_t struct has been reordered and some members resized.  The
`n_pos_args` member is renamed to `asm_n_pos_args`, and `type_sig` renamed
to `asm_type_sig` to indicate that these are used only for the inline-asm
emitters.  These two members are also grouped together in the struct.

The justifications for resizing the members are:
- `fun_data_len` can be 32-bits without issue
- `n_children` is already limited to 16-bits by
  `mp_emit_common_t::ct_cur_child`
- `scope_flags` is already limited to 16-bits by `scope_t::scope_flags`
- `prelude_offset` is already limited to 16-bits by the argument to
  `mp_emit_glue_assign_native()`
- it's reasonable to limit the maximim number of inline-asm arguments to 12
  (24 bits for `asm_type_sig` divided by 2)

This change helps to reduce frozen code size (and in some cases RAM usage)
in the following cases:
- 64-bit targets
- builds with MICROPY_PY_SYS_SETTRACE enabled
- builds with MICROPY_EMIT_MACHINE_CODE enabled but MICROPY_EMIT_INLINE_ASM
  disabled

With this change, unix 64-bit builds are -4080 bytes in size.  Bare-metal
ports like rp2 are unchanged (because mp_raw_code_t is still 32 bytes on
those 32-bit targets).

Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 12:48:02 +11:00
Felix Dörre 223e0d9a5b extmod/network_wiznet5k: Adjust IP types for IPv6.
Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-02-16 11:51:12 +11:00
Felix Dörre 628abf8f25 extmod/modlwip: Support IPv6.
With these changes IPv6 works on the rp2 port (and possibly others that use
the lwIP socket implementation).

Things that have been tested and work:
- Neighbour solicitation for v6 link local address.
- Ping of v6 link-local address.
- Receiving a SLAAC address via router advertisement.
- Ping a v6 address allocated via SLAAC.
- Perform an outgoing connection to a routed v6-address (via default
  gateway).
- Create a listening IPv6 wildcard socked bound to ::, and trying to access
  it via link-local, SLAAC, and IPv4 (to ensure the dual-stack binding
  works).

Things that could be improved:
- socket.socket().getaddrinfo only returns the v4 address.  It could also
  return v6 addresses (getaddrinfo is actively programmed to only return a
  single address, and this is the v4-address by default, with fallback to
  the v6 address if both are enabled).

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-02-16 11:46:40 +11:00
Damien George 866fc3447c tests/multi_bluetooth/ble_irq_calls.py: Enhance test to test recursion.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 10:20:28 +11:00
Damien George cd66aa05cf esp32: Increase NimBLE task stack size and overflow detection headroom.
The Python BLE IRQ handler will most likely run on the NimBLE task, so its
C stack must be large enough to accommodate reasonably complicated Python
code (eg a few call depths).  So increase this stack size.

Also increase the headroom from 1024 to 2048 bytes.  This is needed because
(1) the esp32 architecture uses a fair amount of stack in general; and (2)
by the time execution gets to setting the Python stack top via
`mp_stack_set_top()` in this interlock code, about 600 bytes of stack are
already used, which reduces the amount available for Python.

Fixes issue #12349.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-16 10:19:26 +11:00
YAMAMOTO Takashi 809d113dbc unix: Don't include system headers when features are disabled.
Because the target system may not have these headers at all.

Signed-off-by: YAMAMOTO Takashi <yamamoto@midokura.com>
2024-02-15 16:54:17 +11:00
YAMAMOTO Takashi f9704ce36e unix/input: Flush the prompt after writing it to stdout.
Depending on your setup, stdout might be buffered/line-buffered.

Signed-off-by: YAMAMOTO Takashi <yamamoto@midokura.com>
2024-02-15 16:45:00 +11:00
YAMAMOTO Takashi 06cb6b1e9f minimal: Use printf instead of echo -e.
macOS's echo doesn't have -e option.  printf is in POSIX and more widely
available these days.

Signed-off-by: YAMAMOTO Takashi <yamamoto@midokura.com>
2024-02-15 16:36:22 +11:00
YAMAMOTO Takashi e3be70b5e8 minimal: Allow compiling on macOS.
Signed-off-by: YAMAMOTO Takashi <yamamoto@midokura.com>
2024-02-15 16:35:10 +11:00
Damien George c27d304bed esp32/mpnimbleport: Release the GIL while doing NimBLE port deinit.
In case callbacks must run (eg a disconnect event happens during the
deinit) and the GIL must be obtained to run the callback.

Fixes part of issue #12349.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-15 16:05:41 +11:00
Trent Piepho 34097b776e esp32/network_ppp: Make PPP support optional.
PPP is not that commonly used, let it be turned off in the board config to
save space.  It is still on by default.

On an basic ESP32-S3 build, turning off PPP with LWIP still on saves ~35 kB
of codend 4 kB of data.

   text    data     bss     dec     hex filename
1321257  304296 2941433 4566986  45afca before-ppp-off.elf
1285101  299920 2810305 4395326  43113e after-ppp-off.elf
-------------------------------
-36156    -4376     -56

Note that the BSS segment size includes all NOBITS sections in ELF file.
Some of these are aligned to 64kB chunk sized dummy blocks, I think for
alignment to MMU boundaries, and these went down by 1 block each, so 128
kiB of BSS is not really part of the binary size reduction.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2024-02-15 13:29:43 +11:00
Angus Gratton 00ba6aaae4 ports: On cold boot, enable USB after boot.py completes.
For mimxrt, nrf, renesas-ra, rp2 and samd ports, this commit implements
similar behaviour to the stm32 port, where USB is only brought up after
boot.py completes execution.

Currently this doesn't add any useful functionality (and may break
workflows that depend on USB-CDC being live in boot.py), however it's a
precondition for more usable workflows with USB devices defined in
Python (allows setting up USB interfaces in boot.py before the device
enumerates for the first time).

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-02-15 12:31:26 +11:00
Yoctopuce 5d83bbca60 shared/timeutils: Remove useless void-return.
The C99 standard states:

    6.8.6.4 The return statement Constraints

    A return statement with an expression shall not appear in a function
    whose return type is void.  A return statement without an expression
    shall only appear in a function whose return type is void.

And when `-pedantic` is enabled the compiler gives an error.

Signed-off-by: Yoctopuce <dev@yoctopuce.com>
2024-02-15 11:00:50 +11:00
Yoctopuce 587b6f2e34 extmod/modrandom: Add integer type casts where appropriate.
To prevent compiler warnings when `mp_int_t` is 64-bits.

Signed-off-by: Yoctopuce <dev@yoctopuce.com>
2024-02-15 11:00:44 +11:00
YAMAMOTO Takashi d2a3cd7ac4 embed: Improve stack top estimation.
Obtaining the stack-top via a few function calls may yield a pointer which
is too deep within the stack.  So require the user to obtain it from a
higher level (or via some other means).

Fixes issue #11781.

Signed-off-by: YAMAMOTO Takashi <yamamoto@midokura.com>
2024-02-15 10:07:32 +11:00
iabdalkader be8d660fc2 mimxrt: Fix header include guard names.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-02-15 09:45:14 +11:00
Damien George 0432f73206 tools/mpy-tool.py: Fix static qstrs when freezing without qstr header.
It's rare to freeze .mpy files without specifying a qstr header from a
firmware build, but it can be useful for testing, eg
`mpy-tool.py -f test.mpy`.  Fix this case so static qstrs are properly
excluded from the frozen qstr list.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-12 11:56:24 +11:00
Damien George abe43fe687 extmod/btstack: Reset pending_value_handle before calling read-done cb.
Similar to the previous commit but for MP_BLUETOOTH_IRQ_GATTC_READ_DONE:
the pending_value_handle needs to be reset before calling
mp_bluetooth_gattc_on_read_write_status(), which will call the Python IRQ
handler, which may in turn call back into BTstack to perform an action like
a write.  In that case the pending_value_handle will need to be available
for the write/read/etc to proceed.

Fixes issue #13634.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-12 11:26:27 +11:00
Damien George b4f59984f7 extmod/btstack: Reset pending_value_handle before calling write-done cb.
The pending_value_handle needs to be freed and reset before calling
mp_bluetooth_gattc_on_read_write_status(), which will call the Python IRQ
handler, which may in turn call back into BTstack to perform an action like
a write.  In that case the pending_value_handle will need to be available
for the write/read/etc to proceed.

Fixes issue #13611.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-09 11:44:28 +11:00
Damien George 8cbae12d0d unix/variants: Prefer unix-ffi packages when loading the manifest.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-08 17:16:10 +11:00
Damien George 35dd959133 tools/manifestfile.py: Change library search to use a list of paths.
This commit changes how library packages are searched for when a manifest
file is loaded: there is now simply a list of library paths that is
searched in order for the given package.  This list defaults to the
main directories in micropython-lib, but can be added to -- either appended
or prepended -- by using `add_library()`.

In particular the way unix-ffi library packages are searched has changed,
because the `unix_ffi` argument to `require()` is now removed.  Instead, if
a build wants to include packages from micropython-lib/unix-ffi, then it
must explicitly add this to the list of paths to search using:

    add_library("unix-ffi", "$(MPY_LIB_DIR)/unix-ffi")

Work done in collaboration with Jim Mussared.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-08 17:16:10 +11:00
Jos Verlinde 2bdaa1bede docs/library/sys.rst: Document implementation.version.releaselevel.
Signed-off-by: Jos Verlinde <jos_verlinde@hotmail.com>
2024-02-07 15:51:25 +11:00
Angus Gratton 781366e476 github/workflows: Standardise formatting of ruff.yml.
All the other workflow YAML files use vertical whitespace around top-level
items.

Also remove spurious comment, the features in the linked doc aren't
actually used in this workflow (any more?).

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-02-07 15:22:41 +11:00
Angus Gratton 6f0aa275f8 github/workflows: Add comments where tool versions need to be in sync.
This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-02-07 15:21:55 +11:00
Angus Gratton 84e90639fa github/workflows: Move codespell to a GitHub workflow, version it.
Similar to ruff.yaml, it's simpler to run the codespell command directly
from a workflow file.  And developers can run codespell directly from the
command line without the need for options, or just use pre-commit.

This commit also applies a specific version to codespell, same as
pre-commit (introduced in a166d805f4).

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-02-07 15:19:38 +11:00
Damien George b038d07011 stm32/Makefile: Ignore uninitialised variable warning in H5 HAL SD code.
This warning appears when using an MCU like H562 that only has one SDMMC.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 14:55:07 +11:00
Damien George 657faee7e5 stm32/main: Allow disabling MICROPY_PY_MACHINE.
Disabling this requires also disabling: MICROPY_PY_PYB and MICROPY_PY_STM.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:45:51 +11:00
Damien George 4e6436d4cf stm32/spi: Allow disabling MICROPY_PY_MACHINE_SPI.
This requires that MICROPY_PY_PYB is also disabled.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:45:51 +11:00
Damien George 2158da213e stm32/modos: Allow disabling MICROPY_PY_MACHINE_UART.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:45:51 +11:00
Damien George 1c7afa923b drivers/dht: Only build DHT driver if MICROPY_PY_MACHINE_PULSE enabled.
Because this driver calls `machine_time_pulse_us()`.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:45:51 +11:00
Damien George 4c56b39051 docs: Use vfs module instead of os.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:25:10 +11:00
Damien George 7d28789544 ports: Use vfs module instead of os.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:25:09 +11:00
Damien George b87bbaeb43 tests: Use vfs module instead of os.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:25:09 +11:00
Damien George 5804aa0204 docs/reference/micropython2_migration.rst: Add info about os and vfs.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:25:09 +11:00
Damien George 45f99cb445 docs/library: Move vfs functions and classes from os to vfs module docs.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:25:09 +11:00
Damien George e7020463f1 extmod/modvfs: Add new "vfs" module with mount/umount and Vfs classes.
They have been moved from the "os" module.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 13:25:08 +11:00
Felix Dörre aaba1d8a6c extmod/modtls_mbedtls: Implement cert verification callback for mbedtls.
This is a useful alternative to .getpeercert() when the certificate is not
stored to reduce RAM usage.

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-02-07 13:00:57 +11:00
Felix Dörre b802f0f8ab extmod/modtls: Move the native ssl module to tls.
The current `ssl` module has quite a few differences to the CPython
implementation.  This change moves the MicroPython variant to a new `tls`
module and provides a wrapper module for `ssl` (in micropython-lib).

Users who only rely on implemented comparible behavior can continue to use
`ssl`, while users that rely on non-compatible behavior should switch to
`tls`.  Then we can make the facade in `ssl` more strictly adhere to
CPython.

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-02-07 12:58:52 +11:00
Felix Dörre f8f1f29ac0 extmod/modssl_axtls: Add SSLContext.load_cert_chain().
To match the mbedtls implementation.

Signed-off-by: Felix Dörre <felix@dogcraft.de>
2024-02-07 12:58:52 +11:00
Damien George c68462d996 lib/micropython-lib: Update submodule to latest.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 12:58:50 +11:00
Damien George ff73683077 github/workflows: Initialise micropython-lib submodule for windows CI.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 12:58:34 +11:00
Damien George 5a68e82d17 github/workflows: Bump setup-msbuild, setup-python, checkout versions.
Signed-off-by: Damien George <damien@micropython.org>
2024-02-07 11:28:52 +11:00
David Lechner ed15b3c6c6 github/workflows: Move Windows CI from AppVeyor to GitHub Actions.
By moving to GitHub actions, all MicroPython CI builds are now on GitHub
actions.  This allows faster parallel builds and saves time by not building
when no relevant files changed.

This reveals a few failing tests, so those are temporarily disabled until
they can be fixed.

Signed-off-by: David Lechner <david@pybricks.com>
Signed-off-by: Damien George <damien@micropython.org>
2024-02-06 09:50:03 +11:00
David Lechner 23342eff90 windows/Makefile: Fix float exact int formatting on 32-bit mingw.
When compiler optimizations are enabled on the mingw version of gcc, we are
getting failing tests because of rounding issues, for example:

    print(float("1e24"))

would print

    9.999999999999999e+23

instead of

    1e+24

It turns out special compiler options are needed to get GCC to use the SSE
instruction set instead of the 387 coprocessor (which uses 80-bit precision
internall).

Signed-off-by: David Lechner <david@pybricks.com>
2024-02-05 14:04:15 +11:00
Damien George ac8e7f7b67 docs/library/ssl: Change wrap_socket args keyfile/certfile to key/cert.
So they match the code in extmod/modssl_*.c.

Signed-off-by: Damien George <damien@micropython.org>
2024-02-05 13:05:29 +11:00
Jim Lipsey 0285cb2bf4 stm32/boards/ARDUINO_PORTENTA_H7: Add pin configuration for SPI1.
Currently, only the processor's SPI2 bus is enabled (though the related
pins are labeled SPI1 in the Portenta H7 documentation).  This commit
enables the processor's SPI1 bus, which is accessible via the board's
high-density connectors.

Signed-off-by: Jim Lipsey <github@lipsey.org>
2024-02-01 11:21:44 +11:00
Angus Gratton 457f2ccf80 examples/embedding: Add -fno-common to the sample compiler flags.
This makes no difference when files are linked directly into a target
application, but on macOS additional steps are needed to index common
symbols in static libraries. See https://stackoverflow.com/a/26581710

By not creating any common symbols, this problem is bypassed.

This will also trigger linker errors if there are cases where the same
symbol is defined in the host application.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-01-31 14:29:07 +11:00
Joey232 3e48d24576 esp32/boards/UM_FEATHERS3: Use read_uv() for accurate battery voltage.
Use read_uv() to get the battery voltage because it uses the on-chip
calibraton values.

Signed-off-by: Joey232 <Joey@jsconsulting.com>
2024-01-31 14:24:16 +11:00
Takeo Takahashi 81049edf7c renesas-ra/ra/ra_i2c: Fix 1 byte and 2 bytes read issue.
Tested on Portenta C33 with AT24256B (addrsize=16) and SSD1306.

Fixes issue #13280.

Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2024-01-31 14:16:36 +11:00
Damien George 28b18c43fe py/compile: Fix potential Py-stack overflow in try-finally with return.
If a return is executed within the try block of a try-finally then the
return value is stored on the top of the Python stack during the execution
of the finally block.  In this case the Python stack is one larger than it
normally would be in the finally block.

Prior to this commit, the compiler was not taking this case into account
and could have a Python stack overflow if the Python stack used by the
finally block was more than that used elsewhere in the function.  In such
a scenario the last argument of the function would be clobbered by the
top-most temporary value used in the deepest Python expression/statement.

This commit fixes that case by making sure enough Python stack is allocated
to the function.

Fixes issue #13562.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-31 12:56:29 +11:00
Damien George 2d7fb9a715 tests/ports/rp2/rp2_dma.py: Tweak test to be more reliable.
The timing of the DMA transfer can vary a bit, so tweak the allowed values.
Also test the return value of `rp2.DMA.irq.flags()` to make sure the IRQ is
correctly signalled.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-30 12:50:19 +11:00
Damien George 807c25d05a rp2: Change machine.I2S and rp2.DMA to use shared DMA IRQ handlers.
These separate drivers must share the DMA resource with each other.

Fixes issue #13380.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-30 12:44:22 +11:00
Matthias Urlichs d19371cb23 py/builtinimport: Simplify calls to stat_path().
stat_path is only called with stringified vstr_t objects.

Thus, pulling the stringification into the function replaces three
function calls with one, saving a few bytes.

Signed-off-by: Matthias Urlichs <matthias@urlichs.de>
2024-01-30 11:43:41 +11:00
Carlosgg f3d1495fd3 all: Update bindings, ports and tests for mbedtls v3.5.1.
Changes include:

- Some mbedtls source files renamed or deprecated.

- Our `mbedtls_config.h` files are renamed to `mbedtls_config_port.h`, so
  they don't clash with mbedtls's new default configuration file named
  `mbedtls_config.h`.

- MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE is deprecated.

- MBEDTLS_HAVE_TIME now requires an `mbedtls_ms_time` function to be
  defined but it's only used for TLSv1.3 (currently not enabled in
  MicroPython so there is a lazy implementation, i.e. seconds * 1000).

- `tests/multi_net/ssl_data.py` is removed (due to deprecation of
  MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE), there are the existing
  `ssl_cert_rsa.py` and `sslcontext_server_client.py` tests which do very
  similar, simple SSL data transfer.

- Tests now use an EC key by default (they are smaller and faster), and the
  RSA key has been regenerated due to the old PKCS encoding used by openssl
  rsa command, see
  https://stackoverflow.com/questions/40822328/openssl-rsa-key-pem-and-der-conversion-does-not-match
  (and `tests/README.md` has been updated accordingly).

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2024-01-30 11:08:46 +11:00
Carlosgg 92136cbe67 lib/mbedtls_errors: Update error list for latest mbedtls.
Running `./do-mp.sh` now generates this `mp_mbedtls_errors.c` file.  The
`esp32_mbedtls_errors.c` file is already up-to-date.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2024-01-30 10:56:38 +11:00
Carlosgg 3f217e413d lib/mbedtls: Update to mbedtls v3.5.1.
Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2024-01-30 10:53:48 +11:00
Damien George d5b96813dc extmod/modssl_mbedtls: Fix cipher iteration in SSLContext.get_ciphers.
Prior to this commit it would skip every second cipher returned from
mbedtls.

The corresponding test is also updated and now passes on esp32, rp2, stm32
and unix.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-29 15:11:46 +11:00
Damien George 46e833b071 qemu-arm/mpconfigport: Use MICROPY_CONFIG_ROM_LEVEL_EXTRA_FEATURES.
This simplifes the port configuration.  It enables quite a few new
features, including the `math` and `cmath` modules, adding about 20k to the
firmware size.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-29 13:07:31 +11:00
Damien George 40687451bb tests/extmod/framebuf_polygon.py: Replace sys.stdout.write with print.
So the test doesn't depend on the `sys` module.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-29 13:07:25 +11:00
Damien George 7211bafb33 esp8266/boards/ESP8266_GENERIC: Disable MICROPY_DEBUG_PRINTERS.
This is not enabled on any other MCU port, and is essentially unused on
esp8266 because mp_verbose_flag is always 0.  Disabling saves ~7k of flash.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-29 12:19:06 +11:00
iabdalkader 4a2e510a87 ports: Add LED pin aliases for all Arduino boards.
The standard Arduino pinout uses LEDR/G/B and LED_BUILTIN (if available).
This patch adds aliases to match the standard pinout, while retaining
LED_RED/GREEN/BLUE for compatibility with existing scripts and examples.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-26 14:11:42 +11:00
iabdalkader 8d9d74b6df rp2/boards/ARDUINO_NANO_RP2040_CONNECT: Increase flash storage space.
Fixes issue #13512.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-26 14:05:20 +11:00
Kwabena W. Agyeman bf6214505f mimxrt/modmachine: Fix deepsleep wakeup pin ifdef.
Signed-off-by: Kwabena W. Agyeman <kwagyeman@live.com>
2024-01-26 13:59:41 +11:00
Jim Mussared d4190815a3 py/mpconfig: Disable qstr hashing at minimum feature level.
This will apply to bare-arm and minimal, as well as the minimal unix
variant.

Change the default to MICROPY_QSTR_BYTES_IN_HASH=1 for the CORE,BASIC
levels, 2 for >=EXTRA.

Removes explicit setting of MICROPY_QSTR_BYTES_IN_HASH==1 in ports that
don't set the feature level (because 1 is implied by the default level,
CORE). Applies to cc3200, pic16bt, powerpc.

Removes explicit setting for nRF (which sets feature level). Also for samd,
which sets CORE for d21 and FULL for d51. This means that d21 is unchanged
with MICROPY_QSTR_BYTES_IN_HASH==1, but d51 now moves from 1 to 2 (roughly
adds 1kiB).

The only remaining port which explicitly set bytes-in-hash is rp2 because
it's high-flash (hence CORE level) but lowish-SRAM, so it's worthwhile
saving the RAM for runtime qstrs.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2024-01-25 16:38:17 +11:00
Jim Mussared 8486e28b17 stm32: Disable qstr hashing on small boards.
Sets MICROPY_QSTR_BYTES_IN_HASH==0 on stm32x0 boards.

This saves e.g. 2kiB on NUCLEO_F091.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2024-01-25 16:38:17 +11:00
Jim Mussared 7ea503929a py/qstr: Add support for MICROPY_QSTR_BYTES_IN_HASH=0.
This disables using qstr hashes altogether, which saves RAM and flash
(two bytes per interned string on a typical build) as well as code size.
On PYBV11 this is worth over 3k flash.

qstr comparison will now be done just by length then data. This affects
qstr_find_strn although this has a negligible performance impact as, for a
given comparison, the length and first character will ~usually be
different anyway.

String hashing (e.g. builtin `hash()` and map.c) now need to compute the
hash dynamically, and for the map case this does come at a performance
cost.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2024-01-25 16:38:17 +11:00
Angus Gratton 307ecc5707 docs: Add note about position-only arguments in CPython vs MicroPython.
Required modifying the gen-cpydiff.py code to allow a "preamble" section to
be inserted at the top of any of the generated files.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-01-25 11:56:38 +11:00
Jos Verlinde c8772b7baa CODECONVENTIONS: Update docs for codespell and pre-commit hook.
Signed-off-by: Jos Verlinde <jos_verlinde@hotmail.com>
2024-01-25 11:50:07 +11:00
Jos Verlinde a166d805f4 top: Add pre-commit hook for codespell.
Signed-off-by: Jos Verlinde <jos_verlinde@hotmail.com>
2024-01-25 11:49:58 +11:00
Damien George 982ffdee7e stm32/mboot/Makefile: Revert change to BOARD_DIR that removed abspath.
This reverts the change from ce2058685b.

Without abspath, the build artefacts (object files) for boards with source
files are placed outside the build directory, because the BOARD_DIR
variable starts with "..".  For the list of source files added to SRC_C,
none of them can start with "..".  The usual fix for that would be to make
the files relative to the top of the MicroPython repo (because of the vpath
rule), eg ports/stm32/boards/$(BOARD).  But then the $(wildcard ...)
pattern won't find files in this directory.

So abspath is necessary, although it will prevent building when there is a
space in the path.  A better solution for spaces needs to be found.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-25 11:30:14 +11:00
Damien George 6bb446b7ff tests/extmod: Remove asyncio .exp files that match CPython output.
These were added back in commit c4935f3049
because the tests required CPython 3.8, which was quite new at the time.
But CPython 3.8 was released over 4 years ago (October 2019) and the CI
test runners, and developers, have this (or a more recent) CPython version.

Removing the .exp files also helps keep MicroPython semantics the same as
CPython.

The asyncio_fair.py test it adjusted slightly to have more deterministic
timing and output.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-24 11:20:06 +11:00
Damien George 8eb658f654 github/workflows: Run mimxrt and rp2 CI with space in repository path.
To test building with make and cmake when there is a space in the path.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-24 11:07:00 +11:00
Iksas ce2058685b ports: Fix handling of paths containing spaces in Makefiles.
Make can't handle paths with spaces, see https://savannah.gnu.org/bugs/?712

The following workarounds exist:

- When using make's built-in functions:
    - Use relative paths wherever possible to avoid spaces in the first
      place.
    - All spaces in paths can be escaped with backslashes; quotes don't
      work.
    - Some users use the shell to temporarily rename directories, or to
      create symlinks without spaces.

- When using make to pass commands to the system's shell, enclose paths in
  quotes.  While make will still interpret quoted strings with spaces as
  multiple words, the system's shell will correctly parse the resulting
  command.

This commit contains the following fixes:

- In ports/stm32/mboot/Makefile: Use relative paths to avoid spaces when
  using built-in functions.

- In all other files: Use quotes to enclose paths when make is used to call
  shell functions.

All changes have been tested with a directory containing spaces.

Signed-off-by: Iksas <iksas@mailbox.org>
2024-01-24 10:43:18 +11:00
Maarten van der Schrieck 057701a770 rp2/machine_uart: Fix potential race condition in interrupt handling.
The irq service routine cleared the RT interrupt bit on TX interrupt.  This
opens the possibility that an RT interrupt is missed.

Signed-off-by: Maarten van der Schrieck <maarten@thingsconnected.nl>
2024-01-23 13:11:53 +11:00
Damien George c3ca3612d1 tests/extmod/asyncio_wait_task.py: Add test for raise and delayed wait.
This case was fixed in 2ecbad4e91, which
stored the exception in the task object.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-23 11:13:35 +11:00
iabdalkader e111793d8d nrf: Fix _start() build issue with CMSIS 5.9.0.
The `_start` function prototype is now declared as no-return, so `main()`
can't return.

To fix this, `main()` is replaced with `_start`.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-22 12:40:16 +11:00
iabdalkader beb4459784 mimxrt/boards: Fix __VECTOR_TABLE link issue with CMSIS 5.9.0.
In CMSIS 5.9.0, the compiler headers define `__VECTOR_TABLE`, which will be
substituted with its corresponding value (e.g., `__Vectors` for gcc).
However, the linker script in this port can't include compiler headers when
it's processed, so `__VECTOR_TABLE` is used as the literal variable name,
which results in an undefined linker error.

To fix this, the two possible values of `__VECTOR_TABLE` are both defined
in the linker script.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-22 12:36:43 +11:00
iabdalkader e2fa0c6395 lib/cmsis: Update to CMSIS 5.9.0.
This update brings support for Cortex-M55 and Cortex-M85, zero and copy
tables and more.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-22 12:36:35 +11:00
Damien George 2ecbad4e91 extmod/asyncio: Support gather of tasks that finish early.
Adds support to asyncio.gather() for the case that one or more (or all)
sub-tasks finish and/or raise an exception before the gather starts.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-22 12:03:21 +11:00
Damien George 51fbec2780 tests/extmod/machine_i2s_rate.py: Test multiple I2S instances.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-22 11:49:28 +11:00
Damien George 50b809c8e8 tests/ports/rp2: Add rp2-specific tests with a test for rp2.DMA.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-22 11:49:20 +11:00
Damien George 7bbcee3cf0 tests: Move port-specific test directories into tests/ports/ directory.
To keep them all together, mirroring the top-level directory structure.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-22 11:48:27 +11:00
dependabot[bot] f93ffc2875 github/workflows: Bump actions/cache from 3 to 4.
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-22 11:37:37 +11:00
iabdalkader 4fd7e456f0 renesas-ra/boards/ARDUINO_PORTENTA_C33: Fix the RTC clock source.
Switch the RTC clock source to Sub-clock (XCIN). This board has an
accurate LSE crystal, and it should be used for the RTC clock
source.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-21 00:19:20 +11:00
Kwabena W. Agyeman 490e8e01d5 extmod/extmod.mk: Disable uninitialized warnings in kf_rem_pio2.c.
GCC 13.2 thinks that fq is uninitialized.

Signed-off-by: Kwabena W. Agyeman <kwagyeman@live.com>
2024-01-21 00:04:29 +11:00
Jochen Sprickerhof 16c6bc47cf tools/mpremote: Reduce dependency on importlib_metadata.
No longer require importlib_metadata on new Python versions as it is
included in the standard distribution.

Signed-off-by: Jochen Sprickerhof <git@jochen.sprickerhof.de>
2024-01-17 11:27:47 +11:00
iabdalkader c6f6f345e6 renesas-ra/ra: Remove unnecessary min_delay() declaration.
This function is private to ra_adc.c.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-17 11:19:02 +11:00
iabdalkader 1f04808151 renesas-ra/ra: Fix SysTick clock source.
The SysTick_Config function must use the system/CPU clock to configure the
ticks.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-17 11:17:59 +11:00
Angus Gratton a75ca8a1c0 esp32/modsocket: Use all supplied arguments to socket.getaddrinfo().
- Completes a longstanding TODO in the code, to not ignore
  the optional family, type, proto and flags arguments to
  socket.getaddrinfo().

- Note that passing family=socket.AF_INET6 will now cause queries
  to fail (OSError -202). Previously this argument was ignored so
  IPV4 results were returned instead.

- Optional 'type' argument is now always copied into the result. If not
  set, results have type SOCK_STREAM.

- Fixes inconsistency where previously querying mDNS local suffix (.local)
  hostnames returned results with socket type 0 (invalid), but all other
  queries returned results with socket type SOCK_STREAM (regardless of
  'type' argument).

- Optional proto argument is now returned in the result tuple, if supplied.

- Optional flags argument is now passed through to lwIP. lwIP has handling
  for AI_NUMERICHOST, AI_V4MAPPED, AI_PASSIVE (untested, constants for
  these are not currently exposed in the esp32 socket module).

- Also fixes a possible memory leak in an obscure code path
  (lwip_getaddrinfo apparently sometimes returns a result structure with
  address "0.0.0.0" instead of failing, and this structure would have been
  leaked.)

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-01-17 11:00:58 +11:00
iabdalkader 215a982c14 py/py.mk: Remove extra build dir created for frozen_content.
This was originally needed because the .c --> .o rule is:

    $(BUILD)/%.o: %.c

and because the generated frozen_content.c is inside build-FOO, it must
therefore generate build-FOO/build-FOO/frozen_content.o.

But 2eda513870 added a new build rule for
pins.c that can also be used for frozen_content.c.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-17 08:14:15 +11:00
Angus Gratton bdaea866b7 rp2/mpthreadport: Make result of thread.get_ident() a non-zero integer.
CPython says thread identifier is a "nonzero integer", so rp2 should use a
1-indexed core number rather than 0-indexed.  This fixes the
thread/thread_ident1 test failure on rp2 port.

Unfortunately this may be a breaking change for rp2 code which makes a
hard-coded comparison of thread identifier to 0 or 1.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-01-17 08:02:16 +11:00
Damien George efa54c27b9 rp2/mpconfigport: Allow MICROPY_PY_THREAD to be disabled by a board.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-16 11:42:47 +11:00
Damien George a70367e293 nrf/modules/os/microbitfs: Sweep the filesystem if any free chunk found.
If there are any free chunks found then it's better to sweep the filesystem
and use the available chunks, rather than error out with ENOSPC when there
is in fact a bit of space remaining.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-16 11:42:47 +11:00
Damien George f9df08d8ee docs/develop/porting: Fix argument type of mp_lexer_new_from_file().
Follow up to 5015779a6f.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-16 11:42:47 +11:00
robert-hh c41b421d48 tests/extmod/machine_uart_tx.py: Add a test for timing of UART.flush().
Currently only runs on rp2 but could be extended to run on other targets.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-01-16 09:07:03 +11:00
robert-hh 07472d05db rp2/machine_uart: Fix event wait in uart.flush() and uart.read().
Do not wait in the worst case up to the timeout.

Fixes issue #13377.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-01-16 08:53:34 +11:00
stijn bd21820b4c tests/run-tests.py: Fix path-based special test detection.
Compare the full absolute path instead of relying on the path form
passed by the user.

For instance, this will make

python3 run-tests.py -d basics
python3 run-tests.py -d ./basics
python3 run-tests.py -d ../tests/basics
python3 run-tests.py -d /full/path/to/basics

all behave the same by correctly treating the bytes_compare3 and
builtin_help tests as special, whereas previously only the first
invocation would do that and hence result in these tests to fail
when called with a different path form.

Signed-off-by: stijn <stijn@ignitron.net>
2024-01-10 11:34:09 +01:00
stijn 88d21f186b tests/run-tests.py: Make repl test detection more correct.
Avoid unrelated tests which happen to have "repl_" anywhere
in their path to be treated as repl tests.

Signed-off-by: stijn <stijn@ignitron.net>
2024-01-10 11:34:09 +01:00
stijn ba4330ba10 tests/run-tests.py: Remove unneeded argument from run_feature_check().
In 405893af this was likely left as-is to minimize the diff,
but it just complicates things.

Signed-off-by: stijn <stijn@ignitron.net>
2024-01-10 11:34:09 +01:00
Damien George 2ed976f140 samd/mcu/samd21: Enable MICROPY_STACK_CHECK on SAMD21.
Increases firmware size by +140 bytes and uses +4 extra bytes of RAM, but
allows the test suite to run without crashing.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 23:24:39 +11:00
Damien George e456ee40e0 samd/mpconfigport: Simplify and consolidate config options.
This is a no-op in terms of firmware functionality.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 23:24:39 +11:00
Damien George 7ecff515d7 stm32/flash: Fix sector and bank calculation for H5 and H7 MCUs.
Flash sectors should start counting at 0 for each bank.  This commit makes
sure that is the case on all H5 and H7 MCUs, by using `get_page()` instead
of `flash_get_sector_info()`.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:35:48 +11:00
Damien George 5cb93f63fb stm32/flash: Factor and simplify erase code.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:35:22 +11:00
Damien George cd6e0e1022 stm32/flashbdev: Don't rely on flash sector id.
This commit removes the need for a separate `flash_cache_sector_id`
variable, instead using `flash_cache_sector_start` to indicate which sector
is curretly cached (and -1 indicates no sector).

Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:34:18 +11:00
Damien George b6ab9e420b stm32/flash: Change flash_erase to only erase a single sector at a time.
An erase sector sits in a given flash bank and some MCUs have two flash
banks.  If trying to erase a range of sectors and that range crosses from
one flash bank into the next, the original implementation of
`flash_erase()` would not handle this case and would do the wrong thing.

This commit changes `flash_erase()` to only erase a single sector, which
sidesteps the need to handle flash-bank-crossing.  Most callers of this
function only need to erase a single sector anyway.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:33:34 +11:00
Damien George cf115918e6 stm32/flash: Simplify sector calculation for homogeneous flash layout.
Newer STM32 parts have homogeneous flash layout, and in this case the MCU
configuration and page/sector calculation can be simplified.  The affected
functions are `flash_is_valid_addr()` and `flash_get_sector_info()`, which
are now simpler for homogeneous flash.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:31:10 +11:00
Damien George cd0f75069c stm32/flash: Remove commented-out flash functions.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:31:03 +11:00
Damien George 7002a19be2 stm32/mboot: Improve mass erase to erase all non-protected pages.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:29:19 +11:00
Damien George b7b99522e4 stm32/mboot: Improve detection of invalid flash erase/write.
This commit replaces the linker symbol `_mboot_writable_flash_start` with
`_mboot_protected_flash_start` and `_mboot_protected_flash_end_exclusive`,
to provide better configuration of the protected flash area.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-08 12:22:55 +11:00
Nicko van Someren 1da45e887a rp2: Provide direct memory access to PIO and SPI FIFOs via proxy arrays.
Signed-off-by: Nicko van Someren <nicko@nicko.org>
2024-01-07 18:27:01 +11:00
Nicko van Someren f8cabe82f7 rp2/rp2_dma: Fix fetching 'write' buffers for writing not reading.
Signed-off-by: Nicko van Someren <nicko@nicko.org>
2024-01-07 18:25:52 +11:00
darc 80fd575c8c embed: Fix alloca include for FreeBSD and NetBSD.
Signed-off-by: darc <darcagn@protonmail.com>
2024-01-05 01:03:25 -06:00
Damien George 42eab32a36 windows/windows_mphal: Fix mp_hal_delay_ms() so it runs events.
This changed behaviour in c393f5c123 when the
MICROPY_EVENT_POLL_HOOK macro was removed.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 15:56:34 +11:00
Damien George 0640ff3b97 ports: Move MICROPY_INTERNAL_WFE definition to mphalport.h.
It belongs here because the default value is defined in py/mphal.h.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 15:49:42 +11:00
Damien George d45176fc27 ports: Move MICROPY_PY_LWIP_ENTER/REENTER/EXIT defns to mphalport.h.
Following ad806df857 where the
MICROPY_PY_PENDSV_ENTER/REENTER/EXIT macro definitions were moved to
mphalport.h.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 15:40:06 +11:00
Damien George ee226a8b43 all: Fix "reuse" and "overridden" spelling mistakes.
Codespell doesn't pick up "re-used" or "re-uses", and ignores the tests/
directory, so fix these manually.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 15:08:33 +11:00
Damien George 7a794d0d8e tools/gen-changelog.sh: Exclude "-preview" tags from generated log.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 15:06:14 +11:00
stijn 2b56bab226 tests/run-tests.py: Add an option for running only the failed tests.
Implement the typical 're-run the failed tests' most test runners have, for
convenience.  Accessible via the new --run-failures argument, and
implemented using a json file containing a list of the failed tests.

Signed-off-by: stijn <stijn@ignitron.net>
2024-01-05 12:12:57 +11:00
Damien George 0c81ffd31a tests/multi_net: Generate smaller certs with 2048-bit RSA.
Otherwise running the tests can take a long time when the server is a slow
target (RP2040 takes 23 seconds for a handshake when using 4096-bit RSA).

Also add instructions on how to generate elliptic curve key/certs.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 11:34:01 +11:00
Damien George f0392b8d3d tests/run-multitests.py: Change to dir of test script when running it.
This matches the behaviour of run-tests.py, which sets cwd to the directory
containing the test script, which helps to isolate the filesystem.

It means that the SSL tests no longer need to know the name of their
containing directory to find the certificate files, and helps to run these
tests on bare-metal.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 11:05:34 +11:00
Damien George a003ac2f73 tests/thread: Add a test for accuracy of sleep within a thread.
The existing thread_sleep1.py test only tests execution, not accuracy, of
time.sleep.  Also the existing test only tests sleep(0) on targets like rp2
that can only create a single thread.

The new test in this commit checks for timing accuracy on the main thread
and one other thread when they run at the same time.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 10:35:34 +11:00
Damien George 2265d70add tests/thread: Adjust thread tests so most are able to run on rp2 port.
The aim of this commit is to make it so that the existing thread tests can
be used to test the _thread module on the rp2 port.  The rp2 port only
allows up to one thread to be created at a time, and does not have the GIL
enabled.

The following changes have been made:
- run-tests.py skips mutation tests on rp2, because there's no GIL.
- run-tests.py skips other tests on rp2 that require more than one thread.
- The tests stop trying to start a new thread after there is an OSError,
  which indicates that the system cannot create more threads.
- Some of these tests also now run the test function on the main thread,
  not just the spawned threads.
- In some tests the output printing is adjusted so it's the same regardless
  of how many threads were spawned.
- Some time.sleep(1) are replaced with time.sleep(0) to make the tests run
  a little faster (finish sooner when the work is done).

For the most part the tests are unchanged for existing platforms like esp32
and unix.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-05 10:02:27 +11:00
Damien George 231fc20ce0 tests/run-tests.py: Remove machine_mem.py test from skip list.
This test was removed long ago in eb0e3bab1e.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-04 14:53:11 +11:00
Damien George dc2a4e3cbd rp2/mpthreadport: Fix race with IRQ when entering atomic section.
Prior to this commit there is a potential deadlock in
mp_thread_begin_atomic_section(), when obtaining the atomic_mutex, in the
following situation:
- main thread calls mp_thread_begin_atomic_section() (for whatever reason,
  doesn't matter)
- the second core is running so the main thread grabs the mutex via the
  call mp_thread_mutex_lock(&atomic_mutex, 1), and this succeeds
- before the main thread has a chance to run save_and_disable_interrupts()
  a USB IRQ comes in and the main thread jumps off to process this IRQ
- that USB processing triggers a call to the dcd_event_handler() wrapper
  from commit bcbdee2357
- that then calls mp_sched_schedule_node()
- that then attempts to obtain the atomic section, calling
  mp_thread_begin_atomic_section()
- that call then blocks trying to obtain atomic_mutex
- core0 is now deadlocked on itself, because the main thread has the mutex
  but the IRQ handler (which preempted the main thread) is blocked waiting
  for the mutex, which will never be free

The solution in this commit is to use mutex enter/exit functions that also
atomically disable/restore interrupts.

Fixes issues #12980 and #13288.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-03 15:59:11 +11:00
Damien George 8438c8790c rp2/mutex_extra: Implement additional mutex functions.
These allow entering/exiting a mutex and also disabling/restoring
interrupts, in an atomic way.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-03 15:59:02 +11:00
Damien George c3989e398f rp2/rp2_flash: Lockout second core only when doing flash erase/write.
Using the multicore lockout feature in the general atomic section makes it
much more difficult to get correct.

Signed-off-by: Damien George <damien@micropython.org>
2024-01-03 15:58:39 +11:00
robert-hh 3d0b6276f3 samd/mcu: Fix wrong EIC table entries in pin-af-table.csv.
Fixes:
- SAMD21: PB16
- SAMD51: PB03, PB22 and PB00.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-01-02 18:48:17 +11:00
robert-hh aea93a88f8 samd/mcu/samd21: Reorganize and enable more firmware features.
This commit enables additional features for SAMD21 with external flash:
- Viper and native code support.  On a relatively slow devices, viper and
  native code can be helpful.
- Freeze the asyncio scripts and add the select module.
- Enable Framebuffer support.
- Enable UART flow control.
- Enable a few more features from the extra features set.

Drop onewire and asyncio support from SAMD21 firmware without external
flash, leaving a little bit more room for future extensions.  Asyncio was
anyhow incomplete.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-01-02 18:46:33 +11:00
robert-hh 36d9e98fc6 samd: Remove the MICROPY_PY_MACHINE_RTC config option.
RTC is enabled on all boards.  Therefore the conditional compile is not
needed.  Removing it simplifies the source code a little bit.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-01-02 18:46:11 +11:00
robert-hh 8498b0b13e docs/samd/pinout: Update pinout docs with fixed pin assignment.
Fixes a wrong assignment for Sparkfun SAMD51 Thing Plus, and updates the
sample script for printing the pin info table.

Signed-off-by: robert-hh <robert@hammelrath.com>
2024-01-02 18:44:45 +11:00
iabdalkader f34e27f178 mimxrt/mpbthciport: Add missing extmod/modmachine.h header.
Include extmod/modmachine.h for machine_uart_type declaration.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-02 18:24:19 +11:00
iabdalkader 87d3f8b367 mimxrt/mphalport: Remove redundant NVIC/IRQ defines.
These are already defined in `irq.h`.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2024-01-02 18:19:58 +11:00
Damien George 2037edb5a2 all: Bump version to 1.23.0-preview.
Signed-off-by: Damien George <damien@micropython.org>
2024-01-02 18:11:41 +11:00
1281 zmienionych plików z 42887 dodań i 14496 usunięć

Wyświetl plik

@ -1,3 +1,12 @@
# all: Prune trailing whitespace.
dda9b9c6da5d3c31fa8769e581a753e95a270803
# all: Remove the "STATIC" macro and just use "static" instead.
decf8e6a8bb940d5829ca3296790631fcece7b21
# renesas-ra: Fix spelling mistakes found by codespell.
b3f2f18f927fa2fad10daf63d8c391331f5edf58
# all: Update Python formatting to ruff-format.
bbd8760bd9a2302e5abee29db279102bb11d7732

Wyświetl plik

@ -1,25 +0,0 @@
---
name: Bug report
about: Report an issue
title: ''
labels: bug
assignees: ''
---
* Please search existing issues before raising a new issue. For questions about MicroPython or for help using MicroPython, or any sort of "how do I?" requests, please use the Discussions tab or raise a documentation request instead.
* In your issue, please include a clear and concise description of what the bug is, the expected output, and how to replicate it.
* If this issue involves external hardware, please include links to relevant datasheets and schematics.
* If you are seeing code being executed incorrectly, please provide a minimal example and expected output (e.g. comparison to CPython).
* For build issues, please include full details of your environment, compiler versions, command lines, and build output.
* Please provide as much information as possible about the version of MicroPython you're running, such as:
- firmware file name
- git commit hash and port/board
- version information shown in the REPL (hit Ctrl-B to see the startup message)
* Remove all placeholder text above before submitting.

Wyświetl plik

@ -0,0 +1,107 @@
name: Bug report
description: Report a bug or unexpected behaviour
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Please provide as much detail as you can, it really helps us find and fix bugs faster.
#### Not a bug report?
* If you have a question \"How Do I ...?\", please post it on [GitHub Discussions](https://github.com/orgs/micropython/discussions/) or [Discord](https://discord.gg/RB8HZSAExQ) instead of here.
* For missing or incorrect documentation, or feature requests, then please [choose a different issue type](https://github.com/micropython/micropython/issues/new/choose).
- type: checkboxes
id: terms
attributes:
label: Checks
description: |
Before submitting your bug report, please go over these check points:
options:
- label: |
I agree to follow the MicroPython [Code of Conduct](https://github.com/micropython/micropython/blob/master/CODEOFCONDUCT.md) to ensure a safe and respectful space for everyone.
required: true
- label: |
I've searched for [existing issues](https://github.com/micropython/micropython/issues) matching this bug, and didn't find any.
required: true
- type: input
id: port-board-hw
attributes:
label: Port, board and/or hardware
description: |
Which MicroPython port(s) and board(s) are you using?
placeholder: |
esp32 port, ESP32-Fantastic board.
validations:
required: true
- type: textarea
id: version
attributes:
label: MicroPython version
description: |
To find the version:
1. Open a serial REPL.
2. Type Ctrl-B to see the startup message.
3. Copy-paste that output here.
If the issue is about building MicroPython, please provide output of `git describe --dirty` and as much information as possible about the build environment.
If the version or configuration is modified from the official MicroPython releases or the master branch, please tell us the details of this as well.
placeholder: |
MicroPython v6.28.3 on 2029-01-23; PyBoard 9 with STM32F9
validations:
required: true
- type: textarea
id: steps-reproduce
attributes:
label: Reproduction
description: |
What steps will reproduce the problem? Please include all details that could be relevant about the environment, configuration, etc.
If there is Python code to reproduce this issue then please either:
a. Type it into a code block below ([code block guide](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks)), or
b. Post longer code to a [GitHub gist](https://gist.github.com/), or
c. Create a sample project on GitHub.
For build issues, please provide the exact build commands that you ran.
placeholder: |
1. Copy paste the code provided below into a new file
2. Use `mpremote run` to execute it on the board.
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behaviour
description: |
What did you expect MicroPython to do? If comparing output with CPython or a different MicroPython port/version then please provide that output here.
placeholder: |
Expected to print "Hello World".
Here is the correct output, seen with previous MicroPython version v3.14.159:
> [...]
- type: textarea
id: what-happened
attributes:
label: Observed behaviour
description: |
What actually happened? Where possible please paste exact output, or the complete build log, etc. Very long output can be linked in a [GitHub gist](https://gist.github.com/).
placeholder: |
This unexpected exception appears:
> [...]
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional Information
description: |
Is there anything else that might help to resolve this issue?
value: No, I've provided everything above.
- type: markdown
attributes:
value: |
Thanks for taking the time to help improve MicroPython.

Wyświetl plik

@ -1,16 +0,0 @@
---
name: Documentation issue
about: Report areas of the documentation or examples that need improvement
title: 'docs: '
labels: documentation
assignees: ''
---
* Please search existing issues before raising a new issue. For questions about MicroPython or for help using MicroPython, or any sort of "how do I?" requests, please use the Discussions tab instead.
* Describe what was missing from the documentation and/or what was incorrect/incomplete.
* If possible, please link to the relevant page on https://docs.micropython.org/
* Remove all placeholder text above before submitting.

Wyświetl plik

@ -0,0 +1,44 @@
name: Documentation issue
description: Report areas of the documentation or examples that need improvement
title: "docs: "
labels: ["documentation"]
body:
- type: markdown
attributes:
value: |
This form is for reporting issues with the documentation or examples provided with MicroPython.
If you have a general question \"How Do I ...?\", please post it on [GitHub Discussions](https://github.com/orgs/micropython/discussions/) or [Discord](https://discord.gg/RB8HZSAExQ) instead of here.
- type: checkboxes
id: terms
attributes:
label: Checks
description: |
Before submitting your bug report, please go over these check points:
options:
- label: |
I agree to follow the MicroPython [Code of Conduct](https://github.com/micropython/micropython/blob/master/CODEOFCONDUCT.md) to ensure a safe and respectful space for everyone.
required: true
- label: |
I've searched for [existing issues](https://github.com/micropython/micropython/issues) and didn't find any that matched.
required: true
- type: input
id: page
attributes:
label: Documentation URL
description: |
Does this issue relate to a particular page in the [online documentation](https://docs.micropython.org/en/latest/)? If yes, please paste the URL of the page:
placeholder: |
https://docs.micropython.org/en/latest/
- type: textarea
id: version
attributes:
label: Description
description: |
Please describe what was missing from the documentation and/or what was incorrect/incomplete.
validations:
required: true
- type: markdown
attributes:
value: |
Thanks for taking the time to help improve MicroPython.

Wyświetl plik

@ -1,24 +0,0 @@
---
name: Feature request
about: Request a feature or improvement
title: ''
labels: enhancement
assignees: ''
---
* Please search existing issues before raising a new issue. For questions about MicroPython or for help using MicroPython, or any sort of "how do I?" requests, please use the Discussions tab or raise a documentation request instead.
* Describe the feature you'd like to see added to MicroPython. In particular, what does this feature enable and why is it useful. MicroPython aims to strike a balance between functionality and code size, so please consider whether this feature can be optionally enabled and whether it can be provided in other ways (e.g. pure-Python library).
* For core Python features, where possible please include a link to the relevant PEP.
* For new architectures / ports / boards, please provide links to relevant documentation, specifications, and toolchains. Any information about the popularity and unique features about this hardware would also be useful.
* For features for existing ports (e.g. new peripherals or microcontroller features), please describe which port(s) it applies too, and whether this is could be an extension to the machine API or a port-specific module?
* For drivers (e.g. for external hardware), please link to datasheets and/or existing drivers from other sources.
* Who do you expect will implement the feature you are requesting? Would you be willing to sponsor this work?
* Remove all placeholder text above before submitting.

Wyświetl plik

@ -0,0 +1,65 @@
name: Feature request
description: Request a feature or improvement
labels: ['enhancement']
body:
- type: markdown
attributes:
value: |
This form is for requesting features or improvements in MicroPython.
#### Get feedback first
Before submitting a new feature idea here, suggest starting a discussion on [Discord](https://discord.gg/RB8HZSAExQ) or [GitHub Discussions](https://github.com/orgs/micropython/discussions/) to get early feedback from the community and maintainers.
#### Not a MicroPython core feature?
* If you have a question \"How Do I ...?\", please post it on GitHub Discussions or Discord instead of here.
* Could this feature be implemented as a pure Python library? If so, please open the request on the [micropython-lib repository](https://github.com/micropython/micropython-lib/issues) instead.
- type: checkboxes
id: terms
attributes:
label: Checks
description: |
Before submitting your feature request, please go over these check points:
options:
- label: |
I agree to follow the MicroPython [Code of Conduct](https://github.com/micropython/micropython/blob/master/CODEOFCONDUCT.md) to ensure a safe and respectful space for everyone.
required: true
- label: |
I've searched for [existing issues](https://github.com/micropython/micropython/issues) regarding this feature, and didn't find any.
required: true
- type: textarea
id: feature
attributes:
label: Description
description: |
Describe the feature you'd like to see added to MicroPython. What does this feature enable and why is it useful?
* For core Python features, where possible please include a link to the relevant PEP or CPython documentation.
* For new architectures / ports / boards, please provide links to relevant documentation, specifications, and toolchains. Any information about the popularity and unique features about this hardware would also be useful.
* For features for existing ports (e.g. new peripherals or microcontroller features), please describe which port(s) it applies to, and whether this is could be an extension to the machine API or a port-specific module?
* For drivers (e.g. for external hardware), please link to datasheets and/or existing drivers from other sources.
If there is an existing discussion somewhere about this feature, please add a link to it as well.
validations:
required: true
- type: textarea
id: size
attributes:
label: Code Size
description: |
MicroPython aims to strike a balance between functionality and code size. Can this feature be optionally enabled?
If you believe the usefulness of this feature would outweigh the additional code size, please explain. (It's OK to say you're unsure here, we're happy to discuss this with you.)
- type: checkboxes
id: implementation
attributes:
label: Implementation
options:
- label: I intend to implement this feature and would submit a Pull Request if desirable.
- label: I hope the MicroPython maintainers or community will implement this feature.
- label: I would like to [Sponsor](https://github.com/sponsors/micropython#sponsors) development of this feature.
- type: markdown
attributes:
value: |
Thanks for taking the time to suggest improvements for MicroPython.

Wyświetl plik

@ -1,16 +0,0 @@
---
name: Security report
about: Report a security issue or vulnerability in MicroPython
title: ''
labels: security
assignees: ''
---
* If you need to raise this issue privately with the MicroPython team, please email contact@micropython.org instead.
* Include a clear and concise description of what the security issue is.
* What does this issue allow an attacker to do?
* Remove all placeholder text above before submitting.

Wyświetl plik

@ -0,0 +1,59 @@
name: Security report
description: Report a security issue or vulnerability in MicroPython
labels: ["security"]
body:
- type: markdown
attributes:
value: |
This form is for reporting security issues in MicroPython that are not readily exploitable.
1. For issues that are readily exploitable or have high impact, please email contact@micropython.org instead.
1. If this is a question about security, please ask it in [Discussions](https://github.com/orgs/micropython/discussions/) or [Discord](https://discord.gg/RB8HZSAExQ) instead.
- type: checkboxes
id: terms
attributes:
label: Checks
description: |
Before submitting your bug report, please go over these check points:
options:
- label: |
I agree to follow the MicroPython [Code of Conduct](https://github.com/micropython/micropython/blob/master/CODEOFCONDUCT.md) to ensure a safe and respectful space for everyone.
required: true
- label: I wish to report a specific security issue that is **not readily exploitable and does not have high impact** for MicroPython developers or users.
required: true
- label: |
I've searched for [existing issues](https://github.com/micropython/micropython/issues) and didn't find any that matched.
required: true
- type: input
id: port-board-hw
attributes:
label: Port, board and/or hardware
description: |
Which MicroPython port(s) and board(s) are you using?
placeholder: |
esp32 port, ESP32-Duper board.
- type: textarea
id: version
attributes:
label: MicroPython version
description: |
To find the version:
1. Open a serial REPL.
2. Type Ctrl-B to see the startup message.
3. Copy-paste that output here.
If the version or configuration is modified from the official MicroPython releases or the master branch, please tell us the details of this as well.
placeholder: |
MicroPython v6.28.3 on 2029-01-23; PyBoard 9 with STM32F9
- type: textarea
id: report
attributes:
label: Issue Report
description: |
Please provide a clear and concise description of the security issue.
* What does this issue allow an attacker to do?
* How does the attacker exploit this issue?
validations:
required: true

16
.github/workflows/biome.yml vendored 100644
Wyświetl plik

@ -0,0 +1,16 @@
name: JavaScript code lint and formatting with Biome
on: [push, pull_request]
jobs:
eslint:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Biome
uses: biomejs/setup-biome@v2
with:
version: 1.5.3
- name: Run Biome
run: biome ci --indent-style=space --indent-width=4 tests/ ports/webassembly

Wyświetl plik

@ -18,13 +18,3 @@ jobs:
run: source tools/ci.sh && ci_c_code_formatting_run
- name: Check code formatting
run: git diff --exit-code
code-spelling:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- name: Install packages
run: source tools/ci.sh && ci_code_spell_setup
- name: Run spell checker
run: source tools/ci.sh && ci_code_spell_run

Wyświetl plik

@ -8,9 +8,15 @@ on:
- 'tools/**'
- 'py/**'
- 'extmod/**'
- 'shared/**'
- 'lib/**'
- 'ports/bare-arm/**'
- 'ports/mimxrt/**'
- 'ports/minimal/**'
- 'ports/rp2/**'
- 'ports/samd/**'
- 'ports/stm32/**'
- 'ports/unix/**'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}

13
.github/workflows/codespell.yml vendored 100644
Wyświetl plik

@ -0,0 +1,13 @@
name: Check spelling with codespell
on: [push, pull_request]
jobs:
codespell:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# codespell version should be kept in sync with .pre-commit-config.yml
- run: pip install --user codespell==2.2.6 tomli
- run: codespell

Wyświetl plik

@ -35,7 +35,7 @@ jobs:
- name: Cached ESP-IDF install
id: cache_esp_idf
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: |
./esp-idf/

Wyświetl plik

@ -20,8 +20,13 @@ concurrency:
jobs:
build:
runs-on: ubuntu-20.04
defaults:
run:
working-directory: 'micropython repo' # test build with space in path
steps:
- uses: actions/checkout@v4
with:
path: 'micropython repo'
- name: Install packages
run: source tools/ci.sh && ci_mimxrt_setup
- name: Build

Wyświetl plik

@ -20,8 +20,13 @@ concurrency:
jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: 'micropython repo' # test build with space in path
steps:
- uses: actions/checkout@v4
with:
path: 'micropython repo'
- name: Install packages
run: source tools/ci.sh && ci_rp2_setup
- name: Build

Wyświetl plik

@ -25,6 +25,7 @@ jobs:
ci_func: # names are functions in ci.sh
- stm32_pyb_build
- stm32_nucleo_build
- stm32_misc_build
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v4

Wyświetl plik

@ -88,10 +88,11 @@ jobs:
(cd ports/unix && gcov -o build-coverage/py ../../py/*.c || true)
(cd ports/unix && gcov -o build-coverage/extmod ../../extmod/*.c || true)
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v4
with:
fail_ci_if_error: true
verbose: true
token: ${{ secrets.CODECOV_TOKEN }}
- name: Print failures
if: failure()
run: tests/run-tests.py --print-failures

Wyświetl plik

@ -18,7 +18,134 @@ concurrency:
cancel-in-progress: true
jobs:
build:
build-vs:
strategy:
fail-fast: false
matrix:
platform: [x86, x64]
configuration: [Debug, Release]
variant: [dev, standard]
visualstudio: ['2017', '2019', '2022']
include:
- visualstudio: '2017'
runner: windows-latest
vs_version: '[15, 16)'
- visualstudio: '2019'
runner: windows-2019
vs_version: '[16, 17)'
- visualstudio: '2022'
runner: windows-2022
vs_version: '[17, 18)'
# trim down the number of jobs in the matrix
exclude:
- variant: standard
configuration: Debug
- visualstudio: '2019'
configuration: Debug
runs-on: ${{ matrix.runner }}
steps:
- name: Install Visual Studio 2017
if: matrix.visualstudio == '2017'
run: |
choco install visualstudio2017buildtools
choco install visualstudio2017-workload-vctools
choco install windows-sdk-8.1
- uses: microsoft/setup-msbuild@v2
with:
vs-version: ${{ matrix.vs_version }}
- uses: actions/setup-python@v5
if: matrix.runner == 'windows-2019'
with:
python-version: '3.9'
- uses: actions/checkout@v4
- name: Build mpy-cross.exe
run: msbuild mpy-cross\mpy-cross.vcxproj -maxcpucount -property:Configuration=${{ matrix.configuration }} -property:Platform=${{ matrix.platform }}
- name: Update submodules
run: git submodule update --init lib/micropython-lib
- name: Build micropython.exe
run: msbuild ports\windows\micropython.vcxproj -maxcpucount -property:Configuration=${{ matrix.configuration }} -property:Platform=${{ matrix.platform }} -property:PyVariant=${{ matrix.variant }}
- name: Get micropython.exe path
id: get_path
run: |
$exePath="$(msbuild ports\windows\micropython.vcxproj -nologo -v:m -t:ShowTargetPath -property:Configuration=${{ matrix.configuration }} -property:Platform=${{ matrix.platform }} -property:PyVariant=${{ matrix.variant }})"
echo ("micropython=" + $exePath.Trim()) >> $env:GITHUB_OUTPUT
- name: Run tests
id: test
env:
MICROPY_MICROPYTHON: ${{ steps.get_path.outputs.micropython }}
working-directory: tests
run: python run-tests.py
- name: Print failures
if: failure() && steps.test.conclusion == 'failure'
working-directory: tests
run: python run-tests.py --print-failures
- name: Run mpy tests
id: test_mpy
env:
MICROPY_MICROPYTHON: ${{ steps.get_path.outputs.micropython }}
working-directory: tests
run: python run-tests.py --via-mpy -d basics float micropython
- name: Print mpy failures
if: failure() && steps.test_mpy.conclusion == 'failure'
working-directory: tests
run: python run-tests.py --print-failures
build-mingw:
strategy:
fail-fast: false
matrix:
variant: [dev, standard]
sys: [mingw32, mingw64]
include:
- sys: mingw32
env: i686
- sys: mingw64
env: x86_64
runs-on: windows-2022
env:
CHERE_INVOKING: enabled_from_arguments
defaults:
run:
shell: msys2 {0}
steps:
- name: Get Python path
id: python_path
shell: python
run: |
import os
import sys
output = f"python={os.fspath(sys.executable)}"
print(output)
with open(os.environ["GITHUB_OUTPUT"], "w") as f:
f.write(output)
- uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.sys }}
update: true
install: >-
make
mingw-w64-${{ matrix.env }}-gcc
pkg-config
python3
git
diffutils
- uses: actions/checkout@v4
- name: Build mpy-cross.exe
run: make -C mpy-cross -j2
- name: Update submodules
run: make -C ports/windows VARIANT=${{ matrix.variant }} submodules
- name: Build micropython.exe
run: make -C ports/windows -j2 VARIANT=${{ matrix.variant }}
- name: Run tests
id: test
# msys python breaks tests so we need to use "real" windows python
run: MICROPY_CPYTHON3=$(cygpath "${{ steps.python_path.outputs.python }}") make -C ports/windows test_full VARIANT=${{ matrix.variant }}
- name: Print failures
if: failure() && steps.test.conclusion == 'failure'
working-directory: tests
run: python run-tests.py --print-failures
cross-build-on-linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

Wyświetl plik

@ -1,11 +1,13 @@
# https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
name: Python code lint and formatting with ruff
on: [push, pull_request]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# ruff version should be kept in sync with .pre-commit-config.yaml
- run: pip install --user ruff==0.1.3
- run: ruff check --output-format=github .
- run: ruff format --diff .

11
.gitmodules vendored
Wyświetl plik

@ -9,7 +9,7 @@
url = https://github.com/lwip-tcpip/lwip.git
[submodule "lib/berkeley-db-1.xx"]
path = lib/berkeley-db-1.xx
url = https://github.com/pfalcon/berkeley-db-1.xx
url = https://github.com/micropython/berkeley-db-1.xx
[submodule "lib/stm32lib"]
path = lib/stm32lib
url = https://github.com/micropython/stm32lib
@ -59,3 +59,12 @@
[submodule "lib/protobuf-c"]
path = lib/protobuf-c
url = https://github.com/protobuf-c/protobuf-c.git
[submodule "lib/open-amp"]
path = lib/open-amp
url = https://github.com/OpenAMP/open-amp.git
[submodule "lib/libmetal"]
path = lib/libmetal
url = https://github.com/OpenAMP/libmetal.git
[submodule "lib/arduino-lib"]
path = lib/arduino-lib
url = https://github.com/arduino/arduino-lib-mpy.git

Wyświetl plik

@ -12,7 +12,16 @@ repos:
verbose: true
stages: [commit-msg]
- repo: https://github.com/charliermarsh/ruff-pre-commit
# Version should be kept in sync with .github/workflows/ruff.yml
rev: v0.1.3
hooks:
- id: ruff
- id: ruff-format
- repo: https://github.com/codespell-project/codespell
# Version should be kept in sync with .github/workflows/codespell.yml
rev: v2.2.6
hooks:
- id: codespell
name: Spellcheck for changed files (codespell)
additional_dependencies:
- tomli

Wyświetl plik

@ -104,6 +104,22 @@ This command may work, please raise a new Issue if it doesn't:
curl -L https://github.com/Homebrew/homebrew-core/raw/2b07d8192623365078a8b855a164ebcdf81494a6/Formula/uncrustify.rb > uncrustify.rb && brew install uncrustify.rb && rm uncrustify.rb
```
Code spell checking
===================
Code spell checking is done using [codespell](https://github.com/codespell-project/codespell#codespell)
and runs in a GitHub action in CI. Codespell is configured via `pyproject.toml`
to avoid false positives. It is recommended run codespell before submitting a
PR. To simplify this, codespell is configured as a pre-commit hook and will be
installed if you run `pre-commit install` (see below).
If you want to install and run codespell manually, you can do so by running:
```
$ pip install codespell tomli
$ codespell
```
Automatic Pre-Commit Hooks
==========================

Wyświetl plik

@ -48,12 +48,14 @@ used during the build process and is not part of the compiled source code.
/cmsis (BSD-3-clause)
/crypto-algorithms (NONE)
/libhydrogen (ISC)
/libmetal (BSD-3-clause)
/littlefs (BSD-3-clause)
/lwip (BSD-3-clause)
/mynewt-nimble (Apache-2.0)
/nrfx (BSD-3-clause)
/nxp_driver (BSD-3-Clause)
/oofatfs (BSD-1-clause)
/open-amp (BSD-3-clause)
/pico-sdk (BSD-3-clause)
/re15 (BSD-3-clause)
/stm32lib (BSD-3-clause)
@ -69,6 +71,8 @@ used during the build process and is not part of the compiled source code.
/FreeRTOS (GPL-2.0 with FreeRTOS exception)
/esp32
/ppp_set_auth.* (Apache-2.0)
/rp2
/mutex_extra.c (BSD-3-clause)
/stm32
/usbd*.c (MCD-ST Liberty SW License Agreement V2)
/stm32_it.* (MIT + BSD-3-clause)

Wyświetl plik

@ -98,7 +98,7 @@ Then also edit ``py/lexer.c`` to add the new keyword literal text:
.. code-block:: c
:emphasize-lines: 12
STATIC const char *const tok_kw[] = {
static const char *const tok_kw[] = {
...
"or",
"pass",
@ -157,7 +157,7 @@ The most relevant method you should know about is this:
mp_compile_to_raw_code(parse_tree, source_file, is_repl, &cm);
// Create and return a function object that executes the outer module.
return mp_make_function_from_raw_code(cm.rc, cm.context, NULL);
return mp_make_function_from_proto_fun(cm.rc, cm.context, NULL);
}
The compiler compiles the code in four passes: scope, stack size, code size and emit.
@ -301,7 +301,7 @@ code statement:
.. code-block:: c
STATIC void emit_native_unary_op(emit_t *emit, mp_unary_op_t op) {
static void emit_native_unary_op(emit_t *emit, mp_unary_op_t op) {
vtype_kind_t vtype;
emit_pre_pop_reg(emit, &vtype, REG_ARG_2);
if (vtype == VTYPE_PYOBJ) {

Wyświetl plik

@ -112,7 +112,7 @@ Check that you have Python available on your system:
.. code-block:: bash
$ python3
Python 3.5.0 (default, Jul 17 2020, 14:04:10)
Python 3.5.0 (default, Jul 17 2020, 14:04:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Wyświetl plik

@ -48,16 +48,16 @@ hypothetical new module ``subsystem`` in the file ``modsubsystem.c``:
#if MICROPY_PY_SUBSYSTEM
// info()
STATIC mp_obj_t py_subsystem_info(void) {
static mp_obj_t py_subsystem_info(void) {
return MP_OBJ_NEW_SMALL_INT(42);
}
MP_DEFINE_CONST_FUN_OBJ_0(subsystem_info_obj, py_subsystem_info);
STATIC const mp_rom_map_elem_t mp_module_subsystem_globals_table[] = {
static const mp_rom_map_elem_t mp_module_subsystem_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_subsystem) },
{ MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&subsystem_info_obj) },
};
STATIC MP_DEFINE_CONST_DICT(mp_module_subsystem_globals, mp_module_subsystem_globals_table);
static MP_DEFINE_CONST_DICT(mp_module_subsystem_globals, mp_module_subsystem_globals_table);
const mp_obj_module_t mp_module_subsystem = {
.base = { &mp_type_module },

Wyświetl plik

@ -128,7 +128,7 @@ The file ``factorial.c`` contains:
#include "py/dynruntime.h"
// Helper function to compute factorial
STATIC mp_int_t factorial_helper(mp_int_t x) {
static mp_int_t factorial_helper(mp_int_t x) {
if (x == 0) {
return 1;
}
@ -136,7 +136,7 @@ The file ``factorial.c`` contains:
}
// This is the function which will be called from Python, as factorial(x)
STATIC mp_obj_t factorial(mp_obj_t x_obj) {
static mp_obj_t factorial(mp_obj_t x_obj) {
// Extract the integer from the MicroPython input object
mp_int_t x = mp_obj_get_int(x_obj);
// Calculate the factorial
@ -145,7 +145,7 @@ The file ``factorial.c`` contains:
return mp_obj_new_int(result);
}
// Define a Python reference to the function above
STATIC MP_DEFINE_CONST_FUN_OBJ_1(factorial_obj, factorial);
static MP_DEFINE_CONST_FUN_OBJ_1(factorial_obj, factorial);
// This is the entry point and is called when the module is imported
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {

Wyświetl plik

@ -33,7 +33,7 @@ Variables
MicroPython processes local and global variables differently. Global variables
are stored and looked up from a global dictionary that is allocated on the heap
(note that each module has its own separate dict, so separate namespace).
Local variables on the other hand are are stored on the Python value stack, which may
Local variables on the other hand are stored on the Python value stack, which may
live on the C stack or on the heap. They are accessed directly by their offset
within the Python stack, which is more efficient than a global lookup in a dict.

Wyświetl plik

@ -83,7 +83,7 @@ The basic MicroPython firmware is implemented in the main port file, e.g ``main.
}
// There is no filesystem so opening a file raises an exception.
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
mp_lexer_t *mp_lexer_new_from_file(qstr filename) {
mp_raise_OSError(MP_ENOENT);
}
@ -262,17 +262,17 @@ To add a custom module like ``myport``, first add the module definition in a fil
#include "py/runtime.h"
STATIC mp_obj_t myport_info(void) {
static mp_obj_t myport_info(void) {
mp_printf(&mp_plat_print, "info about my port\n");
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(myport_info_obj, myport_info);
static MP_DEFINE_CONST_FUN_OBJ_0(myport_info_obj, myport_info);
STATIC const mp_rom_map_elem_t myport_module_globals_table[] = {
static const mp_rom_map_elem_t myport_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_myport) },
{ MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&myport_info_obj) },
};
STATIC MP_DEFINE_CONST_DICT(myport_module_globals, myport_module_globals_table);
static MP_DEFINE_CONST_DICT(myport_module_globals, myport_module_globals_table);
const mp_obj_module_t myport_module = {
.base = { &mp_type_module },

Wyświetl plik

@ -0,0 +1,33 @@
.. Preamble section inserted into generated output
Positional-only Parameters
--------------------------
To save code size, many functions that accept keyword arguments in CPython only accept positional arguments in MicroPython.
MicroPython marks positional-only parameters in the same way as CPython, by inserting a ``/`` to mark the end of the positional parameters. Any function whose signature ends in ``/`` takes *only* positional arguments. For more details, see `PEP 570 <https://peps.python.org/pep-0570/>`_.
Example
~~~~~~~
For example, in CPython 3.4 this is the signature of the constructor ``socket.socket``::
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
However, the signature documented in :func:`MicroPython<socket.socket>` is::
socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, /)
The ``/`` at the end of the parameters indicates that they are all positional-only in MicroPython. The following code works in CPython but not in most MicroPython ports::
import socket
s = socket.socket(type=socket.SOCK_DGRAM)
MicroPython will raise an exception::
TypeError: function doesn't take keyword arguments
The following code will work in both CPython and MicroPython::
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

Wyświetl plik

@ -105,4 +105,4 @@ Changes to built-in modules:
.. rubric:: Notes
.. [#ftimenanosec] Only :func:`time.time_ns` is implemented.
.. [#ftimenanosec] Only :func:`time.time_ns` is implemented.

Wyświetl plik

@ -18,6 +18,9 @@ working with this board it may be useful to get an overview of the microcontroll
general.rst
tutorial/index.rst
Note that there are several varieties of ESP32 -- ESP32, ESP32C3, ESP32S2, ESP32S3 --
supported by MicroPython, with some differences in functionality between them.
Installing MicroPython
----------------------
@ -58,12 +61,18 @@ The :mod:`esp32` module::
import esp32
esp32.raw_temperature() # read the internal temperature of the MCU, in Fahrenheit
esp32.ULP() # access to the Ultra-Low-Power Co-processor
esp32.ULP() # access to the Ultra-Low-Power Co-processor, not on ESP32C3
Note that the temperature sensor in the ESP32 will typically read higher than
ambient due to the IC getting warm while it runs. This effect can be minimised
by reading the temperature sensor immediately after waking up from sleep.
ESP32C3, ESP32S2, and ESP32S3 also have an internal temperature sensor available.
It is implemented a bit differently to the ESP32 and returns the temperature in
Celsius::
esp32.mcu_temperature() # read the internal temperature of the MCU, in Celsius
Networking
----------
@ -128,6 +137,7 @@ The keyword arguments for the constructor defining the PHY type and interface ar
- mdc=pin-object # set the mdc and mdio pins.
- mdio=pin-object
- reset=pin-object # set the reset pin of the PHY device.
- power=pin-object # set the pin which switches the power of the PHY device.
- phy_type=<type> # Select the PHY device type. Supported devices are PHY_LAN8710,
PHY_LAN8720, PH_IP101, PHY_RTL8201, PHY_DP83848 and PHY_KSZ8041
@ -650,15 +660,15 @@ SD card
See :ref:`machine.SDCard <machine.SDCard>`. ::
import machine, os
import machine, os, vfs
# Slot 2 uses pins sck=18, cs=5, miso=19, mosi=23
sd = machine.SDCard(slot=2)
os.mount(sd, '/sd') # mount
vfs.mount(sd, '/sd') # mount
os.listdir('/sd') # list directory contents
os.umount('/sd') # eject
vfs.umount('/sd') # eject
RMT
---

Wyświetl plik

@ -312,7 +312,7 @@ Broadcaster Role (Advertiser)
in all broadcasts, and *resp_data* is send in reply to an active scan.
**Note:** if *adv_data* (or *resp_data*) is ``None``, then the data passed
to the previous call to ``gap_advertise`` will be re-used. This allows a
to the previous call to ``gap_advertise`` will be reused. This allows a
broadcaster to resume advertising with just ``gap_advertise(interval_us)``.
To clear the advertising payload pass an empty ``bytes``, i.e. ``b''``.
@ -722,7 +722,7 @@ Pairing and bonding
and ``_IRQ_SET_SECRET`` events.
**Note:** This is currently only supported when using the NimBLE stack on
STM32 and Unix (not ESP32).
ESP32, STM32 and Unix.
.. method:: BLE.gap_pair(conn_handle, /)

Wyświetl plik

@ -18,7 +18,9 @@ Classes
appends and pops from either side of the deque. New deques are created
using the following arguments:
- *iterable* must be the empty tuple, and the new deque is created empty.
- *iterable* is an iterable used to populate the deque when it is
created. It can be an empty tuple or list to create a deque that
is initially empty.
- *maxlen* must be specified and the deque will be bounded to this
maximum length. Once the deque is full, any new items added will
@ -26,18 +28,37 @@ Classes
- The optional *flags* can be 1 to check for overflow when adding items.
As well as supporting `bool` and `len`, deque objects have the following
methods:
Deque objects support `bool`, `len`, iteration and subscript load and store.
They also have the following methods:
.. method:: deque.append(x)
Add *x* to the right side of the deque.
Raises IndexError if overflow checking is enabled and there is no more room left.
Raises ``IndexError`` if overflow checking is enabled and there is
no more room in the queue.
.. method:: deque.appendleft(x)
Add *x* to the left side of the deque.
Raises ``IndexError`` if overflow checking is enabled and there is
no more room in the queue.
.. method:: deque.pop()
Remove and return an item from the right side of the deque.
Raises ``IndexError`` if no items are present.
.. method:: deque.popleft()
Remove and return an item from the left side of the deque.
Raises IndexError if no items are present.
Raises ``IndexError`` if no items are present.
.. method:: deque.extend(iterable)
Extend the deque by appending all the items from *iterable* to
the right of the deque.
Raises ``IndexError`` if overflow checking is enabled and there is
no more room in the deque.
.. function:: namedtuple(name, fields)

Wyświetl plik

@ -114,7 +114,7 @@ methods to enable over-the-air (OTA) updates.
These methods implement the simple and :ref:`extended
<block-device-interface>` block protocol defined by
:class:`os.AbstractBlockDev`.
:class:`vfs.AbstractBlockDev`.
.. method:: Partition.set_boot()

Wyświetl plik

@ -103,7 +103,9 @@ the following libraries.
micropython.rst
neopixel.rst
network.rst
openamp.rst
uctypes.rst
vfs.rst
The following libraries provide drivers for hardware components.

Wyświetl plik

@ -26,7 +26,7 @@ Constructors
Access the ADC peripheral identified by *id*, which may be an integer
or string.
The *bits* argument, if given, sets the resolution in bits of the
conversion process. If not specified then the previous or default
resolution is used.

Wyświetl plik

@ -86,7 +86,7 @@ Specific PWM class implementations
The following concrete class(es) implement enhancements to the PWM class.
| :ref:`pyb.Timer for PyBoard <pyb.Timer>`
| :ref:`pyb.Timer for PyBoard <pyb.Timer>`
Limitations of PWM
------------------
@ -103,7 +103,7 @@ Limitations of PWM
Some ports like the RP2040 one use a fractional divider, which allow a finer
granularity of the frequency at higher frequencies by switching the PWM
pulse duration between two adjacent values, such that the resulting average
frequency is more close to the intended one, at the cost of spectral purity.
frequency is more close to the intended one, at the cost of spectral purity.
* The duty cycle has the same discrete nature and its absolute accuracy is not
achievable. On most hardware platforms the duty will be applied at the next

Wyświetl plik

@ -75,6 +75,21 @@ Methods
- ``wake`` specifies the sleep mode from where this interrupt can wake
up the system.
.. method:: RTC.memory([data])
``RTC.memory(data)`` will write *data* to the RTC memory, where *data* is any
object which supports the buffer protocol (including `bytes`, `bytearray`,
`memoryview` and `array.array`). ``RTC.memory()`` reads RTC memory and returns
a `bytes` object.
Data written to RTC user memory is persistent across restarts, including
`machine.soft_reset()` and `machine.deepsleep()`.
The maximum length of RTC user memory is 2048 bytes by default on esp32,
and 492 bytes on esp8266.
Availability: esp32, esp8266 ports.
Constants
---------

Wyświetl plik

@ -20,11 +20,11 @@ more info regarding the pins which can be remapped to be used with a SD card.
Example usage::
from machine import SD
import os
import vfs
# clk cmd and dat0 pins must be passed along with
# their respective alternate functions
sd = machine.SD(pins=('GP10', 'GP11', 'GP15'))
os.mount(sd, '/sd')
vfs.mount(sd, '/sd')
# do normal file operations
Constructors

Wyświetl plik

@ -27,10 +27,10 @@ vary from platform to platform.
This class provides access to SD or MMC storage cards using either
a dedicated SD/MMC interface hardware or through an SPI channel.
The class implements the block protocol defined by :class:`os.AbstractBlockDev`.
The class implements the block protocol defined by :class:`vfs.AbstractBlockDev`.
This allows the mounting of an SD card to be as simple as::
os.mount(machine.SDCard(), "/sd")
vfs.mount(machine.SDCard(), "/sd")
The constructor takes the following parameters:

Wyświetl plik

@ -0,0 +1,296 @@
.. currentmodule:: machine
.. _machine.USBDevice:
class USBDevice -- USB Device driver
====================================
.. note:: ``machine.USBDevice`` is currently only supported on the rp2 and samd
ports.
USBDevice provides a low-level Python API for implementing USB device functions using
Python code.
.. warning:: This low-level API assumes familiarity with the USB standard. There
are high-level `usb driver modules in micropython-lib`_ which provide a
simpler interface and more built-in functionality.
Terminology
-----------
- A "Runtime" USB device interface or driver is one which is defined using this
Python API after MicroPython initially starts up.
- A "Built-in" USB device interface or driver is one that is compiled into the
MicroPython firmware, and is always available. Examples are USB-CDC (serial
port) which is usually enabled by default. Built-in USB-MSC (Mass Storage) is an
option on some ports.
Lifecycle
---------
Managing a runtime USB interface can be tricky, especially if you are communicating
with MicroPython over a built-in USB-CDC serial port that's part of the same USB
device.
- A MicroPython soft reset will always clear all runtime USB interfaces, which
results in the entire USB device disconnecting from the host. If MicroPython
is also providing a built-in USB-CDC serial port then this will re-appear
after the soft reset.
This means some functions (like ``mpremote run``) that target the USB-CDC
serial port will immediately fail if a runtime USB interface is active,
because the port goes away when ``mpremote`` triggers a soft reset. The
operation should succeed on the second try, as after the soft reset there is
no more runtime USB interface.
- To configure a runtime USB device on every boot, it's recommended to place the
configuration code in the ``boot.py`` file on the :ref:`device VFS
<filesystem>`. On each reset this file is executed before the USB subsystem is
initialised (and before ``main.py``), so it allows the board to come up with the runtime
USB device immediately.
- For development or debugging, it may be convenient to connect a hardware
serial REPL and disable the built-in USB-CDC serial port entirely. Not all ports
support this (currently only ``rp2``). The custom build should be configured
with ``#define MICROPY_HW_USB_CDC (0)`` and ``#define
MICROPY_HW_ENABLE_UART_REPL (1)``.
Constructors
------------
.. class:: USBDevice()
Construct a USBDevice object.
.. note:: This object is a singleton, each call to this constructor
returns the same object reference.
Methods
-------
.. method:: USBDevice.config(desc_dev, desc_cfg, desc_strs=None, open_itf_cb=None, reset_cb=None, control_xfer_cb=None, xfer_cb=None)
Configures the ``USBDevice`` singleton object with the USB runtime device
state and callback functions:
- ``desc_dev`` - A bytes-like object containing
the new USB device descriptor.
- ``desc_cfg`` - A bytes-like object containing the
new USB configuration descriptor.
- ``desc_strs`` - Optional object holding strings or bytes objects
containing USB string descriptor values. Can be a list, a dict, or any
object which supports subscript indexing with integer keys (USB string
descriptor index).
Strings are an optional USB feature, and this parameter can be unset
(default) if no strings are referenced in the device and configuration
descriptors, or if only built-in strings should be used.
Apart from index 0, all the string values should be plain ASCII. Index 0
is the special "languages" USB descriptor, represented as a bytes object
with a custom format defined in the USB standard. ``None`` can be
returned at index 0 in order to use a default "English" language
descriptor.
To fall back to providing a built-in string value for a given index, a
subscript lookup can return ``None``, raise ``KeyError``, or raise
``IndexError``.
- ``open_itf_cb`` - This callback is called once for each interface
or Interface Association Descriptor in response to a Set
Configuration request from the USB Host (the final stage before
the USB device is available to the host).
The callback takes a single argument, which is a memoryview of the
interface or IAD descriptor that the host is accepting (including
all associated descriptors). It is a view into the same
``desc_cfg`` object that was provided as a separate
argument to this function. The memoryview is only valid until the
callback function returns.
- ``reset_cb`` - This callback is called when the USB host performs
a bus reset. The callback takes no arguments. Any in-progress
transfers will never complete. The USB host will most likely
proceed to re-enumerate the USB device by calling the descriptor
callbacks and then ``open_itf_cb()``.
- ``control_xfer_cb`` - This callback is called one or more times
for each USB control transfer (device Endpoint 0). It takes two
arguments.
The first argument is the control transfer stage. It is one of:
- ``1`` for SETUP stage.
- ``2`` for DATA stage.
- ``3`` for ACK stage.
Second argument is a memoryview to read the USB control request
data for this stage. The memoryview is only valid until the
callback function returns. Data in this memoryview will be the same
across each of the three stages of a single transfer.
A successful transfer consists of this callback being called in sequence
for the three stages. Generally speaking, if a device wants to do
something in response to a control request then it's best to wait until
the ACK stage to confirm the host controller completed the transfer as
expected.
The callback should return one of the following values:
- ``False`` to stall the endpoint and reject the transfer. It won't
proceed to any remaining stages.
- ``True`` to continue the transfer to the next stage.
- A buffer object can be returned at the SETUP stage when the transfer
will send or receive additional data. Typically this is the case when
the ``wLength`` field in the request has a non-zero value. This should
be a writable buffer for an ``OUT`` direction transfer, or a readable
buffer with data for an ``IN`` direction transfer.
- ``xfer_cb`` - This callback is called whenever a non-control
transfer submitted by calling :func:`USBDevice.submit_xfer` completes.
The callback has three arguments:
1. The Endpoint number for the completed transfer.
2. Result value: ``True`` if the transfer succeeded, ``False``
otherwise.
3. Number of bytes successfully transferred. In the case of a
"short" transfer, The result is ``True`` and ``xferred_bytes``
will be smaller than the length of the buffer submitted for the
transfer.
.. note:: If a bus reset occurs (see :func:`USBDevice.reset`),
``xfer_cb`` is not called for any transfers that have not
already completed.
.. method:: USBDevice.active(self, [value] /)
Returns the current active state of this runtime USB device as a
boolean. The runtime USB device is "active" when it is available to
interact with the host, it doesn't mean that a USB Host is actually
present.
If the optional ``value`` argument is set to a truthy value, then
the USB device will be activated.
If the optional ``value`` argument is set to a falsey value, then
the USB device is deactivated. While the USB device is deactivated,
it will not be detected by the USB Host.
To simulate a disconnect and a reconnect of the USB device, call
``active(False)`` followed by ``active(True)``. This may be
necessary if the runtime device configuration has changed, so that
the host sees the new device.
.. attribute:: USBDevice.builtin_driver
This attribute holds the current built-in driver configuration, and must be
set to one of the ``USBDevice.BUILTIN_`` named constants defined on this object.
By default it holds the value :data:`USBDevice.BUILTIN_NONE`.
Runtime USB device must be inactive when setting this field. Call the
:func:`USBDevice.active` function to deactivate before setting if necessary
(and again to activate after setting).
If this value is set to any value other than :data:`USBDevice.BUILTIN_NONE` then
the following restrictions apply to the :func:`USBDevice.config` arguments:
- ``desc_cfg`` should begin with the built-in USB interface descriptor data
accessible via :data:`USBDevice.builtin_driver` attribute ``desc_cfg``.
Descriptors appended after the built-in configuration descriptors should use
interface, string and endpoint numbers starting from the max built-in values
defined in :data:`USBDevice.builtin_driver` attributes ``itf_max``, ``str_max`` and
``ep_max``.
- The ``bNumInterfaces`` field in the built-in configuration
descriptor will also need to be updated if any new interfaces
are appended to the end of ``desc_cfg``.
- ``desc_strs`` should either be ``None`` or a list/dictionary where index
values less than ``USBDevice.builtin_driver.str_max`` are missing or have
value ``None``. This reserves those string indexes for the built-in
drivers. Placing a different string at any of these indexes overrides that
string in the built-in driver.
.. method:: USBDevice.submit_xfer(self, ep, buffer /)
Submit a USB transfer on endpoint number ``ep``. ``buffer`` must be
an object implementing the buffer interface, with read access for
``IN`` endpoints and write access for ``OUT`` endpoints.
.. note:: ``ep`` cannot be the control Endpoint number 0. Control
transfers are built up through successive executions of
``control_xfer_cb``, see above.
Returns ``True`` if successful, ``False`` if the transfer could not
be queued (as USB device is not configured by host, or because
another transfer is queued on this endpoint.)
When the USB host completes the transfer, the ``xfer_cb`` callback
is called (see above).
Raises ``OSError`` with reason ``MP_EINVAL`` If the USB device is not
active.
.. method:: USBDevice.stall(self, ep, [stall] /)
Calling this function gets or sets the STALL state of a device endpoint.
``ep`` is the number of the endpoint.
If the optional ``stall`` parameter is set, this is a boolean flag
for the STALL state.
The return value is the current stall state of the endpoint (before
any change made by this function).
An endpoint that is set to STALL may remain stalled until this
function is called again, or STALL may be cleared automatically by
the USB host.
Raises ``OSError`` with reason ``MP_EINVAL`` If the USB device is not
active.
Constants
---------
.. data:: USBDevice.BUILTIN_NONE
.. data:: USBDevice.BUILTIN_DEFAULT
.. data:: USBDevice.BUILTIN_CDC
.. data:: USBDevice.BUILTIN_MSC
.. data:: USBDevice.BUILTIN_CDC_MSC
These constant objects hold the built-in descriptor data which is
compiled into the MicroPython firmware. ``USBDevice.BUILTIN_NONE`` and
``USBDevice.BUILTIN_DEFAULT`` are always present. Additional objects may be present
depending on the firmware build configuration and the actual built-in drivers.
.. note:: Currently at most one of ``USBDevice.BUILTIN_CDC``,
``USBDevice.BUILTIN_MSC`` and ``USBDevice.BUILTIN_CDC_MSC`` is defined
and will be the same object as ``USBDevice.BUILTIN_DEFAULT``.
These constants are defined to allow run-time detection of
the built-in driver (if any). Support for selecting one of
multiple built-in driver configurations may be added in the
future.
These values are assigned to :data:`USBDevice.builtin_driver` to get/set the
built-in configuration.
Each object contains the following read-only fields:
- ``itf_max`` - One more than the highest bInterfaceNumber value used
in the built-in configuration descriptor.
- ``ep_max`` - One more than the highest bEndpointAddress value used
in the built-in configuration descriptor. Does not include any
``IN`` flag bit (0x80).
- ``str_max`` - One more than the highest string descriptor index
value used by any built-in descriptor.
- ``desc_dev`` - ``bytes`` object containing the built-in USB device
descriptor.
- ``desc_cfg`` - ``bytes`` object containing the complete built-in USB
configuration descriptor.
.. _usb driver modules in micropython-lib: https://github.com/micropython/micropython-lib/tree/master/micropython/usb#readme

Wyświetl plik

@ -265,3 +265,4 @@ Classes
machine.WDT.rst
machine.SD.rst
machine.SDCard.rst
machine.USBDevice.rst

Wyświetl plik

@ -0,0 +1,115 @@
:mod:`openamp` -- provides standard Asymmetric Multiprocessing (AMP) support
============================================================================
.. module:: openamp
:synopsis: provides standard Asymmetric Multiprocessing (AMP) support
The ``openamp`` module provides a standard inter-processor communications infrastructure
for MicroPython. The module handles all of the details of OpenAMP, such as setting up
the shared resource table, initializing vrings, etc. It provides an API for using the
RPMsg bus infrastructure with the `Endpoint` class, and provides processor Life Cycle
Management (LCM) support, such as loading firmware and starting and stopping a remote
core, via the `RemoteProc` class.
Example usage::
import openamp
def ept_recv_callback(src, data):
print("Received message on endpoint", data)
# Create a new RPMsg endpoint to communicate with the remote core.
ept = openamp.Endpoint("vuart-channel", callback=ept_recv_callback)
# Create a RemoteProc object, load its firmware and start it.
rproc = openamp.RemoteProc("virtual_uart.elf") # Or entry point address (ex 0x081E0000)
rproc.start()
while True:
if ept.is_ready():
ept.send("data")
Functions
---------
.. function:: new_service_callback(ns_callback)
Set the new service callback.
The *ns_callback* argument is a function that will be called when the remote processor
announces new services. At that point the host processor can choose to create the
announced endpoint, if this particular service is supported, or ignore it if it's
not. If this function is not set, the host processor should first register the
endpoint locally, and it will be automatically bound when the remote announces
the service.
Endpoint class
--------------
.. class:: Endpoint(name, callback, src=ENDPOINT_ADDR_ANY, dest=ENDPOINT_ADDR_ANY)
Construct a new RPMsg Endpoint. An endpoint is a bidirectional communication
channel between two cores.
Arguments are:
- *name* is the name of the endpoint.
- *callback* is a function that is called when the endpoint receives data with the
source address of the remote point, and the data as bytes passed by reference.
- *src* is the endpoint source address. If none is provided one will be assigned
to the endpoint by the library.
- *dest* is the endpoint destination address. If the endpoint is created from the
new_service_callback, this must be provided and it must match the remote endpoint's
source address. If the endpoint is registered locally, before the announcement, the
destination address will be assigned by the library when the endpoint is bound.
.. method:: Endpoint.deinit()
Destroy the endpoint and release all of its resources.
.. method:: Endpoint.is_ready()
Returns True if the endpoint is ready to send (i.e., has both a source and destination addresses)
.. method:: Endpoint.send(src=-1, dest=-1, timeout=-1)
Send a message to the remote processor over this endpoint.
Arguments are:
- *src* is the source endpoint address of the message. If none is provided, the
source address the endpoint is bound to is used.
- *dest* is the destination endpoint address of the message. If none is provided,
the destination address the endpoint is bound to is used.
- *timeout* specifies the time in milliseconds to wait for a free buffer. By default
the function is blocking.
RemoteProc class
----------------
.. class:: RemoteProc(entry)
The RemoteProc object provides processor Life Cycle Management (LCM) support, such as
loading firmware, starting and stopping a remote core.
The *entry* argument can be a path to firmware image, in which case the firmware is
loaded from file to its target memory, or an entry point address, in which case the
firmware must be loaded already at the given address.
.. method:: RemoteProc.start()
Starts the remote processor.
.. method:: RemoteProc.stop()
Stops the remote processor. The exact behavior is platform-dependent. On the STM32H7 for
example it's not possible to stop and then restart the Cortex-M4 core, so a complete
system reset is performed on a call to this function.
.. method:: RemoteProc.shutdown()
Shutdown stops the remote processor and releases all of its resources. The exact behavior
is platform-dependent, however typically it disables power and clocks to the remote core.
This function is also used as the finaliser (i.e., called when ``RemoteProc`` object is
collected). Note that on the STM32H7, it's not possible to stop and then restart the
Cortex-M4 core, so a complete system reset is performed on a call to this function.

Wyświetl plik

@ -136,192 +136,30 @@ Terminal redirection and duplication
Filesystem mounting
-------------------
Some ports provide a Virtual Filesystem (VFS) and the ability to mount multiple
"real" filesystems within this VFS. Filesystem objects can be mounted at either
the root of the VFS, or at a subdirectory that lives in the root. This allows
dynamic and flexible configuration of the filesystem that is seen by Python
programs. Ports that have this functionality provide the :func:`mount` and
:func:`umount` functions, and possibly various filesystem implementations
represented by VFS classes.
The following functions and classes have been moved to the :mod:`vfs` module.
They are provided in this module only for backwards compatibility and will be
removed in version 2 of MicroPython.
.. function:: mount(fsobj, mount_point, *, readonly)
Mount the filesystem object *fsobj* at the location in the VFS given by the
*mount_point* string. *fsobj* can be a a VFS object that has a ``mount()``
method, or a block device. If it's a block device then the filesystem type
is automatically detected (an exception is raised if no filesystem was
recognised). *mount_point* may be ``'/'`` to mount *fsobj* at the root,
or ``'/<name>'`` to mount it at a subdirectory under the root.
If *readonly* is ``True`` then the filesystem is mounted read-only.
During the mount process the method ``mount()`` is called on the filesystem
object.
Will raise ``OSError(EPERM)`` if *mount_point* is already mounted.
See `vfs.mount`.
.. function:: umount(mount_point)
Unmount a filesystem. *mount_point* can be a string naming the mount location,
or a previously-mounted filesystem object. During the unmount process the
method ``umount()`` is called on the filesystem object.
Will raise ``OSError(EINVAL)`` if *mount_point* is not found.
See `vfs.umount`.
.. class:: VfsFat(block_dev)
Create a filesystem object that uses the FAT filesystem format. Storage of
the FAT filesystem is provided by *block_dev*.
Objects created by this constructor can be mounted using :func:`mount`.
.. staticmethod:: mkfs(block_dev)
Build a FAT filesystem on *block_dev*.
See `vfs.VfsFat`.
.. class:: VfsLfs1(block_dev, readsize=32, progsize=32, lookahead=32)
Create a filesystem object that uses the `littlefs v1 filesystem format`_.
Storage of the littlefs filesystem is provided by *block_dev*, which must
support the :ref:`extended interface <block-device-interface>`.
Objects created by this constructor can be mounted using :func:`mount`.
See :ref:`filesystem` for more information.
.. staticmethod:: mkfs(block_dev, readsize=32, progsize=32, lookahead=32)
Build a Lfs1 filesystem on *block_dev*.
.. note:: There are reports of littlefs v1 failing in certain situations,
for details see `littlefs issue 347`_.
See `vfs.VfsLfs1`.
.. class:: VfsLfs2(block_dev, readsize=32, progsize=32, lookahead=32, mtime=True)
Create a filesystem object that uses the `littlefs v2 filesystem format`_.
Storage of the littlefs filesystem is provided by *block_dev*, which must
support the :ref:`extended interface <block-device-interface>`.
Objects created by this constructor can be mounted using :func:`mount`.
See `vfs.VfsLfs2`.
The *mtime* argument enables modification timestamps for files, stored using
littlefs attributes. This option can be disabled or enabled differently each
mount time and timestamps will only be added or updated if *mtime* is enabled,
otherwise the timestamps will remain untouched. Littlefs v2 filesystems without
timestamps will work without reformatting and timestamps will be added
transparently to existing files once they are opened for writing. When *mtime*
is enabled `os.stat` on files without timestamps will return 0 for the timestamp.
.. class:: VfsPosix(root=None)
See :ref:`filesystem` for more information.
.. staticmethod:: mkfs(block_dev, readsize=32, progsize=32, lookahead=32)
Build a Lfs2 filesystem on *block_dev*.
.. note:: There are reports of littlefs v2 failing in certain situations,
for details see `littlefs issue 295`_.
.. _littlefs v1 filesystem format: https://github.com/ARMmbed/littlefs/tree/v1
.. _littlefs v2 filesystem format: https://github.com/ARMmbed/littlefs
.. _littlefs issue 295: https://github.com/ARMmbed/littlefs/issues/295
.. _littlefs issue 347: https://github.com/ARMmbed/littlefs/issues/347
Block devices
-------------
A block device is an object which implements the block protocol. This enables a
device to support MicroPython filesystems. The physical hardware is represented
by a user defined class. The :class:`AbstractBlockDev` class is a template for
the design of such a class: MicroPython does not actually provide that class,
but an actual block device class must implement the methods described below.
A concrete implementation of this class will usually allow access to the
memory-like functionality of a piece of hardware (like flash memory). A block
device can be formatted to any supported filesystem and mounted using ``os``
methods.
See :ref:`filesystem` for example implementations of block devices using the
two variants of the block protocol described below.
.. _block-device-interface:
Simple and extended interface
.............................
There are two compatible signatures for the ``readblocks`` and ``writeblocks``
methods (see below), in order to support a variety of use cases. A given block
device may implement one form or the other, or both at the same time. The second
form (with the offset parameter) is referred to as the "extended interface".
Some filesystems (such as littlefs) that require more control over write
operations, for example writing to sub-block regions without erasing, may require
that the block device supports the extended interface.
.. class:: AbstractBlockDev(...)
Construct a block device object. The parameters to the constructor are
dependent on the specific block device.
.. method:: readblocks(block_num, buf)
readblocks(block_num, buf, offset)
The first form reads aligned, multiples of blocks.
Starting at the block given by the index *block_num*, read blocks from
the device into *buf* (an array of bytes).
The number of blocks to read is given by the length of *buf*,
which will be a multiple of the block size.
The second form allows reading at arbitrary locations within a block,
and arbitrary lengths.
Starting at block index *block_num*, and byte offset within that block
of *offset*, read bytes from the device into *buf* (an array of bytes).
The number of bytes to read is given by the length of *buf*.
.. method:: writeblocks(block_num, buf)
writeblocks(block_num, buf, offset)
The first form writes aligned, multiples of blocks, and requires that the
blocks that are written to be first erased (if necessary) by this method.
Starting at the block given by the index *block_num*, write blocks from
*buf* (an array of bytes) to the device.
The number of blocks to write is given by the length of *buf*,
which will be a multiple of the block size.
The second form allows writing at arbitrary locations within a block,
and arbitrary lengths. Only the bytes being written should be changed,
and the caller of this method must ensure that the relevant blocks are
erased via a prior ``ioctl`` call.
Starting at block index *block_num*, and byte offset within that block
of *offset*, write bytes from *buf* (an array of bytes) to the device.
The number of bytes to write is given by the length of *buf*.
Note that implementations must never implicitly erase blocks if the offset
argument is specified, even if it is zero.
.. method:: ioctl(op, arg)
Control the block device and query its parameters. The operation to
perform is given by *op* which is one of the following integers:
- 1 -- initialise the device (*arg* is unused)
- 2 -- shutdown the device (*arg* is unused)
- 3 -- sync the device (*arg* is unused)
- 4 -- get a count of the number of blocks, should return an integer
(*arg* is unused)
- 5 -- get the number of bytes in a block, should return an integer,
or ``None`` in which case the default value of 512 is used
(*arg* is unused)
- 6 -- erase a block, *arg* is the block number to erase
As a minimum ``ioctl(4, ...)`` must be intercepted; for littlefs
``ioctl(6, ...)`` must also be intercepted. The need for others is
hardware dependent.
Prior to any call to ``writeblocks(block, ...)`` littlefs issues
``ioctl(6, block)``. This enables a device driver to erase the block
prior to a write if the hardware requires it. Alternatively a driver
might intercept ``ioctl(6, block)`` and return 0 (success). In this case
the driver assumes responsibility for detecting the need for erasure.
Unless otherwise stated ``ioctl(op, arg)`` can return ``None``.
Consequently an implementation can ignore unused values of ``op``. Where
``op`` is intercepted, the return value for operations 4 and 5 are as
detailed above. Other operations should return 0 on success and non-zero
for failure, with the value returned being an ``OSError`` errno code.
See `vfs.VfsPosix`.

Wyświetl plik

@ -43,7 +43,7 @@ Methods
These methods implement the simple and :ref:`extended
<block-device-interface>` block protocol defined by
:class:`os.AbstractBlockDev`.
:class:`vfs.AbstractBlockDev`.
Hardware Note
-------------

Wyświetl plik

@ -213,11 +213,11 @@ Miscellaneous functions
.. function:: mount(device, mountpoint, *, readonly=False, mkfs=False)
.. note:: This function is deprecated. Mounting and unmounting devices should
be performed by :meth:`os.mount` and :meth:`os.umount` instead.
be performed by :meth:`vfs.mount` and :meth:`vfs.umount` instead.
Mount a block device and make it available as part of the filesystem.
``device`` must be an object that provides the block protocol. (The
following is also deprecated. See :class:`os.AbstractBlockDev` for the
following is also deprecated. See :class:`vfs.AbstractBlockDev` for the
correct way to create a block device.)
- ``readblocks(self, blocknum, buf)``

Wyświetl plik

@ -0,0 +1,293 @@
.. currentmodule:: rp2
.. _rp2.DMA:
class DMA -- access to the RP2040's DMA controller
==================================================
The :class:`DMA` class offers access to the RP2040's Direct Memory Access (DMA)
controller, providing the ability move data between memory blocks and/or IO registers. The DMA
controller has its own, separate read and write bus master connections onto the bus fabric and
each DMA channel can independently read data from one address and write it back to another
address, optionally incrementing one or both pointers, allowing it to perform transfers on behalf
of the processor while the processor carries out other tasks or enters a low power state. The
RP2040's DMA controller has 12 independent DMA channels that can run concurrently. For full
details of the RP2040's DMA system see section 2.5 of the `RP2040 Datasheet
<https://datasheets.raspberrypi.org/rp2040/rp2040-datasheet.pdf>`_.
Examples
--------
The simplest use of the DMA controller is to move data from one block of memory to another.
This can be accomplished with the following code::
a = bytearray(32*1024)
b = bytearray(32*1024)
d = rp2.DMA()
c = d.pack_ctrl() # Just use the default control value.
# The count is in 'transfers', which defaults to four-byte words, so divide length by 4
d.config(read=a, write=b, count=len(a)//4, ctrl=c, trigger=True)
# Wait for completion
while d.active():
pass
Note that while this example sits in an idle loop while it waits for the transfer to complete,
the program could just as well do some useful work in this time instead.
Another, perhaps more common use of the DMA controller is to transfer between memory and an IO
peripheral. In this situation the address of the IO register does not change for each transfer but
the memory address needs to be incremented. It is also necessary to control the pace of the
transfer so as to not write data before it can be accepted by a peripheral or read it before the
data is ready, and this can be controlled with the ``treq_sel`` field of the DMA channel's control
register. The various fields of the control register for each DMA channel can be packed
using the :meth:`DMA.pack_ctrl()` method and unpacked using the :meth:`DMA.unpack_ctrl()`
static method. Code to transfer data from a byte array to the TX FIFO of a PIO state machine,
one byte at a time, looks like this::
# pio_num is index of the PIO block being used, sm_num is the state machine in that block.
# my_state_machine is an rp2.PIO() instance.
DATA_REQUEST_INDEX = (pio_num << 3) + sm_num
src_data = bytearray(1024)
d = rp2.DMA()
# Transfer bytes, rather than words, don't increment the write address and pace the transfer.
c = d.pack_ctrl(size=0, inc_write=False, treq_sel=DATA_REQUEST_INDEX)
d.config(
read=src_data,
write=my_state_machine,
count=len(src_data),
ctrl=c,
trigger=True
)
Note that in this example the value given for the write address is just the PIO state machine to
which we are sending the data. This works because PIO state machines present the buffer protocol,
allowing direct access to their data FIFO registers.
Constructor
-----------
.. class:: DMA()
Claim one of the DMA controller channels for exclusive use.
Methods
-------
.. method:: DMA.config(read=None, write=None, count=None, ctrl=None, trigger=False)
Configure the DMA registers for the channel and optionally start the transfer.
Parameters are:
- *read*: The address from which the DMA controller will start reading data or
an object that will provide data to be read. It can be an integer or any
object that supports the buffer protocol.
- *write*: The address to which the DMA controller will start writing or an
object into which data will be written. It can be an integer or any object
that supports the buffer protocol.
- *count*: The number of bus transfers that will execute before this channel
stops. Note that this is the number of transfers, not the number of bytes.
If the transfers are 2 or 4 bytes wide then the total amount of data moved
(and thus the size of required buffer) needs to be multiplied accordingly.
- *ctrl*: The value for the DMA control register. This is an integer value
that is typically packed using the :meth:`DMA.pack_ctrl()`.
- *trigger*: Optionally commence the transfer immediately.
.. method:: DMA.irq(handler=None, hard=False)
Returns the IRQ object for this DMA channel and optionally configures it.
.. method:: DMA.close()
Release the claim on the underlying DMA channel and free the interrupt
handler. The :class:`DMA` object can not be used after this operation.
.. method:: DMA.pack_ctrl(default=None, **kwargs)
Pack the values provided in the keyword arguments into the named fields of a new control
register value. Any field that is not provided will be set to a default value. The
default will either be taken from the provided ``default`` value, or if that is not
given, a default suitable for the current channel; setting this to the current value
of the `DMA.ctrl` attribute provides an easy way to override a subset of the fields.
The keys for the keyword arguments can be any key returned by the :meth:`DMA.unpack_ctrl()`
method. The writable values are:
- *enable*: ``bool`` Set to enable the channel (default: ``True``).
- *high_pri*: ``bool`` Make this channel's bus traffic high priority (default: ``False``).
- *size*: ``int`` Transfer size: 0=byte, 1=half word, 2=word (default: 2).
- *inc_read*: ``bool`` Increment the read address after each transfer (default: ``True``).
- *inc_write*: ``bool`` Increment the write address after each transfer (default: ``True``).
- *ring_size*: ``int`` If non-zero, only the bottom ``ring_size`` bits of one
address register will change when an address is incremented, causing the
address to wrap at the next ``1 << ring_size`` byte boundary. Which
address is wrapped is controlled by the ``ring_sel`` flag. A zero value
disables address wrapping.
- *ring_sel*: ``bool`` Set to ``False`` to have the ``ring_size`` apply to the read address
or ``True`` to apply to the write address.
- *chain_to*: ``int`` The channel number for a channel to trigger after this transfer
completes. Setting this value to this DMA object's own channel number
disables chaining (this is the default).
- *treq_sel*: ``int`` Select a Transfer Request signal. See section 2.5.3 in the RP2040
datasheet for details.
- *irq_quiet*: ``bool`` Do not generate interrupt at the end of each transfer. Interrupts
will instead be generated when a zero value is written to the trigger
register, which will halt a sequence of chained transfers (default:
``True``).
- *bswap*: ``bool`` If set to true, bytes in words or half-words will be reversed before
writing (default: ``True``).
- *sniff_en*: ``bool`` Set to ``True`` to allow data to be accessed by the chips sniff
hardware (default: ``False``).
- *write_err*: ``bool`` Setting this to ``True`` will clear a previously reported write
error.
- *read_err*: ``bool`` Setting this to ``True`` will clear a previously reported read
error.
See the description of the ``CH0_CTRL_TRIG`` register in section 2.5.7 of the RP2040
datasheet for details of all of these fields.
.. method:: DMA.unpack_ctrl(value)
Unpack a value for a DMA channel control register into a dictionary with key/value pairs
for each of the fields in the control register. *value* is the ``ctrl`` register value
to unpack.
This method will return values for all the keys that can be passed to ``DMA.pack_ctrl``.
In addition, it will also return the read-only flags in the control register: ``busy``,
which goes high when a transfer starts and low when it ends, and ``ahb_err``, which is
the logical OR of the ``read_err`` and ``write_err`` flags. These values will be ignored
when packing, so that the dictionary created by unpacking a control register can be used
directly as the keyword arguments for packing.
.. method:: DMA.active([value])
Gets or sets whether the DMA channel is currently running.
>>> sm.active()
0
>>> sm.active(1)
>>> while sm.active():
... pass
Attributes
----------
.. attribute:: DMA.read
This attribute reflects the address from which the next bus transfer
will read. It may be written with either an integer or an object
that supports the buffer protocol and doing so has immediate effect.
.. attribute:: DMA.write
This attribute reflects the address to which the next bus transfer
will write. It may be written with either an integer or an object
that supports the buffer protocol and doing so has immediate effect.
.. attribute:: DMA.count
Reading this attribute will return the number of remaining bus
transfers in the *current* transfer sequence. Writing this attribute
sets the total number of transfers to be the *next* transfer sequence.
.. attribute:: DMA.ctrl
This attribute reflects DMA channel control register. It is typically written
with an integer packed using the :meth:`DMA.pack_ctrl()` method. The returned
register value can be unpacked using the :meth:`DMA.unpack_ctrl()` method.
.. attribute:: DMA.channel
The channel number of the DMA channel. This can be passed in the ``chain_to``
argument of `DMA.pack_ctrl()` on another channel to allow DMA chaining.
.. attribute:: DMA.registers
This attribute is an array-like object that allows direct access to
the DMA channel's registers. The index is by word, rather than by byte,
so the register indices are the register address offsets divided by 4.
See the RP2040 data sheet for register details.
Chaining and trigger register access
------------------------------------
The DMA controller in the RP2040 offers a couple advanced features to allow one DMA channel
to initiate a transfer on another channel. One is the use of the ``chain_to`` value in the
control register and the other is writing to one of the DMA channel's registers that has a
trigger effect. When coupled with the ability to have one DMA channel write directly to the
`DMA.registers` of another channel, this allows for complex transactions to be performed
without any CPU intervention.
Below is an example of using both chaining and register
triggering to implement gathering of multiple blocks of data into a single destination. Full
details of these features can be found in section 2.5 of the RP2040 data sheet and the code
below is a Pythonic version of the example in sub-section 2.5.6.2.
.. code-block:: python
from rp2 import DMA
from uctypes import addressof
from array import array
def gather_strings(string_list, buf):
# We use two DMA channels. The first sends lengths and source addresses from the gather
# list to the registers of the second. The second copies the data itself.
gather_dma = DMA()
buffer_dma = DMA()
# Pack up length/address pairs to be sent to the registers.
gather_list = array("I")
for s in string_list:
gather_list.append(len(s))
gather_list.append(addressof(s))
gather_list.append(0)
gather_list.append(0)
# When writing to the registers of the second DMA channel, we need to wrap the
# write address on an 8-byte (1<<3 bytes) boundary. We write to the ``TRANS_COUNT``
# and ``READ_ADD_TRIG`` registers in the last register alias (registers 14 and 15).
gather_ctrl = gather_dma.pack_ctrl(ring_size=3, ring_sel=True)
gather_dma.config(
read=gather_list, write=buffer_dma.registers[14:16],
count=2, ctrl=gather_ctrl
)
# When copying the data, the transfer size is single bytes, and when completed we need
# to chain back to the start another gather DMA transaction.
buffer_ctrl = buffer_dma.pack_ctrl(size=0, chain_to=gather_dma.channel)
# The read and count values will be set by the other DMA channel.
buffer_dma.config(write=buf, ctrl=buffer_ctrl)
# Set the transfer in motion.
gather_dma.active(1)
# Wait until all the register values have been sent
end_address = addressof(gather_list) + 4 * len(gather_list)
while gather_dma.read != end_address:
pass
input = ["This is ", "a ", "test", " of the scatter", " gather", " process"]
output = bytearray(64)
print(output)
gather_strings(input, output)
print(output)
This example idles while waiting for the transfer to complete; alternatively it could
set an interrupt handler and return immediately.

Wyświetl plik

@ -32,5 +32,5 @@ Methods
These methods implement the simple and extended
:ref:`block protocol <block-device-interface>` defined by
:class:`os.AbstractBlockDev`.
:class:`vfs.AbstractBlockDev`.

Wyświetl plik

@ -32,7 +32,7 @@ Methods
The program is added to the instruction memory of this PIO instance. If the
instruction memory already contains this program, then its offset is
re-used so as to save on instruction memory.
reused so as to save on instruction memory.
- *freq* is the frequency in Hz to run the state machine at. Defaults to
the system clock frequency.
@ -140,3 +140,10 @@ Methods
Optionally configure it.
Buffer protocol
---------------
The StateMachine class supports the `buffer protocol`, allowing direct access to the transmit
and receive FIFOs for each state machine. This is primarily in order to allow StateMachine
objects to be passed directly as the read or write parameters when configuring a `rp2.DMA()`
channel.

Wyświetl plik

@ -241,6 +241,7 @@ Classes
.. toctree::
:maxdepth: 1
rp2.DMA.rst
rp2.Flash.rst
rp2.PIO.rst
rp2.StateMachine.rst

Wyświetl plik

@ -13,7 +13,7 @@ facilities for network sockets, both client-side and server-side.
Functions
---------
.. function:: ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, cadata=None, server_hostname=None, do_handshake=True)
.. function:: ssl.wrap_socket(sock, server_side=False, key=None, cert=None, cert_reqs=CERT_NONE, cadata=None, server_hostname=None, do_handshake=True)
Wrap the given *sock* and return a new wrapped-socket object. The implementation
of this function is to first create an `SSLContext` and then call the `SSLContext.wrap_socket`

Wyświetl plik

@ -45,6 +45,8 @@ The following data types are supported:
+--------+--------------------+-------------------+---------------+
| Q | unsigned long long | integer (`1<fn>`) | 8 |
+--------+--------------------+-------------------+---------------+
| e | n/a (half-float) | float (`2<fn>`) | 2 |
+--------+--------------------+-------------------+---------------+
| f | float | float (`2<fn>`) | 4 |
+--------+--------------------+-------------------+---------------+
| d | double | float (`2<fn>`) | 8 |

Wyświetl plik

@ -69,7 +69,7 @@ Constants
MicroPython, it has following attributes:
* *name* - string "micropython"
* *version* - tuple (major, minor, micro), e.g. (1, 7, 0)
* *version* - tuple (major, minor, micro, releaselevel), e.g. (1, 22, 0, '')
* *_machine* - string describing the underlying machine
* *_mpy* - supported mpy file-format version (optional attribute)
@ -77,6 +77,9 @@ Constants
Python implementations (note that it still may not exist in the very
minimal ports).
Starting with version 1.22.0-preview, the fourth node *releaselevel* in
*implementation.version* is either an empty string or ``"preview"``.
.. admonition:: Difference to CPython
:class: attention

Wyświetl plik

@ -0,0 +1,208 @@
:mod:`vfs` -- virtual filesystem control
========================================
.. module:: vfs
:synopsis: virtual filesystem control
The ``vfs`` module contains functions for creating filesystem objects and
mounting/unmounting them in the Virtual Filesystem.
Filesystem mounting
-------------------
Some ports provide a Virtual Filesystem (VFS) and the ability to mount multiple
"real" filesystems within this VFS. Filesystem objects can be mounted at either
the root of the VFS, or at a subdirectory that lives in the root. This allows
dynamic and flexible configuration of the filesystem that is seen by Python
programs. Ports that have this functionality provide the :func:`mount` and
:func:`umount` functions, and possibly various filesystem implementations
represented by VFS classes.
.. function:: mount(fsobj, mount_point, *, readonly)
Mount the filesystem object *fsobj* at the location in the VFS given by the
*mount_point* string. *fsobj* can be a a VFS object that has a ``mount()``
method, or a block device. If it's a block device then the filesystem type
is automatically detected (an exception is raised if no filesystem was
recognised). *mount_point* may be ``'/'`` to mount *fsobj* at the root,
or ``'/<name>'`` to mount it at a subdirectory under the root.
If *readonly* is ``True`` then the filesystem is mounted read-only.
During the mount process the method ``mount()`` is called on the filesystem
object.
Will raise ``OSError(EPERM)`` if *mount_point* is already mounted.
.. function:: umount(mount_point)
Unmount a filesystem. *mount_point* can be a string naming the mount location,
or a previously-mounted filesystem object. During the unmount process the
method ``umount()`` is called on the filesystem object.
Will raise ``OSError(EINVAL)`` if *mount_point* is not found.
.. class:: VfsFat(block_dev)
Create a filesystem object that uses the FAT filesystem format. Storage of
the FAT filesystem is provided by *block_dev*.
Objects created by this constructor can be mounted using :func:`mount`.
.. staticmethod:: mkfs(block_dev)
Build a FAT filesystem on *block_dev*.
.. class:: VfsLfs1(block_dev, readsize=32, progsize=32, lookahead=32)
Create a filesystem object that uses the `littlefs v1 filesystem format`_.
Storage of the littlefs filesystem is provided by *block_dev*, which must
support the :ref:`extended interface <block-device-interface>`.
Objects created by this constructor can be mounted using :func:`mount`.
See :ref:`filesystem` for more information.
.. staticmethod:: mkfs(block_dev, readsize=32, progsize=32, lookahead=32)
Build a Lfs1 filesystem on *block_dev*.
.. note:: There are reports of littlefs v1 failing in certain situations,
for details see `littlefs issue 347`_.
.. class:: VfsLfs2(block_dev, readsize=32, progsize=32, lookahead=32, mtime=True)
Create a filesystem object that uses the `littlefs v2 filesystem format`_.
Storage of the littlefs filesystem is provided by *block_dev*, which must
support the :ref:`extended interface <block-device-interface>`.
Objects created by this constructor can be mounted using :func:`mount`.
The *mtime* argument enables modification timestamps for files, stored using
littlefs attributes. This option can be disabled or enabled differently each
mount time and timestamps will only be added or updated if *mtime* is enabled,
otherwise the timestamps will remain untouched. Littlefs v2 filesystems without
timestamps will work without reformatting and timestamps will be added
transparently to existing files once they are opened for writing. When *mtime*
is enabled `os.stat` on files without timestamps will return 0 for the timestamp.
See :ref:`filesystem` for more information.
.. staticmethod:: mkfs(block_dev, readsize=32, progsize=32, lookahead=32)
Build a Lfs2 filesystem on *block_dev*.
.. note:: There are reports of littlefs v2 failing in certain situations,
for details see `littlefs issue 295`_.
.. class:: VfsPosix(root=None)
Create a filesystem object that accesses the host POSIX filesystem.
If *root* is specified then it should be a path in the host filesystem to use
as the root of the ``VfsPosix`` object. Otherwise the current directory of
the host filesystem is used.
.. _littlefs v1 filesystem format: https://github.com/ARMmbed/littlefs/tree/v1
.. _littlefs v2 filesystem format: https://github.com/ARMmbed/littlefs
.. _littlefs issue 295: https://github.com/ARMmbed/littlefs/issues/295
.. _littlefs issue 347: https://github.com/ARMmbed/littlefs/issues/347
Block devices
-------------
A block device is an object which implements the block protocol. This enables a
device to support MicroPython filesystems. The physical hardware is represented
by a user defined class. The :class:`AbstractBlockDev` class is a template for
the design of such a class: MicroPython does not actually provide that class,
but an actual block device class must implement the methods described below.
A concrete implementation of this class will usually allow access to the
memory-like functionality of a piece of hardware (like flash memory). A block
device can be formatted to any supported filesystem and mounted using ``os``
methods.
See :ref:`filesystem` for example implementations of block devices using the
two variants of the block protocol described below.
.. _block-device-interface:
Simple and extended interface
.............................
There are two compatible signatures for the ``readblocks`` and ``writeblocks``
methods (see below), in order to support a variety of use cases. A given block
device may implement one form or the other, or both at the same time. The second
form (with the offset parameter) is referred to as the "extended interface".
Some filesystems (such as littlefs) that require more control over write
operations, for example writing to sub-block regions without erasing, may require
that the block device supports the extended interface.
.. class:: AbstractBlockDev(...)
Construct a block device object. The parameters to the constructor are
dependent on the specific block device.
.. method:: readblocks(block_num, buf)
readblocks(block_num, buf, offset)
The first form reads aligned, multiples of blocks.
Starting at the block given by the index *block_num*, read blocks from
the device into *buf* (an array of bytes).
The number of blocks to read is given by the length of *buf*,
which will be a multiple of the block size.
The second form allows reading at arbitrary locations within a block,
and arbitrary lengths.
Starting at block index *block_num*, and byte offset within that block
of *offset*, read bytes from the device into *buf* (an array of bytes).
The number of bytes to read is given by the length of *buf*.
.. method:: writeblocks(block_num, buf)
writeblocks(block_num, buf, offset)
The first form writes aligned, multiples of blocks, and requires that the
blocks that are written to be first erased (if necessary) by this method.
Starting at the block given by the index *block_num*, write blocks from
*buf* (an array of bytes) to the device.
The number of blocks to write is given by the length of *buf*,
which will be a multiple of the block size.
The second form allows writing at arbitrary locations within a block,
and arbitrary lengths. Only the bytes being written should be changed,
and the caller of this method must ensure that the relevant blocks are
erased via a prior ``ioctl`` call.
Starting at block index *block_num*, and byte offset within that block
of *offset*, write bytes from *buf* (an array of bytes) to the device.
The number of bytes to write is given by the length of *buf*.
Note that implementations must never implicitly erase blocks if the offset
argument is specified, even if it is zero.
.. method:: ioctl(op, arg)
Control the block device and query its parameters. The operation to
perform is given by *op* which is one of the following integers:
- 1 -- initialise the device (*arg* is unused)
- 2 -- shutdown the device (*arg* is unused)
- 3 -- sync the device (*arg* is unused)
- 4 -- get a count of the number of blocks, should return an integer
(*arg* is unused)
- 5 -- get the number of bytes in a block, should return an integer,
or ``None`` in which case the default value of 512 is used
(*arg* is unused)
- 6 -- erase a block, *arg* is the block number to erase
As a minimum ``ioctl(4, ...)`` must be intercepted; for littlefs
``ioctl(6, ...)`` must also be intercepted. The need for others is
hardware dependent.
Prior to any call to ``writeblocks(block, ...)`` littlefs issues
``ioctl(6, block)``. This enables a device driver to erase the block
prior to a write if the hardware requires it. Alternatively a driver
might intercept ``ioctl(6, block)`` and return 0 (success). In this case
the driver assumes responsibility for detecting the need for erasure.
Unless otherwise stated ``ioctl(op, arg)`` can return ``None``.
Consequently an implementation can ignore unused values of ``op``. Where
``op`` is intercepted, the return value for operations 4 and 5 are as
detailed above. Other operations should return 0 on success and non-zero
for failure, with the value returned being an ``OSError`` errno code.

Wyświetl plik

@ -34,5 +34,5 @@ Methods
These methods implement the simple and extended
:ref:`block protocol <block-device-interface>` defined by
:class:`os.AbstractBlockDev`.
:class:`vfs.AbstractBlockDev`.

Wyświetl plik

@ -37,4 +37,4 @@ Methods
These methods implement the simple and extended
:ref:`block protocol <block-device-interface>` defined by
:class:`os.AbstractBlockDev`.
:class:`vfs.AbstractBlockDev`.

Wyświetl plik

@ -319,7 +319,7 @@ MIXMXRT1050-EVKB D10/-/D11/D12/D13 (*) - -
MIXMXRT1060-EVK D10/-/D11/D12/D13 (*) - -
MIXMXRT1064-EVK D10/-/D11/D12/D13 (*) - -
MIXMXRT1170-EVK D10/-/D11/D12/D13 D28/-/D25/D24/D26 -/-/D14/D15/D24
Adafruit Metro M7 -/-/MOSI/MISO/SCK - -
Adafruit Metro M7 -/-/MOSI/MISO/SCK - -
Olimex RT1010Py - CS0/-/SDO/SDI/SCK SDCARD with CS1
Seeed ARCH MIX J4_12/-/J4_14/J4_13/J4_15 J3_09/J3_05/J3_08_J3_11
================= ========================= ======================= ===============
@ -375,7 +375,7 @@ Teensy 4.0 2 33 4 3 2 - - 5
Teensy 4.1 1 23 26 27 7 21 20 8
Teensy 4.1 2 33 4 3 2 - - 5
Seeed Arch MIX 1 J4_09 J4_14 J4_15 J14_13 J4_11 J4_10 J4_10
Adafruit Metro M7 1 D8 D10 D9 D12 D14 D15 D13
Adafruit Metro M7 1 D8 D10 D9 D12 D14 D15 D13
Olimex RT1010Py 1 D8 D6 D7 D4 D1 D2 D3
Olimex RT1010Py 3 - D10 D9 D11 - - -
MIMXRT_DEV 1 "MCK" "SCK_TX" "WS_TX" "SD_TX" "SCK_RX" "WS_RX" "SD_RX"

Wyświetl plik

@ -309,7 +309,7 @@ rates (up to 30Mhz). Hardware SPI is accessed via the
For the assignment of Pins to SPI signals, refer to
:ref:`Hardware SPI pinout <mimxrt_spi_pinout>`.
The keyword option cs=n can be used to enable the cs pin 0 or 1 for an automatic cs signal. The
default is cs=-1. Using cs=-1 the automatic cs signal is not created.
default is cs=-1. Using cs=-1 the automatic cs signal is not created.
In that case, cs has to be set by the script. Clearing that assignment requires a power cycle.
Notes:
@ -443,27 +443,27 @@ SD card
See :ref:`machine.SDCard <machine.SDCard>`::
import machine, os
import machine, os, vfs
sd = machine.SDCard()
fs = os.VfsFat(sd)
os.mount(fs, "/sd") # mount
fs = vfs.VfsFat(sd)
vfs.mount(fs, "/sd") # mount
os.listdir('/sd') # list directory contents
os.umount('/sd') # eject
vfs.umount('/sd') # eject
Note: The i.mx-rt 1011 and 1015 based boards do not support the ``machine.SDCard``
class. For these, the SPI based driver ``sdcard.py`` from the MicroPython drivers
can be used. When using it, you have to overdrive the CS pin of the SPI hardware
module. Example::
import os, sdcard, machine
import vfs, sdcard, machine
cs_pin = "D10"
spi = machine.SPI(0) # SPI0 with cs at Pin "D10" used for SDCARD
cs = machine.Pin(cs_pin, machine.Pin.OUT, value=1)
sd = sdcard.SDCard(spi, cs)
vfs = os.VfsFat(sd)
os.mount(vfs, "/sdcard")
fs = vfs.VfsFat(sd)
vfs.mount(fs, "/sdcard")
OneWire driver
--------------

Wyświetl plik

@ -21,7 +21,7 @@ If needed, you can prevent the use of the SD card by creating an empty file
called ``/flash/SKIPSD``. If this file exists when the pyboard boots
up then the SD card will be skipped and the pyboard will always boot from the
internal filesystem (in this case the SD card won't be mounted but you can still
mount and use it later in your program using ``os.mount``).
mount and use it later in your program using ``vfs.mount``).
(Note that on older versions of the board, ``/flash`` is called ``0:/`` and ``/sd``
is called ``1:/``).

Wyświetl plik

@ -211,7 +211,7 @@ two loops:
spi.readinto(buf)
# process data in buf
The first creates a buffer on each pass whereas the second re-uses a pre-allocated
The first creates a buffer on each pass whereas the second reuses a pre-allocated
buffer; this is both faster and more efficient in terms of memory fragmentation.
**Bytes are smaller than ints**

Wyświetl plik

@ -40,7 +40,7 @@ Block devices
-------------
A block device is an instance of a class that implements the
:class:`os.AbstractBlockDev` protocol.
:class:`vfs.AbstractBlockDev` protocol.
Built-in block devices
~~~~~~~~~~~~~~~~~~~~~~
@ -108,16 +108,16 @@ RAM using a ``bytearray``::
It can be used as follows::
import os
import vfs
bdev = RAMBlockDev(512, 50)
os.VfsFat.mkfs(bdev)
os.mount(bdev, '/ramdisk')
vfs.VfsFat.mkfs(bdev)
vfs.mount(bdev, '/ramdisk')
An example of a block device that supports both the simple and extended
interface (i.e. both signatures and behaviours of the
:meth:`os.AbstractBlockDev.readblocks` and
:meth:`os.AbstractBlockDev.writeblocks` methods) is::
:meth:`vfs.AbstractBlockDev.readblocks` and
:meth:`vfs.AbstractBlockDev.writeblocks` methods) is::
class RAMBlockDev:
def __init__(self, block_size, num_blocks):
@ -148,13 +148,13 @@ interface (i.e. both signatures and behaviours of the
return 0
As it supports the extended interface, it can be used with :class:`littlefs
<os.VfsLfs2>`::
<vfs.VfsLfs2>`::
import os
import vfs
bdev = RAMBlockDev(512, 50)
os.VfsLfs2.mkfs(bdev)
os.mount(bdev, '/ramdisk')
vfs.VfsLfs2.mkfs(bdev)
vfs.mount(bdev, '/ramdisk')
Once mounted, the filesystem (regardless of its type) can be used as it
normally would be used from Python code, for example::
@ -166,8 +166,8 @@ normally would be used from Python code, for example::
Filesystems
-----------
MicroPython ports can provide implementations of :class:`FAT <os.VfsFat>`,
:class:`littlefs v1 <os.VfsLfs1>` and :class:`littlefs v2 <os.VfsLfs2>`.
MicroPython ports can provide implementations of :class:`FAT <vfs.VfsFat>`,
:class:`littlefs v1 <vfs.VfsLfs1>` and :class:`littlefs v2 <vfs.VfsLfs2>`.
The following table shows which filesystems are included in the firmware by
default for given port/board combinations, however they can be optionally
@ -197,16 +197,16 @@ recommended to use littlefs instead.
To format the entire flash using FAT::
# ESP8266 and ESP32
import os
os.umount('/')
os.VfsFat.mkfs(bdev)
os.mount(bdev, '/')
import vfs
vfs.umount('/')
vfs.VfsFat.mkfs(bdev)
vfs.mount(bdev, '/')
# STM32
import os, pyb
os.umount('/flash')
os.VfsFat.mkfs(pyb.Flash(start=0))
os.mount(pyb.Flash(start=0), '/flash')
import os, vfs, pyb
vfs.umount('/flash')
vfs.VfsFat.mkfs(pyb.Flash(start=0))
vfs.mount(pyb.Flash(start=0), '/flash')
os.chdir('/flash')
Littlefs
@ -222,16 +222,16 @@ resistant to filesystem corruption.
To format the entire flash using littlefs v2::
# ESP8266 and ESP32
import os
os.umount('/')
os.VfsLfs2.mkfs(bdev)
os.mount(bdev, '/')
import vfs
vfs.umount('/')
vfs.VfsLfs2.mkfs(bdev)
vfs.mount(bdev, '/')
# STM32
import os, pyb
os.umount('/flash')
os.VfsLfs2.mkfs(pyb.Flash(start=0))
os.mount(pyb.Flash(start=0), '/flash')
import os, vfs, pyb
vfs.umount('/flash')
vfs.VfsLfs2.mkfs(pyb.Flash(start=0))
vfs.mount(pyb.Flash(start=0), '/flash')
os.chdir('/flash')
A littlefs filesystem can be still be accessed on a PC over USB MSC using the
@ -264,14 +264,14 @@ block devices spanning a subset of the flash device.
For example, to configure the first 256kiB as FAT (and available over USB MSC),
and the remainder as littlefs::
import os, pyb
os.umount('/flash')
import os, vfs, pyb
vfs.umount('/flash')
p1 = pyb.Flash(start=0, len=256*1024)
p2 = pyb.Flash(start=256*1024)
os.VfsFat.mkfs(p1)
os.VfsLfs2.mkfs(p2)
os.mount(p1, '/flash')
os.mount(p2, '/data')
vfs.VfsFat.mkfs(p1)
vfs.VfsLfs2.mkfs(p2)
vfs.mount(p1, '/flash')
vfs.mount(p2, '/data')
os.chdir('/flash')
This might be useful to make your Python files, configuration and other
@ -282,9 +282,9 @@ failure, etc.
The partition at offset ``0`` will be mounted automatically (and the filesystem
type automatically detected), but you can add::
import os, pyb
import vfs, pyb
p2 = pyb.Flash(start=256*1024)
os.mount(p2, '/data')
vfs.mount(p2, '/data')
to ``boot.py`` to mount the data partition.
@ -297,7 +297,7 @@ define an arbitrary partition layout.
At boot, the partition named "vfs" will be mounted at ``/`` by default, but any
additional partitions can be mounted in your ``boot.py`` using::
import esp32, os
import esp32, vfs
p = esp32.Partition.find(esp32.Partition.TYPE_DATA, label='foo')
os.mount(p, '/foo')
vfs.mount(p, '/foo')

Wyświetl plik

@ -95,6 +95,17 @@ Note: The ``opt`` keyword argument can be set on the various functions, this con
the optimisation level used by the cross-compiler.
See :func:`micropython.opt_level`.
.. function:: add_library(library, library_path, prepend=False)
Register the path to an external named *library*.
The path *library_path* will be automatically searched when using `require`.
By default the added library is added to the end of the list of libraries to
search. Pass ``True`` to *prepend* to add it to the start of the list.
Additionally, the added library can be explicitly requested by using
``require("name", library="library")``.
.. function:: package(package_path, files=None, base_path=".", opt=None)
This is equivalent to copying the "package_path" directory to the device
@ -138,11 +149,13 @@ See :func:`micropython.opt_level`.
You can use the variables above, such as ``$(PORT_DIR)`` in ``base_path``.
.. function:: require(name, unix_ffi=False)
.. function:: require(name, library=None)
Require a package by name (and its dependencies) from :term:`micropython-lib`.
Optionally specify unix_ffi=True to use a module from the unix-ffi directory.
Optionally specify *library* (a string) to reference a package from a
library that has been previously registered with `add_library`. Otherwise
the list of library paths will be used.
.. function:: include(manifest_path)

Wyświetl plik

@ -71,4 +71,11 @@ which is useful for development and testing.
Changes
~~~~~~~
*None yet*
Introduction of a new module :mod:`vfs`. The following functions and
classes have moved out of :mod:`os` to :mod:`vfs`:
- `os.mount`
- `os.umount`
- `os.VfsFat`
- `os.VfsLfs1`
- `os.VfsLfs2`
- `os.VfsPosix`

Wyświetl plik

@ -86,7 +86,8 @@ and .mpy version.
=================== ============
MicroPython release .mpy version
=================== ============
v1.22.0 and up 6.2
v1.23.0 and up 6.3
v1.22.x 6.2
v1.20 - v1.21.0 6.1
v1.19.x 6
v1.12 - v1.18 5
@ -102,6 +103,7 @@ MicroPython repository at which the .mpy version was changed.
=================== ========================================
.mpy version change Git commit
=================== ========================================
6.2 to 6.3 bdbc869f9ea200c0d28b2bc7bfb60acd9d884e1b
6.1 to 6.2 6967ff3c581a66f73e9f3d78975f47528db39980
6 to 6.1 d94141e1473aebae0d3c63aeaa8397651ad6fa01
5 to 6 f2040bfc7ee033e48acef9f289790f3b4e6b74e5

Wyświetl plik

@ -387,15 +387,15 @@ SDCard
The frozen sdcard driver (drivers/sdcard/sdcard.py) is available by connecting microSD card device to hardware SPI0 pins.::
from machine import Pin, SPI
import os, sdcard
import os, vfs, sdcard
spi = SPI(0, baudrate=500000)
cs = Pin.cpu.P103
sd = sdcard.SDCard(spi, cs)
os.mount(sd, '/sd')
vfs.mount(sd, '/sd')
os.listdir('/')
os.chdir('/sd')
os.umount('/sd')
vfs.umount('/sd')
OneWire driver
--------------

Wyświetl plik

@ -17,12 +17,12 @@ Adafruit ItsyBitsy M0 Express pin assignment table
=== ==== ============ ==== ==== ====== ====== ====== ======
Pin GPIO Pin name IRQ ADC Serial Serial TCC/TC TCC/TC
=== ==== ============ ==== ==== ====== ====== ====== ======
2 PA02 A0 2 0 - - - -
40 PB08 A1 8 2 - 4/0 4/0 -
41 PB09 A2 9 3 - 4/1 4/1 -
4 PA04 A3 4 4 - 0/0 0/0 -
5 PA05 A4 5 5 - 0/1 0/1 -
34 PB02 A5 2 10 - 5/0 6/0 -
2 PA02 A0 2 0 - - - -
40 PB08 A1 8 2 - 4/0 4/0 -
41 PB09 A2 9 3 - 4/1 4/1 -
4 PA04 A3 4 4 - 0/0 0/0 -
5 PA05 A4 5 5 - 0/1 0/1 -
34 PB02 A5 2 10 - 5/0 6/0 -
11 PA11 D0 11 19 0/3 2/3 1/1 0/3
10 PA10 D1 10 18 0/2 2/2 1/0 0/2
14 PA14 D2 14 - 2/2 4/2 3/0 0/4
@ -30,31 +30,31 @@ Pin GPIO Pin name IRQ ADC Serial Serial TCC/TC TCC/TC
8 PA08 D4 - 16 0/0 2/0 0/0 1/2
15 PA15 D5 15 - 2/3 4/3 3/1 0/5
21 PA21 D7 5 - 5/3 3/3 7/1 0/7
7 PA07 D9 7 7 - 0/3 1/1 -
7 PA07 D9 7 7 - 0/3 1/1 -
18 PA18 D10 2 - 1/2 3/2 3/0 0/2
16 PA16 D11 0 - 1/0 3/0 2/0 0/6
19 PA19 D12 3 - 1/3 3/3 3/1 0/3
17 PA17 D13 1 - 1/1 3/1 2/1 0/7
0 PA00 DOTSTAR_CLK 0 - - 1/0 2/0 -
1 PA01 DOTSTAR_DATA 1 - - 1/1 2/1 -
27 PA27 FLASH_CS 15 - - - - -
35 PB03 FLASH_MISO 3 11 - 5/1 6/1 -
54 PB22 FLASH_MOSI 6 - - 5/2 7/0 -
55 PB23 FLASH_SCK 7 - - 5/3 7/1 -
0 PA00 DOTSTAR_CLK 0 - - 1/0 2/0 -
1 PA01 DOTSTAR_DATA 1 - - 1/1 2/1 -
27 PA27 FLASH_CS 15 - - - - -
35 PB03 FLASH_MISO 3 11 - 5/1 6/1 -
54 PB22 FLASH_MOSI 6 - - 5/2 7/0 -
55 PB23 FLASH_SCK 7 - - 5/3 7/1 -
12 PA12 MISO 12 - 2/0 4/0 2/0 0/6
42 PB10 MOSI 10 - - 4/2 5/0 0/4
43 PB11 SCK 11 - - 4/3 5/1 0/5
23 PA23 SCL 7 - 3/1 5/1 4/1 0/5
22 PA22 SDA 6 - 3/0 5/0 4/0 0/4
30 PA30 SWCLK 10 - - 1/2 1/0 -
31 PA31 SWDIO 11 - - 1/3 1/1 -
30 PA30 SWCLK 10 - - 1/2 1/0 -
31 PA31 SWDIO 11 - - 1/3 1/1 -
24 PA24 USB_DM 12 - 3/2 5/2 5/0 1/2
25 PA25 USB_DP 13 - 3/3 5/3 5/1 1/3
3 PA03 3 1 - - - -
6 PA06 6 6 - 0/2 1/0 -
3 PA03 3 1 - - - -
6 PA06 6 6 - 0/2 1/0 -
13 PA13 13 - 2/1 4/1 2/0 0/7
20 PA20 4 - 5/2 3/2 7/0 0/4
28 PA28 8 - - - - -
28 PA28 8 - - - - -
=== ==== ============ ==== ==== ====== ====== ====== ======
@ -348,12 +348,12 @@ Adafruit Metro M4 Airlift pin assignment table
=== ==== ============ ==== ==== ==== ====== ====== ===== ===== =====
Pin GPIO Pin name IRQ ADC ADC Serial Serial TC PWM PWM
=== ==== ============ ==== ==== ==== ====== ====== ===== ===== =====
2 PA02 A0 2 0 - - - - - -
5 PA05 A1 5 5 - - 0/1 0/1 - -
6 PA06 A2 6 6 - - 0/2 1/0 - -
32 PB00 A3 9 12 - - 5/2 7/0 - -
40 PB08 A4 8 2 0 - 4/0 4/0 - -
41 PB09 A5 9 3 1 - 4/1 4/1 - -
2 PA02 A0 2 0 - - - - - -
5 PA05 A1 5 5 - - 0/1 0/1 - -
6 PA06 A2 6 6 - - 0/2 1/0 - -
32 PB00 A3 9 12 - - 5/2 7/0 - -
40 PB08 A4 8 2 0 - 4/0 4/0 - -
41 PB09 A5 9 3 1 - 4/1 4/1 - -
23 PA23 D0 7 - - 3/1 5/0 4/1 1/7 0/3
22 PA22 D1 6 - - 3/0 5/1 4/0 1/6 0/2
49 PB17 D2 1 - - 5/1 - 6/1 3/1 0/5
@ -364,17 +364,17 @@ Pin GPIO Pin name IRQ ADC ADC Serial Serial TC PWM PWM
44 PB12 D7 12 - - 4/0 - 4/0 3/0 0/0
21 PA21 D8 5 - - 5/3 3/3 7/1 1/5 0/1
20 PA20 D9 4 - - 5/2 3/2 7/0 1/4 0/0
3 PA03 AREF 3 10 - - - - - -
3 PA03 AREF 3 10 - - - - - -
18 PA18 D10 2 - - 1/2 3/2 3/0 1/2 0/6
19 PA19 D11 3 - - 1/3 3/3 3/1 1/3 0/7
16 PA16 D13 0 - - 1/0 3/1 2/0 1/0 0/4
36 PB04 ESP_BUSY 4 - 6 - - - - -
36 PB04 ESP_BUSY 4 - 6 - - - - -
15 PA15 ESP_CS 15 - - 2/3 4/3 3/1 2/1 1/3
33 PB01 ESP_GPIO0 1 13 - - 5/3 7/1 - -
37 PB05 ESP_RESET 5 - 7 - - - - -
55 PB23 ESP_RTS 7 - - 1/3 5/3 7/1 - -
7 PA07 ESP_RX 7 7 - - 0/3 1/1 - -
4 PA04 ESP_TX 4 4 - - 0/0 0/0 - -
33 PB01 ESP_GPIO0 1 13 - - 5/3 7/1 - -
37 PB05 ESP_RESET 5 - 7 - - - - -
55 PB23 ESP_RTS 7 - - 1/3 5/3 7/1 - -
7 PA07 ESP_RX 7 7 - - 0/3 1/1 - -
4 PA04 ESP_TX 4 4 - - 0/0 0/0 - -
43 PB11 FLASH_CS 12 - - - 4/3 5/1 0/5 1/1
11 PA11 FLASH_HOLD 11 11 - 0/3 2/3 1/1 0/3 1/7
9 PA09 FLASH_MISO 9 9 3 0/1 2/0 0/1 0/1 1/5
@ -383,21 +383,21 @@ Pin GPIO Pin name IRQ ADC ADC Serial Serial TC PWM PWM
10 PA10 FLASH_WP 10 10 - 0/2 2/2 1/0 0/2 1/6
14 PA14 MISO 14 - - 2/2 4/2 3/0 2/0 1/2
12 PA12 MOSI 12 - - 2/0 4/1 2/0 0/6 1/2
54 PB22 NEOPIXEL 22 - - 1/2 5/2 7/0 - -
38 PB06 RXLED 6 - 8 - - - - -
54 PB22 NEOPIXEL 22 - - 1/2 5/2 7/0 - -
38 PB06 RXLED 6 - 8 - - - - -
13 PA13 SCK 13 - - 2/1 4/0 2/1 0/7 1/3
35 PB03 SCL 9 15 - - 5/1 6/1 - -
34 PB02 SDA 2 14 - - 5/0 6/0 2/2 -
30 PA30 SWCLK 14 - - 7/2 1/2 6/0 2/0 -
31 PA31 SWDIO 15 - - 7/3 1/3 6/1 2/1 -
35 PB03 SCL 9 15 - - 5/1 6/1 - -
34 PB02 SDA 2 14 - - 5/0 6/0 2/2 -
30 PA30 SWCLK 14 - - 7/2 1/2 6/0 2/0 -
31 PA31 SWDIO 15 - - 7/3 1/3 6/1 2/1 -
62 PB30 SWO 14 - - 7/0 5/1 0/0 4/0 0/6
39 PB07 TXLED 7 - 9 - - - - -
24 PA24 USB_DM 8 - - 3/2 5/2 5/0 2/2 -
25 PA25 USB_DP 9 - - 3/3 5/3 5/1 - -
39 PB07 TXLED 7 - 9 - - - - -
24 PA24 USB_DM 8 - - 3/2 5/2 5/0 2/2 -
25 PA25 USB_DP 9 - - 3/3 5/3 5/1 - -
17 PA17 USB_HOSTEN 1 - - 1/1 3/0 2/1 1/1 0/5
0 PA00 - 0 - - - 1/0 2/0 - -
1 PA01 - 1 - - - 1/1 2/1 - -
27 PA27 - 11 - - - - - - -
0 PA00 - 0 - - - 1/0 2/0 - -
1 PA01 - 1 - - - 1/1 2/1 - -
27 PA27 - 11 - - - - - - -
63 PB31 - 15 - - 7/1 5/0 0/1 4/1 0/7
=== ==== ============ ==== ==== ==== ====== ====== ===== ===== =====
@ -870,7 +870,7 @@ Adafruit ItsyBitsy M4 Express :ref:`samd51_pinout_table`.
The default devices at the board are:
- UART 1 at pins PB23/PB22, labelled RXD/TXD
- UART 2 at pins PA13/PA12, labelled RXD/TXD
- I2C 5 at pins PA22/PA23, labelled SDA/SCL
- SPI 4 at pins PB12/PB11/PB13, labelled MOSI, MISO and SCK
- DAC output on pins PA02 and PA05, labelled A0 and A4
@ -884,36 +884,36 @@ The tables shown above were created with small a Python script running on the ta
from machine import Pin
import os
def print_entry(e, txt):
def print_item(e, txt):
print(txt, end=": ")
if e == 255:
print(" - ", end="")
else:
print("%d/%d" % (e >> 4, e & 0x0f), end="")
def print_pininfo(pin, info):
print("%3d" % pin, end=" ")
print("P%c%02d" % ("ABCD"[pin // 32], pin % 32), end="")
print(" %12s" % info[0], end="")
def print_pininfo(pin_id, name, info):
print("%3d" % pin_id, end=" ")
print("%4s %12s" % (info[0], name), end="")
print(" IRQ:%2s" % (info[1] if info[1] != 255 else "-"), end="")
print(" ADC0:%2s" % (info[2] if info[2] != 255 else "-"), end="")
if len(info) == 7:
print_entry(info[3], " Serial1")
print_entry(info[4], " Serial2")
print_entry(info[5], " PWM1" if (info[5] >> 4) < 3 else " TC")
print_entry(info[6], " PWM2")
print_item(info[3], " Serial1")
print_item(info[4], " Serial2")
print_item(info[5], " PWM1" if (info[5] >> 4) < 3 else " TC")
print_item(info[6], " PWM2")
else:
print(" ADC1:%2s" % (info[3] if info[3] != 255 else "-"), end="")
print_entry(info[4], " Serial1")
print_entry(info[5], " Serial2")
print_entry(info[6], " TC")
print_entry(info[7], " PWM1")
print_entry(info[8], " PWM2")
print_item(info[4], " Serial1")
print_item(info[5], " Serial2")
print_item(info[6], " TC")
print_item(info[7], " PWM1")
print_item(info[8], " PWM2")
print()
def tblkey(i):
name = i[1][0]
if name != "-":
name = i[1]
if name != "":
if len(name) < 3:
return " " + name
else:
@ -921,17 +921,25 @@ The tables shown above were created with small a Python script running on the ta
else:
return "zzzzzzz%03d" % i[0]
def table(num = 127):
def table(num=127, sort=True):
pintbl = []
inv_bd = {v: k for k, v in Pin.board.__dict__.items()}
for i in range(num):
try:
pintbl.append((i, pininfo(i)))
p = Pin(i)
pi = pininfo(p)
if p in inv_bd.keys():
name = inv_bd[p]
else:
name = ""
pintbl.append((i, name, pininfo(i)))
except:
pass
# print("not defined")
pintbl.sort(key=tblkey)
if sort:
pintbl.sort(key=tblkey)
for item in pintbl:
print_pininfo(item[0], item[1])
print_pininfo(item[0], item[1], item[2])
table()

Wyświetl plik

@ -373,7 +373,7 @@ functions are defined in ``os`` module:
Mounts a block device (like an ``SD`` object) in the specified mount
point. Example::
os.mount(sd, '/sd')
vfs.mount(sd, '/sd')
.. function:: unmount(path)

Wyświetl plik

@ -171,13 +171,13 @@ SD card
See :ref:`machine.SD <machine.SD>`. ::
from machine import SD
import os
import vfs
# clock pin, cmd pin, data0 pin
sd = SD(pins=('GP10', 'GP11', 'GP15'))
# or use default ones for the expansion board
sd = SD()
os.mount(sd, '/sd')
vfs.mount(sd, '/sd')
WLAN (WiFi)
-----------

Wyświetl plik

@ -109,12 +109,12 @@ Disk Access
Use the :ref:`zephyr.DiskAccess <zephyr.DiskAccess>` class to support filesystem::
import os
import vfs
from zephyr import DiskAccess
block_dev = DiskAccess('SDHC') # create a block device object for an SD card
os.VfsFat.mkfs(block_dev) # create FAT filesystem object using the disk storage block
os.mount(block_dev, '/sd') # mount the filesystem at the SD card subdirectory
vfs.VfsFat.mkfs(block_dev) # create FAT filesystem object using the disk storage block
vfs.mount(block_dev, '/sd') # mount the filesystem at the SD card subdirectory
# with the filesystem mounted, files can be manipulated as normal
with open('/sd/hello.txt','w') as f: # open a new file in the directory
@ -126,12 +126,12 @@ Flash Area
Use the :ref:`zephyr.FlashArea <zephyr.FlashArea>` class to support filesystem::
import os
import vfs
from zephyr import FlashArea
block_dev = FlashArea(4, 4096) # creates a block device object in the frdm-k64f flash scratch partition
os.VfsLfs2.mkfs(block_dev) # create filesystem in lfs2 format using the flash block device
os.mount(block_dev, '/flash') # mount the filesystem at the flash subdirectory
vfs.VfsLfs2.mkfs(block_dev) # create filesystem in lfs2 format using the flash block device
vfs.mount(block_dev, '/flash') # mount the filesystem at the flash subdirectory
# with the filesystem mounted, files can be manipulated as normal
with open('/flash/hello.txt','w') as f: # open a new file in the directory

Wyświetl plik

@ -6,14 +6,14 @@ Filesystems and Storage
Storage modules support virtual filesystem with FAT and littlefs formats, backed by either
Zephyr DiskAccess or FlashArea (flash map) APIs depending on which the board supports.
See `os Filesystem Mounting <https://docs.micropython.org/en/latest/library/os.html?highlight=os#filesystem-mounting>`_.
See `vfs Filesystem Mounting <https://docs.micropython.org/en/latest/library/vfs.html?highlight=vfs#filesystem-mounting>`_.
Disk Access
-----------
The :ref:`zephyr.DiskAccess <zephyr.DiskAccess>` class can be used to access storage devices, such as SD cards.
This class uses `Zephyr Disk Access API <https://docs.zephyrproject.org/latest/reference/storage/disk/access.html>`_ and
implements the `os.AbstractBlockDev` protocol.
implements the `vfs.AbstractBlockDev` protocol.
For use with SD card controllers, SD cards must be present at boot & not removed; they will
be auto detected and initialized by filesystem at boot. Use the disk driver interface and a
@ -21,11 +21,11 @@ file system to access SD cards via disk access (see below).
Example usage of FatFS with an SD card on the mimxrt1050_evk board::
import os
import vfs
from zephyr import DiskAccess
bdev = zephyr.DiskAccess('SDHC') # create block device object using DiskAccess
os.VfsFat.mkfs(bdev) # create FAT filesystem object using the disk storage block
os.mount(bdev, '/sd') # mount the filesystem at the SD card subdirectory
vfs.VfsFat.mkfs(bdev) # create FAT filesystem object using the disk storage block
vfs.mount(bdev, '/sd') # mount the filesystem at the SD card subdirectory
with open('/sd/hello.txt','w') as f: # open a new file in the directory
f.write('Hello world') # write to the file
print(open('/sd/hello.txt').read()) # print contents of the file
@ -39,15 +39,15 @@ customize filesystem configurations. To store persistent data on the device, usi
API is recommended (see below).
This class uses `Zephyr Flash map API <https://docs.zephyrproject.org/latest/reference/storage/flash_map/flash_map.html#>`_ and
implements the `os.AbstractBlockDev` protocol.
implements the `vfs.AbstractBlockDev` protocol.
Example usage with the internal flash on the reel_board or the rv32m1_vega_ri5cy board::
import os
import vfs
from zephyr import FlashArea
bdev = FlashArea(FlashArea.STORAGE, 4096) # create block device object using FlashArea
os.VfsLfs2.mkfs(bdev) # create Little filesystem object using the flash area block
os.mount(bdev, '/flash') # mount the filesystem at the flash storage subdirectory
vfs.VfsLfs2.mkfs(bdev) # create Little filesystem object using the flash area block
vfs.mount(bdev, '/flash') # mount the filesystem at the flash storage subdirectory
with open('/flash/hello.txt','w') as f: # open a new file in the directory
f.write('Hello world') # write to the file
print(open('/flash/hello.txt').read()) # print contents of the file

Wyświetl plik

@ -49,14 +49,14 @@
#endif
STATIC void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) {
static void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) {
mp_hal_pin_write(self->io0, v & 1);
mp_hal_pin_write(self->io1, (v >> 1) & 1);
mp_hal_pin_write(self->io2, (v >> 2) & 1);
mp_hal_pin_write(self->io3, (v >> 3) & 1);
}
STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) {
static int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
switch (cmd) {
@ -80,7 +80,7 @@ STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) {
return 0; // success
}
STATIC void mp_soft_qspi_transfer(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *src, uint8_t *dest) {
static void mp_soft_qspi_transfer(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *src, uint8_t *dest) {
// Will run as fast as possible, limited only by CPU speed and GPIO time
mp_hal_pin_input(self->io1);
mp_hal_pin_output(self->io0);
@ -119,7 +119,7 @@ STATIC void mp_soft_qspi_transfer(mp_soft_qspi_obj_t *self, size_t len, const ui
}
}
STATIC void mp_soft_qspi_qread(mp_soft_qspi_obj_t *self, size_t len, uint8_t *buf) {
static void mp_soft_qspi_qread(mp_soft_qspi_obj_t *self, size_t len, uint8_t *buf) {
// Make all IO lines input
mp_hal_pin_input(self->io2);
mp_hal_pin_input(self->io3);
@ -137,7 +137,7 @@ STATIC void mp_soft_qspi_qread(mp_soft_qspi_obj_t *self, size_t len, uint8_t *bu
}
}
STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *buf) {
static void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *buf) {
// Make all IO lines output
mp_hal_pin_output(self->io2);
mp_hal_pin_output(self->io3);
@ -158,7 +158,7 @@ STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint
//mp_hal_pin_input(self->io1);
}
STATIC int mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t data) {
static int mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t data) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint32_t cmd_buf = cmd | data << 8;
CS_LOW(self);
@ -167,7 +167,7 @@ STATIC int mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, u
return 0;
}
STATIC int mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) {
static int mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint8_t cmd_buf[5] = {cmd};
uint8_t addr_len = mp_spi_set_addr_buff(&cmd_buf[1], addr);
@ -178,7 +178,7 @@ STATIC int mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t
return 0;
}
STATIC int mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len, uint32_t *dest) {
static int mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len, uint32_t *dest) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint32_t cmd_buf = cmd;
CS_LOW(self);
@ -188,7 +188,7 @@ STATIC int mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len, uint32_
return 0;
}
STATIC int mp_soft_qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest) {
static int mp_soft_qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint8_t cmd_buf[7] = {cmd};
uint8_t addr_len = mp_spi_set_addr_buff(&cmd_buf[1], addr);

Wyświetl plik

@ -51,7 +51,7 @@ extern uint8_t mp_bluetooth_hci_cmd_buf[4 + 256];
// Provided by the port.
extern machine_uart_obj_t mp_bluetooth_hci_uart_obj;
STATIC void cywbt_wait_cts_low(void) {
static void cywbt_wait_cts_low(void) {
mp_hal_pin_config(CYW43_PIN_BT_CTS, MP_HAL_PIN_MODE_INPUT, MP_HAL_PIN_PULL_UP, 0);
for (int i = 0; i < 200; ++i) {
if (mp_hal_pin_read(CYW43_PIN_BT_CTS) == 0) {
@ -64,7 +64,7 @@ STATIC void cywbt_wait_cts_low(void) {
}
#endif
STATIC int cywbt_hci_cmd_raw(size_t len, uint8_t *buf) {
static int cywbt_hci_cmd_raw(size_t len, uint8_t *buf) {
mp_bluetooth_hci_uart_write((void *)buf, len);
for (int c, i = 0; i < 6; ++i) {
while ((c = mp_bluetooth_hci_uart_readchar()) == -1) {
@ -96,7 +96,7 @@ STATIC int cywbt_hci_cmd_raw(size_t len, uint8_t *buf) {
return 0;
}
STATIC int cywbt_hci_cmd(int ogf, int ocf, size_t param_len, const uint8_t *param_buf) {
static int cywbt_hci_cmd(int ogf, int ocf, size_t param_len, const uint8_t *param_buf) {
uint8_t *buf = mp_bluetooth_hci_cmd_buf;
buf[0] = 0x01;
buf[1] = ocf;
@ -108,19 +108,19 @@ STATIC int cywbt_hci_cmd(int ogf, int ocf, size_t param_len, const uint8_t *para
return cywbt_hci_cmd_raw(4 + param_len, buf);
}
STATIC void put_le16(uint8_t *buf, uint16_t val) {
static void put_le16(uint8_t *buf, uint16_t val) {
buf[0] = val;
buf[1] = val >> 8;
}
STATIC void put_le32(uint8_t *buf, uint32_t val) {
static void put_le32(uint8_t *buf, uint32_t val) {
buf[0] = val;
buf[1] = val >> 8;
buf[2] = val >> 16;
buf[3] = val >> 24;
}
STATIC int cywbt_set_baudrate(uint32_t baudrate) {
static int cywbt_set_baudrate(uint32_t baudrate) {
uint8_t buf[6];
put_le16(buf, 0);
put_le32(buf + 2, baudrate);
@ -128,7 +128,7 @@ STATIC int cywbt_set_baudrate(uint32_t baudrate) {
}
// download firmware
STATIC int cywbt_download_firmware(const uint8_t *firmware) {
static int cywbt_download_firmware(const uint8_t *firmware) {
cywbt_hci_cmd(0x3f, 0x2e, 0, NULL);
bool last_packet = false;
@ -255,7 +255,7 @@ int mp_bluetooth_hci_controller_deinit(void) {
}
#ifdef CYW43_PIN_BT_DEV_WAKE
STATIC uint32_t bt_sleep_ticks;
static uint32_t bt_sleep_ticks;
#endif
int mp_bluetooth_hci_controller_sleep_maybe(void) {

Wyświetl plik

@ -29,6 +29,9 @@
#include "py/runtime.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#if MICROPY_PY_MACHINE_PULSE
#include "extmod/modmachine.h"
#include "drivers/dht/dht.h"
@ -37,7 +40,7 @@
#define mp_hal_pin_od_high_dht mp_hal_pin_od_high
#endif
STATIC mp_obj_t dht_readinto(mp_obj_t pin_in, mp_obj_t buf_in) {
static mp_obj_t dht_readinto(mp_obj_t pin_in, mp_obj_t buf_in) {
mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(pin_in);
mp_hal_pin_open_drain(pin);
@ -92,3 +95,5 @@ timeout:
mp_raise_OSError(MP_ETIMEDOUT);
}
MP_DEFINE_CONST_FUN_OBJ_2(dht_readinto_obj, dht_readinto);
#endif // MICROPY_PY_MACHINE_PULSE

Wyświetl plik

@ -44,14 +44,14 @@
extern void mod_network_poll_events(void);
STATIC mp_obj_t esp_hosted_pin_irq_callback(mp_obj_t self_in) {
static mp_obj_t esp_hosted_pin_irq_callback(mp_obj_t self_in) {
#ifdef MICROPY_HW_WIFI_LED
led_toggle(MICROPY_HW_WIFI_LED);
#endif
mod_network_poll_events();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp_hosted_pin_irq_callback_obj, esp_hosted_pin_irq_callback);
static MP_DEFINE_CONST_FUN_OBJ_1(esp_hosted_pin_irq_callback_obj, esp_hosted_pin_irq_callback);
MP_WEAK int esp_hosted_hal_init(uint32_t mode) {
// Perform a hard reset and set pins to their defaults.

Wyświetl plik

@ -442,6 +442,23 @@ typedef struct {
.single_status_byte = false, \
}
// Settings for the ISSI devices
#define IS25LPWP064D { \
.total_size = (1 << 23), /* 8 MiB */ \
.start_up_time_us = 5000, \
.manufacturer_id = 0x9D, \
.memory_type = 0x60, \
.capacity = 0x17, \
.max_clock_speed_mhz = 80, \
.quad_enable_bit_mask = 0x40, \
.has_sector_protection = false, \
.supports_fast_read = true, \
.supports_qspi = true, \
.supports_qspi_writes = true, \
.write_status_register_split = false, \
.single_status_byte = true, \
}
// Settings for a GENERIC device with the most common setting
#define GENERIC { \
.total_size = (1 << 21), /* 2 MiB */ \

Wyświetl plik

@ -56,21 +56,21 @@
#define PAGE_SIZE (256) // maximum bytes we can write in one SPI transfer
#define SECTOR_SIZE MP_SPIFLASH_ERASE_BLOCK_SIZE
STATIC void mp_spiflash_acquire_bus(mp_spiflash_t *self) {
static void mp_spiflash_acquire_bus(mp_spiflash_t *self) {
const mp_spiflash_config_t *c = self->config;
if (c->bus_kind == MP_SPIFLASH_BUS_QSPI) {
c->bus.u_qspi.proto->ioctl(c->bus.u_qspi.data, MP_QSPI_IOCTL_BUS_ACQUIRE);
}
}
STATIC void mp_spiflash_release_bus(mp_spiflash_t *self) {
static void mp_spiflash_release_bus(mp_spiflash_t *self) {
const mp_spiflash_config_t *c = self->config;
if (c->bus_kind == MP_SPIFLASH_BUS_QSPI) {
c->bus.u_qspi.proto->ioctl(c->bus.u_qspi.data, MP_QSPI_IOCTL_BUS_RELEASE);
}
}
STATIC int mp_spiflash_write_cmd_data(mp_spiflash_t *self, uint8_t cmd, size_t len, uint32_t data) {
static int mp_spiflash_write_cmd_data(mp_spiflash_t *self, uint8_t cmd, size_t len, uint32_t data) {
int ret = 0;
const mp_spiflash_config_t *c = self->config;
if (c->bus_kind == MP_SPIFLASH_BUS_SPI) {
@ -84,7 +84,7 @@ STATIC int mp_spiflash_write_cmd_data(mp_spiflash_t *self, uint8_t cmd, size_t l
return ret;
}
STATIC int mp_spiflash_transfer_cmd_addr_data(mp_spiflash_t *self, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src, uint8_t *dest) {
static int mp_spiflash_transfer_cmd_addr_data(mp_spiflash_t *self, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src, uint8_t *dest) {
int ret = 0;
const mp_spiflash_config_t *c = self->config;
if (c->bus_kind == MP_SPIFLASH_BUS_SPI) {
@ -109,7 +109,7 @@ STATIC int mp_spiflash_transfer_cmd_addr_data(mp_spiflash_t *self, uint8_t cmd,
return ret;
}
STATIC int mp_spiflash_read_cmd(mp_spiflash_t *self, uint8_t cmd, size_t len, uint32_t *dest) {
static int mp_spiflash_read_cmd(mp_spiflash_t *self, uint8_t cmd, size_t len, uint32_t *dest) {
const mp_spiflash_config_t *c = self->config;
if (c->bus_kind == MP_SPIFLASH_BUS_SPI) {
mp_hal_pin_write(c->bus.u_spi.cs, 0);
@ -122,7 +122,7 @@ STATIC int mp_spiflash_read_cmd(mp_spiflash_t *self, uint8_t cmd, size_t len, ui
}
}
STATIC int mp_spiflash_read_data(mp_spiflash_t *self, uint32_t addr, size_t len, uint8_t *dest) {
static int mp_spiflash_read_data(mp_spiflash_t *self, uint32_t addr, size_t len, uint8_t *dest) {
const mp_spiflash_config_t *c = self->config;
uint8_t cmd;
if (c->bus_kind == MP_SPIFLASH_BUS_SPI) {
@ -133,11 +133,11 @@ STATIC int mp_spiflash_read_data(mp_spiflash_t *self, uint32_t addr, size_t len,
return mp_spiflash_transfer_cmd_addr_data(self, cmd, addr, len, NULL, dest);
}
STATIC int mp_spiflash_write_cmd(mp_spiflash_t *self, uint8_t cmd) {
static int mp_spiflash_write_cmd(mp_spiflash_t *self, uint8_t cmd) {
return mp_spiflash_write_cmd_data(self, cmd, 0, 0);
}
STATIC int mp_spiflash_wait_sr(mp_spiflash_t *self, uint8_t mask, uint8_t val, uint32_t timeout) {
static int mp_spiflash_wait_sr(mp_spiflash_t *self, uint8_t mask, uint8_t val, uint32_t timeout) {
do {
uint32_t sr;
int ret = mp_spiflash_read_cmd(self, CMD_RDSR, 1, &sr);
@ -152,11 +152,11 @@ STATIC int mp_spiflash_wait_sr(mp_spiflash_t *self, uint8_t mask, uint8_t val, u
return -MP_ETIMEDOUT;
}
STATIC int mp_spiflash_wait_wel1(mp_spiflash_t *self) {
static int mp_spiflash_wait_wel1(mp_spiflash_t *self) {
return mp_spiflash_wait_sr(self, 2, 2, WAIT_SR_TIMEOUT);
}
STATIC int mp_spiflash_wait_wip0(mp_spiflash_t *self) {
static int mp_spiflash_wait_wip0(mp_spiflash_t *self) {
return mp_spiflash_wait_sr(self, 1, 0, WAIT_SR_TIMEOUT);
}
@ -219,7 +219,7 @@ void mp_spiflash_deepsleep(mp_spiflash_t *self, int value) {
}
}
STATIC int mp_spiflash_erase_block_internal(mp_spiflash_t *self, uint32_t addr) {
static int mp_spiflash_erase_block_internal(mp_spiflash_t *self, uint32_t addr) {
int ret = 0;
// enable writes
ret = mp_spiflash_write_cmd(self, CMD_WREN);
@ -244,7 +244,7 @@ STATIC int mp_spiflash_erase_block_internal(mp_spiflash_t *self, uint32_t addr)
return mp_spiflash_wait_wip0(self);
}
STATIC int mp_spiflash_write_page(mp_spiflash_t *self, uint32_t addr, size_t len, const uint8_t *src) {
static int mp_spiflash_write_page(mp_spiflash_t *self, uint32_t addr, size_t len, const uint8_t *src) {
int ret = 0;
// enable writes
ret = mp_spiflash_write_cmd(self, CMD_WREN);
@ -361,7 +361,7 @@ int mp_spiflash_cached_read(mp_spiflash_t *self, uint32_t addr, size_t len, uint
return ret;
}
STATIC int mp_spiflash_cache_flush_internal(mp_spiflash_t *self) {
static int mp_spiflash_cache_flush_internal(mp_spiflash_t *self) {
#if USE_WR_DELAY
if (!(self->flags & 1)) {
return 0;
@ -396,7 +396,7 @@ int mp_spiflash_cache_flush(mp_spiflash_t *self) {
return ret;
}
STATIC int mp_spiflash_cached_write_part(mp_spiflash_t *self, uint32_t addr, size_t len, const uint8_t *src) {
static int mp_spiflash_cached_write_part(mp_spiflash_t *self, uint32_t addr, size_t len, const uint8_t *src) {
// Align to 4096 sector
uint32_t offset = addr & 0xfff;
uint32_t sec = addr >> 12;

Wyświetl plik

@ -12,7 +12,7 @@ PROG = embed
CFLAGS += -I.
CFLAGS += -I$(EMBED_DIR)
CFLAGS += -I$(EMBED_DIR)/port
CFLAGS += -Wall -Og
CFLAGS += -Wall -Og -fno-common
SRC += main.c
SRC += $(wildcard $(EMBED_DIR)/*/*.c) $(wildcard $(EMBED_DIR)/*/*/*.c)

Wyświetl plik

@ -31,7 +31,14 @@ static char heap[8 * 1024];
int main() {
// Initialise MicroPython.
mp_embed_init(&heap[0], sizeof(heap));
//
// Note: &stack_top below should be good enough for many cases.
// However, depending on environment, there might be more appropriate
// ways to get the stack top value.
// eg. pthread_get_stackaddr_np, pthread_getattr_np,
// __builtin_frame_address/__builtin_stack_address, etc.
int stack_top;
mp_embed_init(&heap[0], sizeof(heap), &stack_top);
// Run the example scripts (they will be compiled first).
mp_embed_exec_str(example_1);

Wyświetl plik

@ -11,9 +11,10 @@ SRC = btree_c.c btree_py.py
ARCH = x64
BTREE_DIR = $(MPY_DIR)/lib/berkeley-db-1.xx
BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error="(void)" -Dabort=abort_ "-Dvirt_fd_t=void*" $(BTREE_DEFS_EXTRA)
CFLAGS += -I$(BTREE_DIR)/PORT/include
CFLAGS += -Wno-old-style-definition -Wno-sign-compare -Wno-unused-parameter $(BTREE_DEFS)
BERKELEY_DB_CONFIG_FILE ?= \"extmod/berkeley-db/berkeley_db_config_port.h\"
CFLAGS += -I$(BTREE_DIR)/include
CFLAGS += -DBERKELEY_DB_CONFIG_FILE=$(BERKELEY_DB_CONFIG_FILE)
CFLAGS += -Wno-old-style-definition -Wno-sign-compare -Wno-unused-parameter
SRC += $(addprefix $(realpath $(BTREE_DIR))/,\
btree/bt_close.c \

Wyświetl plik

@ -39,6 +39,10 @@ void abort_(void) {
nlr_raise(mp_obj_new_exception(mp_load_global(MP_QSTR_RuntimeError)));
}
int puts(const char *s) {
return mp_printf(&mp_plat_print, "%s\n", s);
}
int native_errno;
#if defined(__linux__)
int *__errno_location (void)
@ -100,9 +104,9 @@ mp_getiter_iternext_custom_t btree_getiter_iternext;
#include "extmod/modbtree.c"
mp_map_elem_t btree_locals_dict_table[8];
STATIC MP_DEFINE_CONST_DICT(btree_locals_dict, btree_locals_dict_table);
static MP_DEFINE_CONST_DICT(btree_locals_dict, btree_locals_dict_table);
STATIC mp_obj_t btree_open(size_t n_args, const mp_obj_t *args) {
static mp_obj_t btree_open(size_t n_args, const mp_obj_t *args) {
// Make sure we got a stream object
mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
@ -118,7 +122,7 @@ STATIC mp_obj_t btree_open(size_t n_args, const mp_obj_t *args) {
return MP_OBJ_FROM_PTR(btree_new(db, args[0]));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_open_obj, 5, 5, btree_open);
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_open_obj, 5, 5, btree_open);
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
MP_DYNRUNTIME_INIT_ENTRY

Wyświetl plik

@ -29,7 +29,7 @@ mp_obj_t mp_stream_close(mp_obj_t stream) {
MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_close_obj, mp_stream_close);
// Re-implemented from py/stream.c, not yet available in dynruntime.h.
STATIC mp_obj_t mp_stream___exit__(size_t n_args, const mp_obj_t *args) {
static mp_obj_t mp_stream___exit__(size_t n_args, const mp_obj_t *args) {
(void)n_args;
return mp_stream_close(args[0]);
}
@ -42,7 +42,7 @@ mp_obj_t mp_identity(mp_obj_t self) {
MP_DEFINE_CONST_FUN_OBJ_1(mp_identity_obj, mp_identity);
mp_map_elem_t deflateio_locals_dict_table[7];
STATIC MP_DEFINE_CONST_DICT(deflateio_locals_dict, deflateio_locals_dict_table);
static MP_DEFINE_CONST_DICT(deflateio_locals_dict, deflateio_locals_dict_table);
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
MP_DYNRUNTIME_INIT_ENTRY

Wyświetl plik

@ -8,7 +8,7 @@
#include "py/dynruntime.h"
// Helper function to compute factorial
STATIC mp_int_t factorial_helper(mp_int_t x) {
static mp_int_t factorial_helper(mp_int_t x) {
if (x == 0) {
return 1;
}
@ -16,7 +16,7 @@ STATIC mp_int_t factorial_helper(mp_int_t x) {
}
// This is the function which will be called from Python, as factorial(x)
STATIC mp_obj_t factorial(mp_obj_t x_obj) {
static mp_obj_t factorial(mp_obj_t x_obj) {
// Extract the integer from the MicroPython input object
mp_int_t x = mp_obj_get_int(x_obj);
// Calculate the factorial
@ -25,7 +25,7 @@ STATIC mp_obj_t factorial(mp_obj_t x_obj) {
return mp_obj_new_int(result);
}
// Define a Python reference to the function above
STATIC MP_DEFINE_CONST_FUN_OBJ_1(factorial_obj, factorial);
static MP_DEFINE_CONST_FUN_OBJ_1(factorial_obj, factorial);
// This is the entry point and is called when the module is imported
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {

Wyświetl plik

@ -25,15 +25,15 @@ uint16_t *const table_ptr16a[] = { &data16[0], &data16[1], &data16[2], &data16[3
const uint16_t *const table_ptr16b[] = { &table16[0], &table16[1] };
// A simple function that adds its 2 arguments (must be integers)
STATIC mp_obj_t add(mp_obj_t x_in, mp_obj_t y_in) {
static mp_obj_t add(mp_obj_t x_in, mp_obj_t y_in) {
mp_int_t x = mp_obj_get_int(x_in);
mp_int_t y = mp_obj_get_int(y_in);
return mp_obj_new_int(x + y);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(add_obj, add);
static MP_DEFINE_CONST_FUN_OBJ_2(add_obj, add);
// A local helper function (not exposed to Python)
STATIC mp_int_t fibonacci_helper(mp_int_t x) {
static mp_int_t fibonacci_helper(mp_int_t x) {
if (x < MP_ARRAY_SIZE(table8)) {
return table8[x];
} else {
@ -42,17 +42,17 @@ STATIC mp_int_t fibonacci_helper(mp_int_t x) {
}
// A function which computes Fibonacci numbers
STATIC mp_obj_t fibonacci(mp_obj_t x_in) {
static mp_obj_t fibonacci(mp_obj_t x_in) {
mp_int_t x = mp_obj_get_int(x_in);
if (x < 0) {
mp_raise_ValueError(MP_ERROR_TEXT("can't compute negative Fibonacci number"));
}
return mp_obj_new_int(fibonacci_helper(x));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(fibonacci_obj, fibonacci);
static MP_DEFINE_CONST_FUN_OBJ_1(fibonacci_obj, fibonacci);
// A function that accesses the BSS data
STATIC mp_obj_t access(size_t n_args, const mp_obj_t *args) {
static mp_obj_t access(size_t n_args, const mp_obj_t *args) {
if (n_args == 0) {
// Create a list holding all items from data16
mp_obj_list_t *lst = MP_OBJ_TO_PTR(mp_obj_new_list(MP_ARRAY_SIZE(data16), NULL));
@ -71,17 +71,17 @@ STATIC mp_obj_t access(size_t n_args, const mp_obj_t *args) {
return mp_const_none;
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(access_obj, 0, 2, access);
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(access_obj, 0, 2, access);
// A function that allocates memory and creates a bytearray
STATIC mp_obj_t make_array(void) {
static mp_obj_t make_array(void) {
uint16_t *ptr = m_new(uint16_t, MP_ARRAY_SIZE(table_ptr16b));
for (int i = 0; i < MP_ARRAY_SIZE(table_ptr16b); ++i) {
ptr[i] = *table_ptr16b[i];
}
return mp_obj_new_bytearray_by_ref(sizeof(uint16_t) * MP_ARRAY_SIZE(table_ptr16b), ptr);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(make_array_obj, make_array);
static MP_DEFINE_CONST_FUN_OBJ_0(make_array_obj, make_array);
// This is the entry point and is called when the module is imported
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {

Wyświetl plik

@ -22,29 +22,29 @@
// A function that uses the default float type configured for the current target
// This default can be overridden by specifying MICROPY_FLOAT_IMPL at the make level
STATIC mp_obj_t add(mp_obj_t x, mp_obj_t y) {
static mp_obj_t add(mp_obj_t x, mp_obj_t y) {
return mp_obj_new_float(mp_obj_get_float(x) + mp_obj_get_float(y));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(add_obj, add);
static MP_DEFINE_CONST_FUN_OBJ_2(add_obj, add);
// A function that explicitly uses single precision floats
STATIC mp_obj_t add_f(mp_obj_t x, mp_obj_t y) {
static mp_obj_t add_f(mp_obj_t x, mp_obj_t y) {
return mp_obj_new_float_from_f(mp_obj_get_float_to_f(x) + mp_obj_get_float_to_f(y));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(add_f_obj, add_f);
static MP_DEFINE_CONST_FUN_OBJ_2(add_f_obj, add_f);
#if USE_DOUBLE
// A function that explicitly uses double precision floats
STATIC mp_obj_t add_d(mp_obj_t x, mp_obj_t y) {
static mp_obj_t add_d(mp_obj_t x, mp_obj_t y) {
return mp_obj_new_float_from_d(mp_obj_get_float_to_d(x) + mp_obj_get_float_to_d(y));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(add_d_obj, add_d);
static MP_DEFINE_CONST_FUN_OBJ_2(add_d_obj, add_d);
#endif
// A function that computes the product of floats in an array.
// This function uses the most general C argument interface, which is more difficult
// to use but has access to the globals dict of the module via self->globals.
STATIC mp_obj_t productf(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
static mp_obj_t productf(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
// Check number of arguments is valid
mp_arg_check_num(n_args, n_kw, 1, 1, false);

Wyświetl plik

@ -8,7 +8,7 @@
#include "py/dynruntime.h"
// A function that returns a tuple of object types.
STATIC mp_obj_t get_types(void) {
static mp_obj_t get_types(void) {
return mp_obj_new_tuple(9, ((mp_obj_t []) {
MP_OBJ_FROM_PTR(&mp_type_type),
MP_OBJ_FROM_PTR(&mp_type_NoneType),
@ -21,10 +21,10 @@ STATIC mp_obj_t get_types(void) {
MP_OBJ_FROM_PTR(&mp_type_dict),
}));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(get_types_obj, get_types);
static MP_DEFINE_CONST_FUN_OBJ_0(get_types_obj, get_types);
// A function that returns a tuple of constant objects.
STATIC mp_obj_t get_const_objects(void) {
static mp_obj_t get_const_objects(void) {
return mp_obj_new_tuple(5, ((mp_obj_t []) {
mp_const_none,
mp_const_false,
@ -33,17 +33,17 @@ STATIC mp_obj_t get_const_objects(void) {
mp_const_empty_tuple,
}));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(get_const_objects_obj, get_const_objects);
static MP_DEFINE_CONST_FUN_OBJ_0(get_const_objects_obj, get_const_objects);
// A function that creates a dictionary from the given arguments.
STATIC mp_obj_t make_dict(size_t n_args, const mp_obj_t *args) {
static mp_obj_t make_dict(size_t n_args, const mp_obj_t *args) {
mp_obj_t dict = mp_obj_new_dict(n_args / 2);
for (; n_args >= 2; n_args -= 2, args += 2) {
mp_obj_dict_store(dict, args[0], args[1]);
}
return dict;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(make_dict_obj, 0, MP_OBJ_FUN_ARGS_MAX, make_dict);
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(make_dict_obj, 0, MP_OBJ_FUN_ARGS_MAX, make_dict);
// This is the entry point and is called when the module is imported.
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {

Wyświetl plik

@ -24,7 +24,7 @@ typedef struct {
// Essentially Factorial.__new__ (but also kind of __init__).
// Takes a single argument (the number to find the factorial of)
STATIC mp_obj_t factorial_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args_in) {
static mp_obj_t factorial_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args_in) {
mp_arg_check_num(n_args, n_kw, 1, 1, false);
mp_obj_factorial_t *o = mp_obj_malloc(mp_obj_factorial_t, type);
@ -33,7 +33,7 @@ STATIC mp_obj_t factorial_make_new(const mp_obj_type_t *type, size_t n_args, siz
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_int_t factorial_helper(mp_int_t x) {
static mp_int_t factorial_helper(mp_int_t x) {
if (x == 0) {
return 1;
}
@ -41,16 +41,16 @@ STATIC mp_int_t factorial_helper(mp_int_t x) {
}
// Implements Factorial.calculate()
STATIC mp_obj_t factorial_calculate(mp_obj_t self_in) {
static mp_obj_t factorial_calculate(mp_obj_t self_in) {
mp_obj_factorial_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_int(factorial_helper(self->n));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(factorial_calculate_obj, factorial_calculate);
static MP_DEFINE_CONST_FUN_OBJ_1(factorial_calculate_obj, factorial_calculate);
// Locals dict for the Factorial type (will have a single method, calculate,
// added in mpy_init).
mp_map_elem_t factorial_locals_dict_table[1];
STATIC MP_DEFINE_CONST_DICT(factorial_locals_dict, factorial_locals_dict_table);
static MP_DEFINE_CONST_DICT(factorial_locals_dict, factorial_locals_dict_table);
// This is the entry point and is called when the module is imported
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {

Wyświetl plik

@ -1,3 +1,4 @@
#define MICROPY_PY_ARRAY (1)
#define MICROPY_PY_FRAMEBUF (1)
#include "py/dynruntime.h"
@ -12,8 +13,8 @@ mp_obj_full_type_t mp_type_framebuf;
#include "extmod/modframebuf.c"
mp_map_elem_t framebuf_locals_dict_table[11];
STATIC MP_DEFINE_CONST_DICT(framebuf_locals_dict, framebuf_locals_dict_table);
mp_map_elem_t framebuf_locals_dict_table[12];
static MP_DEFINE_CONST_DICT(framebuf_locals_dict, framebuf_locals_dict_table);
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
MP_DYNRUNTIME_INIT_ENTRY
@ -30,9 +31,10 @@ mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *a
framebuf_locals_dict_table[5] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_rect), MP_OBJ_FROM_PTR(&framebuf_rect_obj) };
framebuf_locals_dict_table[6] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_line), MP_OBJ_FROM_PTR(&framebuf_line_obj) };
framebuf_locals_dict_table[7] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_ellipse), MP_OBJ_FROM_PTR(&framebuf_ellipse_obj) };
framebuf_locals_dict_table[8] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_blit), MP_OBJ_FROM_PTR(&framebuf_blit_obj) };
framebuf_locals_dict_table[9] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_scroll), MP_OBJ_FROM_PTR(&framebuf_scroll_obj) };
framebuf_locals_dict_table[10] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_text), MP_OBJ_FROM_PTR(&framebuf_text_obj) };
framebuf_locals_dict_table[8] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_poly), MP_OBJ_FROM_PTR(&framebuf_poly_obj) };
framebuf_locals_dict_table[9] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_blit), MP_OBJ_FROM_PTR(&framebuf_blit_obj) };
framebuf_locals_dict_table[10] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_scroll), MP_OBJ_FROM_PTR(&framebuf_scroll_obj) };
framebuf_locals_dict_table[11] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_text), MP_OBJ_FROM_PTR(&framebuf_text_obj) };
MP_OBJ_TYPE_SET_SLOT(&mp_type_framebuf, locals_dict, (void*)&framebuf_locals_dict, 2);
mp_store_global(MP_QSTR_FrameBuffer, MP_OBJ_FROM_PTR(&mp_type_framebuf));

Wyświetl plik

@ -38,10 +38,10 @@ mp_obj_full_type_t re_type;
#include "extmod/modre.c"
mp_map_elem_t match_locals_dict_table[5];
STATIC MP_DEFINE_CONST_DICT(match_locals_dict, match_locals_dict_table);
static MP_DEFINE_CONST_DICT(match_locals_dict, match_locals_dict_table);
mp_map_elem_t re_locals_dict_table[3];
STATIC MP_DEFINE_CONST_DICT(re_locals_dict, re_locals_dict_table);
static MP_DEFINE_CONST_DICT(re_locals_dict, re_locals_dict_table);
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
MP_DYNRUNTIME_INIT_ENTRY

Wyświetl plik

@ -5,7 +5,7 @@
#include "py/mphal.h"
// This is the function which will be called from Python as cexample.add_ints(a, b).
STATIC mp_obj_t example_add_ints(mp_obj_t a_obj, mp_obj_t b_obj) {
static mp_obj_t example_add_ints(mp_obj_t a_obj, mp_obj_t b_obj) {
// Extract the ints from the micropython input objects.
int a = mp_obj_get_int(a_obj);
int b = mp_obj_get_int(b_obj);
@ -14,7 +14,7 @@ STATIC mp_obj_t example_add_ints(mp_obj_t a_obj, mp_obj_t b_obj) {
return mp_obj_new_int(a + b);
}
// Define a Python reference to the function above.
STATIC MP_DEFINE_CONST_FUN_OBJ_2(example_add_ints_obj, example_add_ints);
static MP_DEFINE_CONST_FUN_OBJ_2(example_add_ints_obj, example_add_ints);
// This structure represents Timer instance objects.
typedef struct _example_Timer_obj_t {
@ -28,7 +28,7 @@ typedef struct _example_Timer_obj_t {
// This is the Timer.time() method. After creating a Timer object, this
// can be called to get the time elapsed since creating the Timer.
STATIC mp_obj_t example_Timer_time(mp_obj_t self_in) {
static mp_obj_t example_Timer_time(mp_obj_t self_in) {
// The first argument is self. It is cast to the *example_Timer_obj_t
// type so we can read its attributes.
example_Timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
@ -37,11 +37,11 @@ STATIC mp_obj_t example_Timer_time(mp_obj_t self_in) {
mp_uint_t elapsed = mp_hal_ticks_ms() - self->start_time;
return mp_obj_new_int_from_uint(elapsed);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(example_Timer_time_obj, example_Timer_time);
static MP_DEFINE_CONST_FUN_OBJ_1(example_Timer_time_obj, example_Timer_time);
// This represents Timer.__new__ and Timer.__init__, which is called when
// the user instantiates a Timer object.
STATIC mp_obj_t example_Timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
static mp_obj_t example_Timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// Allocates the new object and sets the type.
example_Timer_obj_t *self = mp_obj_malloc(example_Timer_obj_t, type);
@ -54,10 +54,10 @@ STATIC mp_obj_t example_Timer_make_new(const mp_obj_type_t *type, size_t n_args,
// This collects all methods and other static class attributes of the Timer.
// The table structure is similar to the module table, as detailed below.
STATIC const mp_rom_map_elem_t example_Timer_locals_dict_table[] = {
static const mp_rom_map_elem_t example_Timer_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_time), MP_ROM_PTR(&example_Timer_time_obj) },
};
STATIC MP_DEFINE_CONST_DICT(example_Timer_locals_dict, example_Timer_locals_dict_table);
static MP_DEFINE_CONST_DICT(example_Timer_locals_dict, example_Timer_locals_dict_table);
// This defines the type(Timer) object.
MP_DEFINE_CONST_OBJ_TYPE(
@ -73,12 +73,12 @@ MP_DEFINE_CONST_OBJ_TYPE(
// and the MicroPython object reference.
// All identifiers and strings are written as MP_QSTR_xxx and will be
// optimized to word-sized integers by the build system (interned strings).
STATIC const mp_rom_map_elem_t example_module_globals_table[] = {
static const mp_rom_map_elem_t example_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_cexample) },
{ MP_ROM_QSTR(MP_QSTR_add_ints), MP_ROM_PTR(&example_add_ints_obj) },
{ MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&example_type_Timer) },
};
STATIC MP_DEFINE_CONST_DICT(example_module_globals, example_module_globals_table);
static MP_DEFINE_CONST_DICT(example_module_globals, example_module_globals_table);
// Define module object.
const mp_obj_module_t example_user_cmodule = {

Wyświetl plik

@ -2,18 +2,18 @@
// Define a Python reference to the function we'll make available.
// See example.cpp for the definition.
STATIC MP_DEFINE_CONST_FUN_OBJ_2(cppfunc_obj, cppfunc);
static MP_DEFINE_CONST_FUN_OBJ_2(cppfunc_obj, cppfunc);
// Define all attributes of the module.
// Table entries are key/value pairs of the attribute name (a string)
// and the MicroPython object reference.
// All identifiers and strings are written as MP_QSTR_xxx and will be
// optimized to word-sized integers by the build system (interned strings).
STATIC const mp_rom_map_elem_t cppexample_module_globals_table[] = {
static const mp_rom_map_elem_t cppexample_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_cppexample) },
{ MP_ROM_QSTR(MP_QSTR_cppfunc), MP_ROM_PTR(&cppfunc_obj) },
};
STATIC MP_DEFINE_CONST_DICT(cppexample_module_globals, cppexample_module_globals_table);
static MP_DEFINE_CONST_DICT(cppexample_module_globals, cppexample_module_globals_table);
// Define module object.
const mp_obj_module_t cppexample_user_cmodule = {

Wyświetl plik

@ -2,18 +2,18 @@
#include "py/runtime.h"
// Define example_package.foo.bar.f()
STATIC mp_obj_t example_package_foo_bar_f(void) {
static mp_obj_t example_package_foo_bar_f(void) {
mp_printf(&mp_plat_print, "example_package.foo.bar.f\n");
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(example_package_foo_bar_f_obj, example_package_foo_bar_f);
static MP_DEFINE_CONST_FUN_OBJ_0(example_package_foo_bar_f_obj, example_package_foo_bar_f);
// Define all attributes of the second-level sub-package (example_package.foo.bar).
STATIC const mp_rom_map_elem_t example_package_foo_bar_globals_table[] = {
static const mp_rom_map_elem_t example_package_foo_bar_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_example_package_dot_foo_dot_bar) },
{ MP_ROM_QSTR(MP_QSTR_f), MP_ROM_PTR(&example_package_foo_bar_f_obj) },
};
STATIC MP_DEFINE_CONST_DICT(example_package_foo_bar_globals, example_package_foo_bar_globals_table);
static MP_DEFINE_CONST_DICT(example_package_foo_bar_globals, example_package_foo_bar_globals_table);
// Define example_package.foo.bar module object.
const mp_obj_module_t example_package_foo_bar_user_cmodule = {
@ -22,19 +22,19 @@ const mp_obj_module_t example_package_foo_bar_user_cmodule = {
};
// Define example_package.foo.f()
STATIC mp_obj_t example_package_foo_f(void) {
static mp_obj_t example_package_foo_f(void) {
mp_printf(&mp_plat_print, "example_package.foo.f\n");
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(example_package_foo_f_obj, example_package_foo_f);
static MP_DEFINE_CONST_FUN_OBJ_0(example_package_foo_f_obj, example_package_foo_f);
// Define all attributes of the first-level sub-package (example_package.foo).
STATIC const mp_rom_map_elem_t example_package_foo_globals_table[] = {
static const mp_rom_map_elem_t example_package_foo_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_example_package_dot_foo) },
{ MP_ROM_QSTR(MP_QSTR_bar), MP_ROM_PTR(&example_package_foo_bar_user_cmodule) },
{ MP_ROM_QSTR(MP_QSTR_f), MP_ROM_PTR(&example_package_foo_f_obj) },
};
STATIC MP_DEFINE_CONST_DICT(example_package_foo_globals, example_package_foo_globals_table);
static MP_DEFINE_CONST_DICT(example_package_foo_globals, example_package_foo_globals_table);
// Define example_package.foo module object.
const mp_obj_module_t example_package_foo_user_cmodule = {
@ -43,13 +43,13 @@ const mp_obj_module_t example_package_foo_user_cmodule = {
};
// Define example_package.f()
STATIC mp_obj_t example_package_f(void) {
static mp_obj_t example_package_f(void) {
mp_printf(&mp_plat_print, "example_package.f\n");
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(example_package_f_obj, example_package_f);
static MP_DEFINE_CONST_FUN_OBJ_0(example_package_f_obj, example_package_f);
STATIC mp_obj_t example_package___init__(void) {
static mp_obj_t example_package___init__(void) {
if (!MP_STATE_VM(example_package_initialised)) {
// __init__ for builtins is called each time the module is imported,
// so ensure that initialisation only happens once.
@ -58,20 +58,20 @@ STATIC mp_obj_t example_package___init__(void) {
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(example_package___init___obj, example_package___init__);
static MP_DEFINE_CONST_FUN_OBJ_0(example_package___init___obj, example_package___init__);
// The "initialised" state is stored on mp_state so that it is cleared on soft
// reset.
MP_REGISTER_ROOT_POINTER(int example_package_initialised);
// Define all attributes of the top-level package (example_package).
STATIC const mp_rom_map_elem_t example_package_globals_table[] = {
static const mp_rom_map_elem_t example_package_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_example_package) },
{ MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&example_package___init___obj) },
{ MP_ROM_QSTR(MP_QSTR_foo), MP_ROM_PTR(&example_package_foo_user_cmodule) },
{ MP_ROM_QSTR(MP_QSTR_f), MP_ROM_PTR(&example_package_f_obj) },
};
STATIC MP_DEFINE_CONST_DICT(example_package_globals, example_package_globals_table);
static MP_DEFINE_CONST_DICT(example_package_globals, example_package_globals_table);
// Define module object.
const mp_obj_module_t example_package_user_cmodule = {

Wyświetl plik

@ -164,6 +164,7 @@ def run_until_complete(main_task=None):
dt = max(0, ticks_diff(t.ph_key, ticks()))
elif not _io_queue.map:
# No tasks can be woken so finished running
cur_task = None
return
# print('(poll {})'.format(dt), len(_io_queue.map))
_io_queue.wait_io_event(dt)
@ -188,6 +189,7 @@ def run_until_complete(main_task=None):
assert t.data is None
# This task is done, check if it's the main task and then loop should stop
if t is main_task:
cur_task = None
if isinstance(er, StopIteration):
return er.value
raise er
@ -219,6 +221,11 @@ def run_until_complete(main_task=None):
elif t.state is None:
# Task is already finished and nothing await'ed on the task,
# so call the exception handler.
# Save exception raised by the coro for later use.
t.data = exc
# Create exception context and call the exception handler.
_exc_context["exception"] = exc
_exc_context["future"] = t
Loop.call_exception_handler(_exc_context)
@ -237,6 +244,7 @@ async def _stopper():
pass
cur_task = None
_stop_task = None
@ -286,6 +294,8 @@ def get_event_loop(runq_len=0, waitq_len=0):
def current_task():
if cur_task is None:
raise RuntimeError("no running event loop")
return cur_task

Wyświetl plik

@ -63,9 +63,6 @@ class _Remove:
# async
def gather(*aws, return_exceptions=False):
if not aws:
return []
def done(t, er):
# Sub-task "t" has finished, with exception "er".
nonlocal state
@ -86,26 +83,39 @@ def gather(*aws, return_exceptions=False):
# Gather waiting is done, schedule the main gather task.
core._task_queue.push(gather_task)
# Prepare the sub-tasks for the gather.
# The `state` variable counts the number of tasks to wait for, and can be negative
# if the gather should not run at all (because a task already had an exception).
ts = [core._promote_to_task(aw) for aw in aws]
state = 0
for i in range(len(ts)):
if ts[i].state is not True:
# Task is not running, gather not currently supported for this case.
if ts[i].state is True:
# Task is running, register the callback to call when the task is done.
ts[i].state = done
state += 1
elif not ts[i].state:
# Task finished already.
if not isinstance(ts[i].data, StopIteration):
# Task finished by raising an exception.
if not return_exceptions:
# Do not run this gather at all.
state = -len(ts)
else:
# Task being waited on, gather not currently supported for this case.
raise RuntimeError("can't gather")
# Register the callback to call when the task is done.
ts[i].state = done
# Set the state for execution of the gather.
gather_task = core.cur_task
state = len(ts)
cancel_all = False
# Wait for the a sub-task to need attention.
gather_task.data = _Remove
try:
yield
except core.CancelledError as er:
cancel_all = True
state = er
# Wait for a sub-task to need attention (if there are any to wait for).
if state > 0:
gather_task.data = _Remove
try:
yield
except core.CancelledError as er:
cancel_all = True
state = er
# Clean up tasks.
for i in range(len(ts)):
@ -118,8 +128,13 @@ def gather(*aws, return_exceptions=False):
# Sub-task ran to completion, get its return value.
ts[i] = ts[i].data.value
else:
# Sub-task had an exception with return_exceptions==True, so get its exception.
ts[i] = ts[i].data
# Sub-task had an exception.
if return_exceptions:
# Get the sub-task exception to return in the list of return values.
ts[i] = ts[i].data
elif isinstance(state, int):
# Raise the sub-task exception, if there is not already an exception to raise.
state = ts[i].data
# Either this gather was cancelled, or one of the sub-tasks raised an exception with
# return_exceptions==False, so reraise the exception here.

Wyświetl plik

@ -46,7 +46,7 @@
#define CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME ""
#undef CONFIG_SSL_HAS_PEM
#undef CONFIG_SSL_USE_PKCS12
#define CONFIG_SSL_EXPIRY_TIME
#define CONFIG_SSL_EXPIRY_TIME
#define CONFIG_X509_MAX_CA_CERTS 0
#define CONFIG_SSL_MAX_CERTS 3
#undef CONFIG_SSL_CTX_MUTEXING
@ -58,11 +58,11 @@
#undef CONFIG_AXTLSWRAP
#undef CONFIG_AXHTTPD
#undef CONFIG_HTTP_STATIC_BUILD
#define CONFIG_HTTP_PORT
#define CONFIG_HTTP_HTTPS_PORT
#define CONFIG_HTTP_SESSION_CACHE_SIZE
#define CONFIG_HTTP_PORT
#define CONFIG_HTTP_HTTPS_PORT
#define CONFIG_HTTP_SESSION_CACHE_SIZE
#define CONFIG_HTTP_WEBROOT ""
#define CONFIG_HTTP_TIMEOUT
#define CONFIG_HTTP_TIMEOUT
#undef CONFIG_HTTP_HAS_CGI
#define CONFIG_HTTP_CGI_EXTENSIONS ""
#undef CONFIG_HTTP_ENABLE_LUA
@ -107,8 +107,8 @@
#undef CONFIG_BIGINT_BARRETT
#undef CONFIG_BIGINT_CRT
#undef CONFIG_BIGINT_KARATSUBA
#define MUL_KARATSUBA_THRESH
#define SQU_KARATSUBA_THRESH
#define MUL_KARATSUBA_THRESH
#define SQU_KARATSUBA_THRESH
#undef CONFIG_BIGINT_SLIDING_WINDOW
#undef CONFIG_BIGINT_SQUARE
#undef CONFIG_BIGINT_CHECK_ON

Wyświetl plik

@ -0,0 +1,16 @@
// Berkeley-db configuration.
#define __DBINTERFACE_PRIVATE 1
#define mpool_error printf
#define abort abort_
#define virt_fd_t void*
#ifdef MICROPY_BERKELEY_DB_DEFPSIZE
#define DEFPSIZE MICROPY_BERKELEY_DB_DEFPSIZE
#endif
#ifdef MICROPY_BERKELEY_DB_MINCACHE
#define MINCACHE MICROPY_BERKELEY_DB_MINCACHE
#endif
__attribute__((noreturn)) void abort_(void);

Wyświetl plik

@ -48,17 +48,17 @@
// interface to an HCI UART provided by the port.
// We pass the bytes directly to the UART during a send, but then notify btstack in the next poll.
STATIC bool send_done;
STATIC void (*send_handler)(void);
static bool send_done;
static void (*send_handler)(void);
// btstack issues a read of len bytes, and gives us a buffer to asynchronously fill up.
STATIC uint8_t *recv_buf;
STATIC size_t recv_len;
STATIC size_t recv_idx;
STATIC void (*recv_handler)(void);
STATIC bool init_success = false;
static uint8_t *recv_buf;
static size_t recv_len;
static size_t recv_idx;
static void (*recv_handler)(void);
static bool init_success = false;
STATIC int btstack_uart_init(const btstack_uart_config_t *uart_config) {
static int btstack_uart_init(const btstack_uart_config_t *uart_config) {
(void)uart_config;
send_done = false;
@ -81,45 +81,45 @@ STATIC int btstack_uart_init(const btstack_uart_config_t *uart_config) {
return 0;
}
STATIC int btstack_uart_open(void) {
static int btstack_uart_open(void) {
return init_success ? 0 : 1;
}
STATIC int btstack_uart_close(void) {
static int btstack_uart_close(void) {
mp_bluetooth_hci_controller_deinit();
mp_bluetooth_hci_uart_deinit();
return 0;
}
STATIC void btstack_uart_set_block_received(void (*block_handler)(void)) {
static void btstack_uart_set_block_received(void (*block_handler)(void)) {
recv_handler = block_handler;
}
STATIC void btstack_uart_set_block_sent(void (*block_handler)(void)) {
static void btstack_uart_set_block_sent(void (*block_handler)(void)) {
send_handler = block_handler;
}
STATIC int btstack_uart_set_baudrate(uint32_t baudrate) {
static int btstack_uart_set_baudrate(uint32_t baudrate) {
mp_bluetooth_hci_uart_set_baudrate(baudrate);
return 0;
}
STATIC int btstack_uart_set_parity(int parity) {
static int btstack_uart_set_parity(int parity) {
(void)parity;
return 0;
}
STATIC int btstack_uart_set_flowcontrol(int flowcontrol) {
static int btstack_uart_set_flowcontrol(int flowcontrol) {
(void)flowcontrol;
return 0;
}
STATIC void btstack_uart_receive_block(uint8_t *buf, uint16_t len) {
static void btstack_uart_receive_block(uint8_t *buf, uint16_t len) {
recv_buf = buf;
recv_len = len;
}
STATIC void btstack_uart_send_block(const uint8_t *buf, uint16_t len) {
static void btstack_uart_send_block(const uint8_t *buf, uint16_t len) {
#if HCI_TRACE
printf(COL_GREEN "< [% 8d] %02x", (int)mp_hal_ticks_ms(), buf[0]);
for (size_t i = 1; i < len; ++i) {
@ -136,16 +136,16 @@ STATIC void btstack_uart_send_block(const uint8_t *buf, uint16_t len) {
mp_bluetooth_hci_poll_now();
}
STATIC int btstack_uart_get_supported_sleep_modes(void) {
static int btstack_uart_get_supported_sleep_modes(void) {
return 0;
}
STATIC void btstack_uart_set_sleep(btstack_uart_sleep_mode_t sleep_mode) {
static void btstack_uart_set_sleep(btstack_uart_sleep_mode_t sleep_mode) {
(void)sleep_mode;
// printf("btstack_uart_set_sleep %u\n", sleep_mode);
}
STATIC void btstack_uart_set_wakeup_handler(void (*wakeup_handler)(void)) {
static void btstack_uart_set_wakeup_handler(void (*wakeup_handler)(void)) {
(void)wakeup_handler;
// printf("btstack_uart_set_wakeup_handler\n");
}

Wyświetl plik

@ -43,24 +43,24 @@
// How long to wait for a controller to init/deinit.
// Some controllers can take up to 5-6 seconds in normal operation.
STATIC const uint32_t BTSTACK_INIT_DEINIT_TIMEOUT_MS = 15000;
static const uint32_t BTSTACK_INIT_DEINIT_TIMEOUT_MS = 15000;
// We need to know the attribute handle for the GAP device name (see GAP_DEVICE_NAME_UUID)
// so it can be put into the gatts_db before registering the services, and accessed
// efficiently when requesting an attribute in att_read_callback. Because this is the
// first characteristic of the first service, it always has a handle value of 3.
STATIC const uint16_t BTSTACK_GAP_DEVICE_NAME_HANDLE = 3;
static const uint16_t BTSTACK_GAP_DEVICE_NAME_HANDLE = 3;
volatile int mp_bluetooth_btstack_state = MP_BLUETOOTH_BTSTACK_STATE_OFF;
// sm_set_authentication_requirements is set-only, so cache current value.
#if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING
STATIC uint8_t mp_bluetooth_btstack_sm_auth_req = 0;
static uint8_t mp_bluetooth_btstack_sm_auth_req = 0;
#endif
#define ERRNO_BLUETOOTH_NOT_ACTIVE MP_ENODEV
STATIC int btstack_error_to_errno(int err) {
static int btstack_error_to_errno(int err) {
DEBUG_printf(" --> btstack error: %d\n", err);
if (err == ERROR_CODE_SUCCESS) {
return 0;
@ -78,7 +78,7 @@ STATIC int btstack_error_to_errno(int err) {
}
#if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE
STATIC mp_obj_bluetooth_uuid_t create_mp_uuid(uint16_t uuid16, const uint8_t *uuid128) {
static mp_obj_bluetooth_uuid_t create_mp_uuid(uint16_t uuid16, const uint8_t *uuid128) {
mp_obj_bluetooth_uuid_t result;
result.base.type = &mp_type_bluetooth_uuid;
if (uuid16 != 0) {
@ -107,7 +107,7 @@ typedef struct _mp_btstack_active_connection_t {
size_t pending_write_value_len;
} mp_btstack_active_connection_t;
STATIC mp_btstack_active_connection_t *create_active_connection(uint16_t conn_handle) {
static mp_btstack_active_connection_t *create_active_connection(uint16_t conn_handle) {
DEBUG_printf("create_active_connection: conn_handle=%d\n", conn_handle);
mp_btstack_active_connection_t *conn = m_new(mp_btstack_active_connection_t, 1);
conn->conn_handle = conn_handle;
@ -120,7 +120,7 @@ STATIC mp_btstack_active_connection_t *create_active_connection(uint16_t conn_ha
return conn;
}
STATIC mp_btstack_active_connection_t *find_active_connection(uint16_t conn_handle) {
static mp_btstack_active_connection_t *find_active_connection(uint16_t conn_handle) {
DEBUG_printf("find_active_connection: conn_handle=%d\n", conn_handle);
btstack_linked_list_iterator_t it;
btstack_linked_list_iterator_init(&it, &MP_STATE_PORT(bluetooth_btstack_root_pointers)->active_connections);
@ -135,7 +135,7 @@ STATIC mp_btstack_active_connection_t *find_active_connection(uint16_t conn_hand
return conn;
}
STATIC void remove_active_connection(uint16_t conn_handle) {
static void remove_active_connection(uint16_t conn_handle) {
DEBUG_printf("remove_active_connection: conn_handle=%d\n", conn_handle);
mp_btstack_active_connection_t *conn = find_active_connection(conn_handle);
if (conn) {
@ -149,7 +149,7 @@ STATIC void remove_active_connection(uint16_t conn_handle) {
// This needs to be separate to btstack_packet_handler otherwise we get
// dual-delivery of the HCI_EVENT_LE_META event.
STATIC void btstack_packet_handler_att_server(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
static void btstack_packet_handler_att_server(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
DEBUG_printf("btstack_packet_handler_att_server(packet_type=%u, packet=%p)\n", packet_type, packet);
@ -187,13 +187,13 @@ STATIC void btstack_packet_handler_att_server(uint8_t packet_type, uint16_t chan
#if MICROPY_BLUETOOTH_USE_ZEPHYR_STATIC_ADDRESS
// During startup, the controller (e.g. Zephyr) might give us a static address that we can use.
STATIC uint8_t controller_static_addr[6] = {0};
STATIC bool controller_static_addr_available = false;
static uint8_t controller_static_addr[6] = {0};
static bool controller_static_addr_available = false;
STATIC const uint8_t read_static_address_command_complete_prefix[] = { 0x0e, 0x1b, 0x01, 0x09, 0xfc };
static const uint8_t read_static_address_command_complete_prefix[] = { 0x0e, 0x1b, 0x01, 0x09, 0xfc };
#endif
STATIC void btstack_packet_handler_generic(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
static void btstack_packet_handler_generic(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
DEBUG_printf("btstack_packet_handler_generic(packet_type=%u, packet=%p)\n", packet_type, packet);
@ -372,13 +372,13 @@ STATIC void btstack_packet_handler_generic(uint8_t packet_type, uint16_t channel
}
}
STATIC btstack_packet_callback_registration_t hci_event_callback_registration = {
static btstack_packet_callback_registration_t hci_event_callback_registration = {
.callback = &btstack_packet_handler_generic
};
#if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT
// For when the handler is being used for service discovery.
STATIC void btstack_packet_handler_discover_services(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
static void btstack_packet_handler_discover_services(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
if (packet_type != HCI_EVENT_PACKET) {
@ -401,7 +401,7 @@ STATIC void btstack_packet_handler_discover_services(uint8_t packet_type, uint16
}
// For when the handler is being used for characteristic discovery.
STATIC void btstack_packet_handler_discover_characteristics(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
static void btstack_packet_handler_discover_characteristics(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
if (packet_type != HCI_EVENT_PACKET) {
@ -424,7 +424,7 @@ STATIC void btstack_packet_handler_discover_characteristics(uint8_t packet_type,
}
// For when the handler is being used for descriptor discovery.
STATIC void btstack_packet_handler_discover_descriptors(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
static void btstack_packet_handler_discover_descriptors(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
if (packet_type != HCI_EVENT_PACKET) {
@ -447,7 +447,7 @@ STATIC void btstack_packet_handler_discover_descriptors(uint8_t packet_type, uin
}
// For when the handler is being used for a read query.
STATIC void btstack_packet_handler_read(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
static void btstack_packet_handler_read(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
if (packet_type != HCI_EVENT_PACKET) {
@ -462,8 +462,9 @@ STATIC void btstack_packet_handler_read(uint8_t packet_type, uint16_t channel, u
if (!conn) {
return;
}
mp_bluetooth_gattc_on_read_write_status(MP_BLUETOOTH_IRQ_GATTC_READ_DONE, conn_handle, conn->pending_value_handle, status);
uint16_t value_handle = conn->pending_value_handle;
conn->pending_value_handle = 0xffff;
mp_bluetooth_gattc_on_read_write_status(MP_BLUETOOTH_IRQ_GATTC_READ_DONE, conn_handle, value_handle, status);
} else if (event_type == GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT) {
DEBUG_printf(" --> gatt characteristic value query result\n");
uint16_t conn_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
@ -475,7 +476,7 @@ STATIC void btstack_packet_handler_read(uint8_t packet_type, uint16_t channel, u
}
// For when the handler is being used for write-with-response.
STATIC void btstack_packet_handler_write_with_response(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
static void btstack_packet_handler_write_with_response(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel;
(void)size;
if (packet_type != HCI_EVENT_PACKET) {
@ -490,18 +491,19 @@ STATIC void btstack_packet_handler_write_with_response(uint8_t packet_type, uint
if (!conn) {
return;
}
mp_bluetooth_gattc_on_read_write_status(MP_BLUETOOTH_IRQ_GATTC_WRITE_DONE, conn_handle, conn->pending_value_handle, status);
uint16_t value_handle = conn->pending_value_handle;
conn->pending_value_handle = 0xffff;
m_del(uint8_t, conn->pending_write_value, conn->pending_write_value_len);
conn->pending_write_value = NULL;
conn->pending_write_value_len = 0;
mp_bluetooth_gattc_on_read_write_status(MP_BLUETOOTH_IRQ_GATTC_WRITE_DONE, conn_handle, value_handle, status);
}
}
#endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT
STATIC btstack_timer_source_t btstack_init_deinit_timeout;
static btstack_timer_source_t btstack_init_deinit_timeout;
STATIC void btstack_init_deinit_timeout_handler(btstack_timer_source_t *ds) {
static void btstack_init_deinit_timeout_handler(btstack_timer_source_t *ds) {
(void)ds;
// Stop waiting for initialisation.
@ -511,13 +513,13 @@ STATIC void btstack_init_deinit_timeout_handler(btstack_timer_source_t *ds) {
}
#if !MICROPY_BLUETOOTH_USE_MP_HAL_GET_MAC_STATIC_ADDRESS
STATIC void btstack_static_address_ready(void *arg) {
static void btstack_static_address_ready(void *arg) {
DEBUG_printf("btstack_static_address_ready.\n");
*(volatile bool *)arg = true;
}
#endif
STATIC bool set_public_address(void) {
static bool set_public_address(void) {
bd_addr_t local_addr;
gap_local_bd_addr(local_addr);
bd_addr_t null_addr = {0};
@ -530,7 +532,7 @@ STATIC bool set_public_address(void) {
return true;
}
STATIC void set_random_address(void) {
static void set_random_address(void) {
#if MICROPY_BLUETOOTH_USE_ZEPHYR_STATIC_ADDRESS
if (controller_static_addr_available) {
DEBUG_printf("set_random_address: Using static address supplied by controller.\n");
@ -579,7 +581,7 @@ STATIC void set_random_address(void) {
DEBUG_printf("set_random_address: Address loaded by controller\n");
}
STATIC void deinit_stack(void) {
static void deinit_stack(void) {
mp_bluetooth_btstack_state = MP_BLUETOOTH_BTSTACK_STATE_OFF;
// Deinitialise BTstack components.
@ -899,7 +901,7 @@ int mp_bluetooth_gatts_register_service_begin(bool append) {
return 0;
}
STATIC uint16_t att_read_callback(hci_con_handle_t connection_handle, uint16_t att_handle, uint16_t offset, uint8_t *buffer, uint16_t buffer_size) {
static uint16_t att_read_callback(hci_con_handle_t connection_handle, uint16_t att_handle, uint16_t offset, uint8_t *buffer, uint16_t buffer_size) {
// Should return data length, 0 for error, or -1 for delayed response.
// For more details search "*att_read_callback*" in micropython/lib/btstack/doc/manual/docs/profiles.md
(void)connection_handle;
@ -924,7 +926,7 @@ STATIC uint16_t att_read_callback(hci_con_handle_t connection_handle, uint16_t a
return ret;
}
STATIC int att_write_callback(hci_con_handle_t connection_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size) {
static int att_write_callback(hci_con_handle_t connection_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size) {
(void)offset;
(void)transaction_mode;
DEBUG_printf("att_write_callback (handle: %u, mode: %u, offset: %u, buffer: %p, size: %u)\n", att_handle, transaction_mode, offset, buffer, buffer_size);
@ -951,12 +953,12 @@ STATIC int att_write_callback(hci_con_handle_t connection_handle, uint16_t att_h
return 0;
}
STATIC inline uint16_t get_uuid16(const mp_obj_bluetooth_uuid_t *uuid) {
static inline uint16_t get_uuid16(const mp_obj_bluetooth_uuid_t *uuid) {
return (uuid->data[1] << 8) | uuid->data[0];
}
// Map MP_BLUETOOTH_CHARACTERISTIC_FLAG_ values to btstack read/write permission values.
STATIC void get_characteristic_permissions(uint16_t flags, uint16_t *read_permission, uint16_t *write_permission) {
static void get_characteristic_permissions(uint16_t flags, uint16_t *read_permission, uint16_t *write_permission) {
if (flags & MP_BLUETOOTH_CHARACTERISTIC_FLAG_READ_ENCRYPTED) {
*read_permission = ATT_SECURITY_ENCRYPTED;
} else if (flags & MP_BLUETOOTH_CHARACTERISTIC_FLAG_READ_AUTHENTICATED) {
@ -1128,7 +1130,7 @@ typedef struct {
// Called in response to a gatts_notify/indicate being unable to complete, which then calls
// att_server_request_to_send_notification.
STATIC void btstack_notify_indicate_ready_handler(void *context) {
static void btstack_notify_indicate_ready_handler(void *context) {
MICROPY_PY_BLUETOOTH_ENTER
notify_indicate_pending_op_t *pending_op = (notify_indicate_pending_op_t *)context;
DEBUG_printf("btstack_notify_indicate_ready_handler gatts_op=%d conn_handle=%d value_handle=%d len=%lu\n", pending_op->gatts_op, pending_op->conn_handle, pending_op->value_handle, pending_op->value_len);
@ -1268,9 +1270,9 @@ int mp_bluetooth_gap_passkey(uint16_t conn_handle, uint8_t action, mp_int_t pass
#endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING
#if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE
STATIC btstack_timer_source_t scan_duration_timeout;
static btstack_timer_source_t scan_duration_timeout;
STATIC void scan_duration_timeout_handler(btstack_timer_source_t *ds) {
static void scan_duration_timeout_handler(btstack_timer_source_t *ds) {
(void)ds;
mp_bluetooth_gap_scan_stop();
}

Wyświetl plik

@ -18,6 +18,7 @@ set(MICROPY_SOURCE_EXTMOD
${MICROPY_EXTMOD_DIR}/machine_signal.c
${MICROPY_EXTMOD_DIR}/machine_spi.c
${MICROPY_EXTMOD_DIR}/machine_uart.c
${MICROPY_EXTMOD_DIR}/machine_usb_device.c
${MICROPY_EXTMOD_DIR}/machine_wdt.c
${MICROPY_EXTMOD_DIR}/modbluetooth.c
${MICROPY_EXTMOD_DIR}/modframebuf.c
@ -39,9 +40,10 @@ set(MICROPY_SOURCE_EXTMOD
${MICROPY_EXTMOD_DIR}/modre.c
${MICROPY_EXTMOD_DIR}/modselect.c
${MICROPY_EXTMOD_DIR}/modsocket.c
${MICROPY_EXTMOD_DIR}/modssl_axtls.c
${MICROPY_EXTMOD_DIR}/modssl_mbedtls.c
${MICROPY_EXTMOD_DIR}/modtls_axtls.c
${MICROPY_EXTMOD_DIR}/modtls_mbedtls.c
${MICROPY_EXTMOD_DIR}/modtime.c
${MICROPY_EXTMOD_DIR}/modvfs.c
${MICROPY_EXTMOD_DIR}/modwebsocket.c
${MICROPY_EXTMOD_DIR}/modwebrepl.c
${MICROPY_EXTMOD_DIR}/network_cyw43.c
@ -130,27 +132,27 @@ if(MICROPY_PY_BTREE)
)
target_include_directories(micropy_extmod_btree PRIVATE
${MICROPY_LIB_BERKELEY_DIR}/PORT/include
${MICROPY_LIB_BERKELEY_DIR}/include
)
if(NOT BERKELEY_DB_CONFIG_FILE)
set(BERKELEY_DB_CONFIG_FILE "${MICROPY_DIR}/extmod/berkeley-db/berkeley_db_config_port.h")
endif()
target_compile_definitions(micropy_extmod_btree PRIVATE
__DBINTERFACE_PRIVATE=1
mpool_error=printf
abort=abort_
"virt_fd_t=void*"
BERKELEY_DB_CONFIG_FILE="${BERKELEY_DB_CONFIG_FILE}"
)
# The include directories and compile definitions below are needed to build
# modbtree.c and should be added to the main MicroPython target.
list(APPEND MICROPY_INC_CORE
"${MICROPY_LIB_BERKELEY_DIR}/PORT/include"
"${MICROPY_LIB_BERKELEY_DIR}/include"
)
list(APPEND MICROPY_DEF_CORE
MICROPY_PY_BTREE=1
__DBINTERFACE_PRIVATE=1
"virt_fd_t=void*"
BERKELEY_DB_CONFIG_FILE="${BERKELEY_DB_CONFIG_FILE}"
)
list(APPEND MICROPY_SOURCE_EXTMOD
@ -174,20 +176,24 @@ if(MICROPY_SSL_MBEDTLS)
${MICROPY_DIR}/lib/mbedtls_errors/mp_mbedtls_errors.c
${MICROPY_LIB_MBEDTLS_DIR}/library/aes.c
${MICROPY_LIB_MBEDTLS_DIR}/library/aesni.c
${MICROPY_LIB_MBEDTLS_DIR}/library/arc4.c
${MICROPY_LIB_MBEDTLS_DIR}/library/asn1parse.c
${MICROPY_LIB_MBEDTLS_DIR}/library/asn1write.c
${MICROPY_LIB_MBEDTLS_DIR}/library/base64.c
${MICROPY_LIB_MBEDTLS_DIR}/library/bignum_core.c
${MICROPY_LIB_MBEDTLS_DIR}/library/bignum_mod.c
${MICROPY_LIB_MBEDTLS_DIR}/library/bignum_mod_raw.c
${MICROPY_LIB_MBEDTLS_DIR}/library/bignum.c
${MICROPY_LIB_MBEDTLS_DIR}/library/blowfish.c
${MICROPY_LIB_MBEDTLS_DIR}/library/camellia.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ccm.c
${MICROPY_LIB_MBEDTLS_DIR}/library/certs.c
${MICROPY_LIB_MBEDTLS_DIR}/library/chacha20.c
${MICROPY_LIB_MBEDTLS_DIR}/library/chachapoly.c
${MICROPY_LIB_MBEDTLS_DIR}/library/cipher.c
${MICROPY_LIB_MBEDTLS_DIR}/library/cipher_wrap.c
${MICROPY_LIB_MBEDTLS_DIR}/library/nist_kw.c
${MICROPY_LIB_MBEDTLS_DIR}/library/aria.c
${MICROPY_LIB_MBEDTLS_DIR}/library/cmac.c
${MICROPY_LIB_MBEDTLS_DIR}/library/mps_reader.c
${MICROPY_LIB_MBEDTLS_DIR}/library/mps_trace.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ctr_drbg.c
${MICROPY_LIB_MBEDTLS_DIR}/library/debug.c
${MICROPY_LIB_MBEDTLS_DIR}/library/des.c
@ -200,17 +206,13 @@ if(MICROPY_SSL_MBEDTLS)
${MICROPY_LIB_MBEDTLS_DIR}/library/entropy.c
${MICROPY_LIB_MBEDTLS_DIR}/library/entropy_poll.c
${MICROPY_LIB_MBEDTLS_DIR}/library/gcm.c
${MICROPY_LIB_MBEDTLS_DIR}/library/havege.c
${MICROPY_LIB_MBEDTLS_DIR}/library/hmac_drbg.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md2.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md4.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md5.c
${MICROPY_LIB_MBEDTLS_DIR}/library/md.c
${MICROPY_LIB_MBEDTLS_DIR}/library/oid.c
${MICROPY_LIB_MBEDTLS_DIR}/library/padlock.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pem.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pk.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkcs11.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkcs12.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkcs5.c
${MICROPY_LIB_MBEDTLS_DIR}/library/pkparse.c
@ -221,15 +223,17 @@ if(MICROPY_SSL_MBEDTLS)
${MICROPY_LIB_MBEDTLS_DIR}/library/poly1305.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ripemd160.c
${MICROPY_LIB_MBEDTLS_DIR}/library/rsa.c
${MICROPY_LIB_MBEDTLS_DIR}/library/rsa_internal.c
${MICROPY_LIB_MBEDTLS_DIR}/library/rsa_alt_helpers.c
${MICROPY_LIB_MBEDTLS_DIR}/library/sha1.c
${MICROPY_LIB_MBEDTLS_DIR}/library/sha256.c
${MICROPY_LIB_MBEDTLS_DIR}/library/sha512.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_cache.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_ciphersuites.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_cli.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_tls12_client.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_tls12_server.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_client.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_cookie.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_srv.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_debug_helpers_generated.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_msg.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_ticket.c
${MICROPY_LIB_MBEDTLS_DIR}/library/ssl_tls.c
@ -242,11 +246,10 @@ if(MICROPY_SSL_MBEDTLS)
${MICROPY_LIB_MBEDTLS_DIR}/library/x509_csr.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509write_crt.c
${MICROPY_LIB_MBEDTLS_DIR}/library/x509write_csr.c
${MICROPY_LIB_MBEDTLS_DIR}/library/xtea.c
)
if(NOT MBEDTLS_CONFIG_FILE)
set(MBEDTLS_CONFIG_FILE "${MICROPY_PORT_DIR}/mbedtls/mbedtls_config.h")
set(MBEDTLS_CONFIG_FILE "${MICROPY_PORT_DIR}/mbedtls/mbedtls_config_port.h")
endif()
target_compile_definitions(micropy_lib_mbedtls INTERFACE

Some files were not shown because too many files have changed in this diff Show More