Porównaj commity

...

652 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
Damien George 9feb0689ee all: Bump version to 1.22.0.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-27 15:35:31 +11:00
Daniël van de Giessen d014c82826 extmod/nimble: Do not set GAP device name after sync.
Instead, configure the default once at compile-time. This means the GAP
name will no longer be set to default after re-initializing Bluetooth.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-12-22 16:07:02 +11:00
Damien George 0b2676db5c lib/micropython-lib: Update submodule to latest.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-22 14:18:09 +11:00
Nicko van Someren cfc212b108 rp2/rp2_dma: Introduce a new rp2.DMA class for control over DMA xfers.
This commit implements fairly complete support for the DMA controller in
the rp2 series of microcontrollers.  It provides a class for accessing the
DMA channels through a high-level, Pythonic interface, and functions for
setting and manipulating the DMA channel configurations.

Creating an instance of the rp2.DMA class claims one of the processor's DMA
channels.  A sensible, per-channel default value for the ctrl register can
be fetched from the DMA.pack_ctrl() function, and the components of this
register can be set via keyword arguments to pack_ctrl().

The read, write, count and ctrl attributes of the DMA class provide
read/write access to the respective registers of the DMA controller.  The
config() method allows any or all of these values to be set simultaneously
and adds a trigger keyword argument to allow the setup to immediately be
triggered.  The read and write attributes (or keywords in config()) accept
either actual addresses or any object that supports the buffer interface.
The active() method provides read/write control of the channel's activity,
allowing the user to start and stop the channel and test if it is running.

Standard MicroPython interrupt handlers are supported through the irq()
method and the channel can be released either by deleting it and allowing
it to be garbage-collected or with the explicit close() method.

Direct, unfettered access to the DMA controllers registers is provided
through a proxy memoryview() object returned by the DMA.registers attribute
that maps directly onto the memory-mapped registers.  This is necessary for
more fine-grained control and is helpful for allowing chaining of DMA
channels.

As a simple example, using DMA to do a fast memory copy just needs:

    src = bytearray(32*1024)
    dest = bytearray(32*1024)
    dma = rp2.DMA()
    dma.config(read=src, write=dest, count=len(src) // 4,
        ctrl=dma.pack_ctrl(), trigger=True)

    # Wait for completion
    while dma.active():
        pass

This API aims to strike a balance between simplicity and comprehensiveness.

Signed-off-by: Nicko van Someren <nicko@nicko.org>
Signed-off-by: Damien George <damien@micropython.org>
2023-12-22 13:04:51 +11:00
Sebastian Romero e4d3ab3304 nrf/main: Add /flash and /flash/lib to sys.path.
This allows to follow good practice and have libraries live in the lib
folder which means they will be found by the runtime without adding this
path manually at runtime.

Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2023-12-22 11:15:19 +11:00
Peter Züger d69e69adb6 py/mkrules.mk: Fix dependency file generation for compiler wrappers.
When compiling with distcc, it does not understand the -MD flag on its own.
This fixes the interaction by explicitly adding the -MF option.

The error in distcc is described here under "Problems with gcc -MD":
https://www.distcc.org/faq.html

Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2023-12-22 11:07:59 +11:00
Peter Züger ce42c9ee16 extmod/vfs_lfs: Fix lfs cache_size calculation.
The calculation of the lfs2 cache_size was incorrect, the maximum allowed
size is block_size.

The cache size must be: "a multiple of the read and program sizes, and a
factor of the block size".

Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2023-12-22 11:03:23 +11:00
Maarten van der Schrieck 3bca93b2d0 ports: Fix sys.stdout.buffer.write() return value.
MicroPython code may rely on the return value of sys.stdout.buffer.write()
to reflect the number of bytes actually written. While in most scenarios a
write() operation is successful, there are cases where it fails, leading to
data loss. This problem arises because, currently, write() merely returns
the number of bytes it was supposed to write, without indication of
failure.

One scenario where write() might fail, is where USB is used and the
receiving end doesn't read quickly enough to empty the receive buffer. In
that case, write() on the MicroPython side can timeout, resulting in the
loss of data without any indication, a behavior observed notably in
communication between a Pi Pico as a client and a Linux host using the ACM
driver.

A complex issue arises with mp_hal_stdout_tx_strn() when it involves
multiple outputs, such as USB, dupterm and hardware UART. The challenge is
in handling cases where writing to one output is successful, but another
fails, either fully or partially. This patch implements the following
solution:

mp_hal_stdout_tx_strn() attempts to write len bytes to all of the possible
destinations for that data, and returns the minimum successful write
length.

The implementation of this is complicated by several factors:
- multiple outputs may be enabled or disabled at compiled time
- multiple outputs may be enabled or disabled at runtime
- mp_os_dupterm_tx_strn() is one such output, optionally containing
  multiple additional outputs
- each of these outputs may or may not be able to report success
- each of these outputs may or may not be able to report partial writes

As a result, there's no single strategy that fits all ports, necessitating
unique logic for each instance of mp_hal_stdout_tx_strn().

Note that addressing sys.stdout.write() is more complex due to its data
modification process ("cooked" output), and it remains unchanged in this
patch. Developers who are concerned about accurate return values from
write operations should use sys.stdout.buffer.write().

This patch might disrupt some existing code, but it's also expected to
resolve issues, considering that the peculiar return value behavior of
sys.stdout.buffer.write() is not well-documented and likely not widely
known. Therefore, it's improbable that much existing code relies on the
previous behavior.

Signed-off-by: Maarten van der Schrieck <maarten@thingsconnected.nl>
2023-12-22 10:32:46 +11:00
Maarten van der Schrieck 91ee8ac894 extmod/os_dupterm: Let mp_os_dupterm_tx_strn() return num bytes written.
In case of multiple outputs, the minimum successful write length is
returned.  In line with this, in case any output has a write error, zero is
returned.

In case of no outputs, -1 is returned.

The return value can be used to assess whether writes were attempted, and
if so, whether they succeeded.

Signed-off-by: Maarten van der Schrieck <maarten@thingsconnected.nl>
2023-12-22 10:26:52 +11:00
Jim Mussared 5d28bb4adb tools/manifestfile.py: Add support for external libraries.
This adds a `add_library(name, path)` method for use in manifest.py that
allows registering an external path (e.g. to another repo) by name.

This name can then be passed to `require("package", library="name")` to
reference packages in that repo/library rather than micropython-lib.

Within the external library, `require()` continues to work as normal
(referencing micropython-lib) by default, but they can also specify the
library name to require another package from that repo/library.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-12-21 15:28:32 +11:00
IhorNehrutsa 5552896ca8 esp32/mpconfigport: Enable MICROPY_PY_HASHLIB_MD5.
Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-21 11:33:05 +11:00
IhorNehrutsa b31eef6094 extmod/modhashlib: Support MD5 with mbedtls 3.x.
This change was missd in e7ae3ad92d.

Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-21 11:30:52 +11:00
Jim Mussared 74fd7b3d32 tools/ci.sh: Set `ulimit -n` for unix CI.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-12-21 11:05:31 +11:00
Jim Mussared 8b24aa36ba extmod/modselect: Handle growing the pollfds allocation correctly.
The poll_obj_t instances have their pollfd field point into this
allocation.  So if re-allocating results in a move, we need to update the
existing poll_obj_t's.

Update the test to cover this case.

Fixes issue #12887.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-12-21 11:04:59 +11:00
Damien George e9bcd49b3e stm32/mboot: Add support for Microsoft WCID.
This adds support to stm32's mboot for the Microsoft WCID USB 0xee string
and Compatible ID Feature Descriptor.  This allows the USB device to
automatically set the default USB driver, so that when the device is
plugged in Windows will assign the winusb driver to it.  This means that
USB DFU mode can be used without installing any drivers.

For example this page will work (allow the board to be updated over DFU)
with zero install: https://devanlai.github.io/webdfu/dfu-util/

Tested on Windows 10, Windows can read the 0xee string correctly, and
requests the second special descriptor, which then configures the USB
device to use the winusb driver.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-20 19:40:03 +11:00
Damien George 49d0c22b11 stm32/mboot: Expand device descriptor to make it easier to understand.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-20 19:31:15 +11:00
Damien George 859f219690 stm32/mboot: Guard use of tx_pending with USE_USB_POLLING option.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-20 17:25:57 +11:00
Damien George 7cf1118831 stm32/usbdev: Optionally pass through vendor requests to Setup function.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-20 17:25:10 +11:00
Damien George f46269a1d1 extmod/asyncio: Remove non-working Stream __aenter__/__aexit__ methods.
It looks like these never worked and there are no tests for this
functionality.  Furthermore, CPython doesn't support this.

Fixes #12995.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-20 15:56:23 +11:00
Damien George f6d630877c esp32: Add MICROPY_GC_INITIAL_HEAP_SIZE option and tune it.
This gets back the old heap-size behaviour on ESP32, before auto-split-heap
was introduced: after the heap is grown one time the size is 111936 bytes,
with about 40k left for the IDF.  That's enough to start WiFi and do a
HTTPS request.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-19 18:34:23 +11:00
Damien George 97b13132b1 py/gc: Improve calculation of new heap size in split-heap-auto mode.
There are two main changes here to improve the calculation of the size of
the next heap area when automatically expanding the heap:
- Compute the existing total size by counting the total number of GC
  blocks, and then using that to compute the corresponding number of bytes.
- Round the bytes value up to the nearest multiple of BYTES_PER_BLOCK.

This makes the calculation slightly simpler and more accurate, and makes
sure that, in the case of growing from one area to two areas, the number
of bytes allocated from the system for the second area is the same as the
first.  For example on esp32 with an initial area size of 65536 bytes, the
subsequent allocation is also 65536 bytes.  Previously it was a number that
was not even a multiple of 2.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-19 18:34:23 +11:00
Patrick Van Oosterwijck 3270d856fd rp2/boards: Add SIL_RP2040_SHIM board by Silicognition LLC.
Add new board Silicognition RP2040-Shim, RP2040 with 4 MB of flash
and W5500 drivers included and configured by default for use with
the Silicognition PoE-FeatherWing.

Co-authored-by: Matt Trentini <matt.trentini@gmail.com>

Signed-off-by: Patrick Van Oosterwijck <patrick@silicognition.com>
2023-12-18 16:32:20 +11:00
Paul Grayson c51081c604 rp2/boards: Add support for Pololu 3pi+ and Zumo robots.
Signed-off-by: Paul Grayson <paul@pololu.com>
2023-12-18 14:08:04 +11:00
Paul Grayson fbf079d773 rp2: Add new NO_DEFAULT_PINS config options for i2c, spi, and uart.
Some boards have multiple options for these pins, and they don't want to
allow users to initialize a port without explicitly specifying pin numbers.

Signed-off-by: Paul Grayson <paul@pololu.com>
2023-12-18 14:07:03 +11:00
Damien George a78ec4ef7b rp2/mpconfigport: Enable MICROPY_PY_OS_DUPTERM_NOTIFY.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-18 12:20:47 +11:00
Damien George 1f2ec4583d extmod/os_dupterm: Prevent recursive execution of mp_os_dupterm_rx_chr.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-18 12:20:47 +11:00
Damien George 395886caa3 extmod/modos: Factor os.dupterm_notify() function to common extmod code.
esp8266 doesn't need ets task because the notify is now scheduled (see
commits 7d57037906 and
c60caf1995 for relevant history).

Signed-off-by: Damien George <damien@micropython.org>
2023-12-18 12:20:47 +11:00
Trent Piepho 0e706a62b1 py/makeqstrdefs.py: Stop generating temporary intermediate file.
In "cat" mode, output was written to a file named "out", then moved to the
location of the real output file.  There was no reason for this.

While makeqstrdefs.py does make an effort to not update the timestamp on an
existing output file that has not changed, the intermediate "out" file
isn't part of the that process.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2023-12-14 22:55:08 -08:00
Elias Wimmer 2e101a8e44 extmod/modonewire: Improve write timings for better reliability.
When using long cables for sensors on onewire e.g. ds18b20, the current
default timings are too optimistic, leading to bus failures and CRC errors.

Stable results are achieved with the timings given by
https://www.analog.com/en/technical-articles/1wire-communication-through-software.html
2023-12-15 17:08:09 +11:00
Patrick Van Oosterwijck 06df3b2925 extmod/modonewire: Adopt Maxim recommended read timings.
The timing of the onewire module was way too fast when reading.  This
commit adopts read timings as recommended in Maxim application note 126:
6 us (pulse) / 9 us (sample) / 55 us (bit slot).  See also:
https://www.analog.com/en/technical-articles/1wire-communication-through-software.html

Signed-off-by: Damien George <damien@micropython.org>
2023-12-15 17:04:33 +11:00
dependabot[bot] de3e83aa4d github/workflows: Bump actions/upload-artifact from 3 to 4.
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact)
from 3 to 4.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v3...v4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-15 16:14:43 +11:00
dependabot[bot] be64641210 github/workflows: Bump actions/setup-python from 4 to 5.
Bumps [actions/setup-python](https://github.com/actions/setup-python) from
4 to 5.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v4...v5)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-15 16:13:15 +11:00
dependabot[bot] d506b53377 github/workflows: Bump actions/github-script from 6 to 7.
Bumps [actions/github-script](https://github.com/actions/github-script)
from 6 to 7.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v6...v7)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-15 16:09:55 +11:00
Trent Piepho f22e88611d py/makeqstrdefs.py: Don't skip output for stale hash file.
In "cat" mode a "$output_file.hash" file is checked to see if the hash of
the new output is the same as the existing, and if so the output file isn't
updated.

However, it's possible that the output file has been deleted but the hash
file has not.  In this case the output file is not created.

Change the logic so that a hash file is considered stale if there is no
output file and still create the output.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2023-12-15 15:48:07 +11:00
Trent Piepho 0d93392f10 py/mkrules.mk: List hash files as byproducts.
These are produced by the "cat" command to makeqstrdefs.py, to allow it to
not update unchanged files.  cmake doesn't know about them and so they are
not removed on a "clean".

This triggered a bug in makeqstrdefs.py where it would not recreate a
deleted output file (which is removed by clean) if a stale hash file with a
valid hash still existed.

Listing them as byproducts will cause them to be deleted on clean.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2023-12-15 15:48:07 +11:00
stijn 85c02166ca py/modsys: Implement optional sys.intern.
Signed-off-by: stijn <stijn@ignitron.net>
2023-12-15 11:43:39 +11:00
Carlosgg 05d3b22301 docs/library: Document SSLContext cert methods and asyncio support.
Add `load_cert_chain`, `load_verify_locations`, `get_ciphers` and
`set_ciphers` SSLContext methods in ssl library, and update asyncio
`open_connection` and `start_server` methods with ssl support.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-14 13:06:39 +11:00
Carlosgg bfd6ad94ff extmod/asyncio: Add ssl support with SSLContext.
This adds asyncio ssl support with SSLContext and the corresponding
tests in `tests/net_inet` and `tests/multi_net`.

Note that not doing the handshake on connect will delegate the handshake to
the following `mbedtls_ssl_read/write` calls.  However if the handshake
fails when a client certificate is required and not presented by the peer,
it needs to be notified of this handshake error (otherwise it will hang
until timeout if any).  Finally at MicroPython side raise the proper
mbedtls error code and message.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-14 12:20:19 +11:00
Damien George f33dfb966a extmod/modssl_mbedtls: Fix parsing of ciphers in set_ciphers method.
Fixes two issues:
- None should not be allowed in the list, otherwise the corresponding entry
  in ciphersuites[i] will have an undefined value.
- The terminating 0 needs to be put in ciphersuites[len].

Signed-off-by: Damien George <damien@micropython.org>
2023-12-14 12:03:36 +11:00
Damien George bba8a673d5 tests: Update SSL network tests to use SSLContext, and work on CPython.
Changes are:
- use ssl.SSLContext.wrap_socket instead of ssl.wrap_socket
- disable check_hostname and call load_default_certs() where appropriate,
  to get CPython to run the tests correctly
- pass socket.AF_INET to getaddrinfo and socket.socket(), to force IPv4
- change tests to use github.com instead of google.com, because certificate
  validation was failing with google.com

Signed-off-by: Damien George <damien@micropython.org>
2023-12-12 21:22:10 +11:00
Damien George ef996d15b9 extmod/modssl_mbedtls: Make SSLSocket.getpeercert() optional.
And only enable this method when the relevant feature is available in
mbedtls.  Otherwise, if mbedtls doesn't support getting the peer
certificate, this method always returns None and it's confusing why it does
that.  It's better to remove the method altogether, so the error trying to
use it is more obvious.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-12 21:21:54 +11:00
Damien George c9eb6bc601 esp32: Re-enable custom mbedtls error string tables.
To match other ports that use mbedtls.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-12 16:25:07 +11:00
Damien George 58e75264c1 lib/mbedtls_errors: Update error list for latest esp32 mbedtls.
Running `./do-esp32.sh` now generates this esp32_mbedtls_errors.c file,
with IDF v5.0.4.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-12 16:25:07 +11:00
Carlosgg f3f215e9bd extmod/modssl_mbedtls: Add SSLContext certificate methods.
This commit adds:

1) Methods to SSLContext class that match CPython signature:

	- `SSLContext.load_cert_chain(certfile, keyfile)`
	- `SSLContext.load_verify_locations(cafile=, cadata=)`
	- `SSLContext.get_ciphers()` --> ["CIPHERSUITE"]
	- `SSLContext.set_ciphers(["CIPHERSUITE"])`

2) `sslsocket.cipher()` to get current ciphersuite and protocol
   version.

3) `ssl.MBEDTLS_VERSION` string constant.

4) Certificate verification errors info instead of
   `MBEDTLS_ERR_X509_CERT_VERIFY_FAILED`.

5) Tests in `net_inet` and `multi_net` to test these new methods.

`SSLContext.load_cert_chain` method allows loading key and cert from disk
passing a filepath in `certfile` or `keyfile` options.

`SSLContext.load_verify_locations`'s `cafile` option enables the same
functionality for ca files.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-12 16:25:07 +11:00
IhorNehrutsa 4365edb810 esp32: Change minimum supported IDF version to v5.0.4.
Also, IDF v5.1.2 is now supported, just not used by default.

IDF v5.0.2 still builds but we cannot guarantee continued support for this
version moving forward.

Signed-off-by: IhorNehrutsa <IhorNehrutsa@gmail.com>
2023-12-11 13:00:09 +11:00
Damien George d0758d8a33 esp32/boards/ESP32_GENERIC: Disable network.LAN and VM-opt on D2WD.
To reduce firmware size, because IDF v5.0.4 has increased in size.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-11 13:00:06 +11:00
Damien George b4b77c17b5 esp32/mpconfigport: Keep some funcs out of IRAM for ESP32-SPIRAM builds.
To make sure the build fits.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-11 12:59:51 +11:00
Ihor Nehrutsa 3069fee386 esp32/machine_i2s: Fix deprecated fields and constants.
Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-11 12:59:29 +11:00
Ihor Nehrutsa a427117d03 esp32/modmachine: Fix deprecated esp_pm_config_XXX_t.
Co-Authored-By: Trent Piepho <35062987+xyzzy42@users.noreply.github.com>

Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-11 12:59:14 +11:00
Ihor Nehrutsa e423b3c0ba docs/esp32/quickref: Add DAC example.
Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-11 12:58:22 +11:00
IhorNehrutsa 495be71d56 esp32/machine_dac: Support one-shot mode of driver.
And simplify board configuration of DAC by using SOC_DAC_SUPPORTED.

Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-11 12:57:43 +11:00
IhorNehrutsa 3106ee4885 esp32/modnetwork: Add WiFi AUTH_WPA3_ENT_192 authenticate mode.
Available in newer versions of the IDF.

Signed-off-by: IhorNehrutsa <IhorNehrutsa@gmail.com>
2023-12-11 12:57:05 +11:00
IhorNehrutsa 88778be73a esp32/machine_i2c: Use APB_CLK_FREQ instead of I2C_APB_CLK_FREQ.
Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-11 12:56:38 +11:00
Carlosgg c393cd7e48 esp32/boards/sdkconfig.base: Disable unused mbedtls options.
Disable unused EC curves and default certificate bundle which is not
implemented in MicroPython.  This reduces the firmware size significantly.

This follows commit 68f166dae9.

Signed-off-by: Carlos Gil Gonzalez <carlosgilglez@gmail.com>
2023-12-11 12:06:35 +11:00
Damien George e1a7aa23fd ports: Switch build to use common lib/libm list of source files.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-08 15:42:41 +11:00
Damien George 241dbac928 extmod: Add lists of libm/libm_dbl source files for ports to use.
So that ports don't need to specify each of these files, they can simply
refer to the appropriate make/cmake variable.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-08 15:39:28 +11:00
Angus Gratton 2c828a8815 unix: Update port to use the new event functions.
Necessary to get coverage of the new event functions.

Deletes the case that called usleep(delay) for mp_hal_delay_ms(), it seems
like this wouldn't have ever happened anyhow (MICROPY_EVENT_POOL_HOOK is
always defined for the unix port).

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 13:17:15 +11:00
Angus Gratton 73879734d9 esp8266: Update port to use new event functions.
This is necessary to avoid watchdog timeout in long i2c.scan(), as
previously machine_i2c.c would call MICROPY_EVENT_POLL_HOOK if
MICROPY_EVENT_POLL_HOOK_FAST was not available.

Compared to previous implementation, this implementation removes the
ets_event_poll() function and calls the SDK function ets_loop_iter() from
MICROPY_INTERNAL_EVENT_HOOK instead.  This allows using the port-agnostic
functions in more places.

There is a small behaviour change, which is that the event loop gets
iterated in a few more places (i.e. anywhere that mp_event_handle_nowait()
is called).  However, this looks like maybe only modselect.c - and is
probably good to process Wi-Fi events in that polling loop.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 12:50:38 +11:00
Angus Gratton c393f5c123 windows: Implement MICROPY_INTERNAL_WFE() macro.
This should be the equivalent of the previous event poll hook macro.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 12:49:54 +11:00
Angus Gratton 393938b3e6 rp2/main: Enable SEVONPEND CPU interrupt bit.
Previously this was not set, so potential for race conditions in interrupt
handlers this didn't issue SEV.  (Which is currently all of them, as far as
I can see.)

Eventually we might be able to augment the interrupt handlers that wake the
main thread to call SEV, and leave the others as-is to suspend the CPU
slightly faster, but this will solve the issue for now.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 12:49:49 +11:00
Angus Gratton 28529351ae rp2: Switch rp2 and drivers to use new event functions.
This commit changes all uses in the rp2 port, and drivers that are
optionally supported by that port.

The old MICROPY_EVENT_POLL_HOOK and MICROPY_EVENT_POLL_HOOK_FAST macros are
no longer used for rp2 builds and are removed (C user code will need to be
changed to suit).

Also take the opportunity to change some timeouts that used 64-bit
arithmetic to 32-bit, to hopefully claw back a little code size.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 12:49:43 +11:00
Angus Gratton df3948d3c2 extmod: Switch to use new event functions.
See previous commit for details of these functions.  As of this commit,
these still call the old hook macros on all ports.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 12:48:50 +11:00
Angus Gratton f5be0128e4 py: Add port-agnostic inline functions for event handling.
These are intended to replace MICROPY_EVENT_POLL_HOOK and
MICROPY_EVENT_POLL_HOOK_FAST, which are insufficient for tickless ports.

This implementation is along the lines suggested here:
https://github.com/micropython/micropython/issues/12925#issuecomment-1803038430

Currently any usage of these functions expands to use the existing hook
macros, but this can be switched over port by port.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 12:47:00 +11:00
Angus Gratton 66be82da7c esp8266: Avoid including ep_mphal.h directly.
This header has no include guards and is apparently only supposed to be
included from py/mphal.h.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-07 14:07:21 +11:00
iabdalkader 0960d64d3b extmod/network_ninaw10: Switch to using soft-timer for polling.
This patch simplifies the connection and sockets polling code, by switching
to a soft-timer to schedule polling code, and by using one node for
scheduling.  This also fixes any issues that could result from using a heap
allocated machine_timer, and includes better handling of the sockets poll
list.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-12-06 17:32:21 +11:00
iabdalkader 50f31cc902 extmod/modnetwork: Add deinit function to NIC protocol.
This is usually called on soft-reboot, a NIC can implement this to do any
necessary cleaning up (such as invalidating root pointers).

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-12-06 17:32:00 +11:00
Damien George d30d5c99af tests/run-tests.py: Skip Thumb2 tests if target doesn't support them.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-06 16:05:37 +11:00
Damien George b796f1e3f1 tests/float/inf_nan_arith.py: Include -inf in argument combos.
This adds tests for, eg, -inf + inf which should be nan.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-06 14:06:01 +11:00
Damien George 3f2c423686 rp2: Switch to locally provided math library.
This commit fixes all known floating-point bugs with the pico-sdk.  There
are two things going on here:
- Use a custom pico float component so that the pico-sdk doesn't include
  its math functions, and then provide our own from lib/libm.
- Provide a wrapper for __aeabi_fadd to fix the infinity addition bug.

Prior to this commit, the following tests failed on the rp2 port: cmath_fun
float_parse math_domain math_domain_special math_fun_special.  With this
commit, all these tests pass.

Thanks to @projectgus for how to approach this fix.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-06 14:00:07 +11:00
Scott Zhao 1323a71823 esp32/boards/UM_TINYPICO: Fix typo in baudrate instructions.
The installation instructions for ESP32 TinyPICO board contained a typo
that used a non-standard baud rate 912600 instead of 921600.  This made the
upload command fail on some Windows computers.

Signed-off-by: Scott Zhao <zhaomh1998@outlook.com>
2023-12-06 13:46:04 +11:00
Thomas Wenrich 78b3fe5689 esp32/machine_rtc: Preserve RTC user memory over most reset causes.
The user memory area - accessible by machine.RTC.memory() -- will now
survive most reboot causes.  A power-on reset (also caused by the EN pin on
some boards) will clean the memory.  When this happens, the magic number
not found in the user memory will cause initialization.

After other resets (triggered by watchdogs, machine.reset(), ...), the user
is responsible to check and validate the contents of the user area.

This new behaviour can be changed by enabling
MICROPY_HW_RTC_MEM_INIT_ALWAYS: in that case the RTC memory is always
cleared on boot.

Signed-off-by: Thomas Wenrich <twenrich@gmail.com>
2023-12-06 13:31:13 +11:00
Damien George d3595fed2b tools/ci.sh: Build ESP32_GENERIC-SPIRAM as part of esp32 CI.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-06 12:37:25 +11:00
Damien George 69089a532e esp32/boards: Enable further IRAM saving opts to fit ESP32-SPIRAM fw.
The amount of free IRAM in ESP32 SPIRAM builds is very small and went over
the limit due to commit 30b0ee34d3.  This
commit enables further optimisations to reduce IRAM usage.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-06 12:35:45 +11:00
Angus Gratton 527c4b0497 github/workflows: Enable ccache for esp32 build.
CCaches are scoped per-job.

Uses https://github.com/hendrikmuhs/ccache-action to get desired behaviour
(updating the cache on each run).

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-06 12:15:33 +11:00
Angus Gratton 731a1f5233 github/workflows: Enable build matrix for stm32 port.
This is for consistency with the previous commit that uses this approach
for esp32.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-06 12:15:20 +11:00
Angus Gratton b6df8f8452 github/workflows: Use build matrix for esp32 port.
Allows splitting the esp32 job into multiple parts without too much
boilerplate.  The matrix is parameterised using the name of the function to
call in tools/ci.sh, to minimise the dependency on GitHub Actions.

This can get esp32 build times down around 3m if IDF is cached already.

If the cache is cold, the cache preparation step on each job can double up
against each other.  However, restructuring the workflow to not do this
seems either complex or requires copy-pasting the entire cache step.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-06 12:13:56 +11:00
Angus Gratton 9f620d2819 github/workflows: Cache ESP-IDF checkout and installation.
Cache is keyed on the ESP-IDF version used in CI, so there shouldn't be any
cache invalidation issues when ESP-IDF version changes.

Restoring from cache takes approx 15s, compared to 2-3m to perform these
steps (ESP-IDF tools install, ESP-IDF clone, ESP-IDF submodule clone) the
first time.

Cache size is approx 1.6GB, the git clone is tweaked as much as possible to
keep the size down.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-06 12:12:52 +11:00
MikeTeachman 58112fc49a stm32/machine_i2s: Improve accuracy of SCK frequency.
Configures the I2S PLL to produce a frequency that the I2S clock generator
can use to create an optimal SCK frequency.  The I2S PLL configuration
table is automatically generated at build time.

Fixes issue #10280.

Signed-off-by: Mike Teachman <mike.teachman@gmail.com>
2023-12-06 11:48:03 +11:00
Damien George f3889db265 stm32/usbd_cdc_interface: Include header to get machine_bootloader decl.
This was broken by commit 48b5a7b060.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-04 22:19:59 +11:00
Damien George 20af857f52 nrf/boards/ARDUINO_NANO_33_BLE_SENSE: Don't enable MICROPY_MBFS.
This board has MICROPY_VFS enabled, which should take precedence over
MICROPY_MBFS (and did prior to 22d9116c8c).

Signed-off-by: Damien George <damien@micropython.org>
2023-12-04 22:18:14 +11:00
Damien George d422b68d10 nrf/mpconfigport: Enable MICROPY_PY_MACHINE_BOOTLOADER.
This should have been enabled in 48b5a7b060
but was missed.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-04 22:17:18 +11:00
Carlosgg 30b0ee34d3 esp32: Enable mbedtls cert time validation.
Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-04 10:50:42 +11:00
Damien George b5449b0f09 extmod/mbedtls: Enable certificate time/date validation by default.
All ports using this common configuration already enable time/date
validation, so this commit is a no-op change.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-01 15:08:11 +11:00
Carlosgg 20ffbe1a41 unix/mbedtls: Enable mbedtls cert time validation.
To match other ports.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-01 15:08:11 +11:00
Damien George ad806df857 ports: Move definitions of ATOMIC_SECTION macros to mphalport.h.
Also move MICROPY_PY_PENDSV_ENTER/REENTER/EXIT to mphalport.h, for ports
where these are not already there.

This helps separate the hardware implementation of these macros from the
MicroPython configuration (eg for renesas-ra and stm32, the IRQ static
inline helper functions can now be moved to irq.h).

Signed-off-by: Damien George <damien@micropython.org>
2023-12-01 14:37:48 +11:00
Damien George bfdf500ea5 py/mphal: Move configuration of ATOMIC_SECTION macros to mphal.h.
MICROPY_BEGIN_ATOMIC_SECTION/MICROPY_END_ATOMIC_SECTION belong more to the
MicroPython HAL rather than build configuration settings, so move their
default configuration to py/mphal.h, and require all users of these macros
to include py/mphal.h (here, py/objexcept.c and py/scheduler.c).

This helps ports separate configuration from their HAL implementations, and
can improve build times (because mpconfig.h is included everywhere, whereas
mphal.h is not).

Signed-off-by: Damien George <damien@micropython.org>
2023-12-01 14:14:08 +11:00
Damien George 7d784e5385 cc3200/application.mk: Don't add stm32 to build include path.
Or this port may end up accidentally including unwanted headers from stm32.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-01 14:13:34 +11:00
Damien George 7a6489aaa5 cc3200: Eliminate dependency on stm32's irq.h.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-01 14:12:59 +11:00
Damien George 49fa3ce65d cc3200: Convert os module to use extmod version.
Changes:
- os.uname() is removed to save space; sys.version and sys.implementation
  can be used instead.
- os.sync() now uses the common extmod version and syncs by calling the FAT
  FS sync function, which eventually calls sflash_disk_flush().

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 17:35:26 +11:00
Damien George 1c0e4644c7 cc3200: Convert dupterm to use common extmod implementation.
Tested on a WIPY.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 17:35:06 +11:00
Damien George 22d9116c8c nrf: Convert os module to use extmod version.
The os.dupterm() function has changed on this port, it now matches the
semantics used by all other ports (except it's restricted to accept only
machine.UART objects).

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:33:56 +11:00
Damien George e3c4c32c64 nrf: Use dupterm_objs[0] instead of board_stdio_uart.
To make this a little more consistent with other ports.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:33:56 +11:00
Damien George cc8fc450a6 esp8266/modmachine: Use common implementation of disable/enable_irq.
Now that the MICROPY_BEGIN_ATOMIC_SECTION/MICROPY_END_ATOMIC_SECTION macros
act the same as disable_irq/enable_irq, it's possible to use the common
extmod implementation of these machine functions.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 39d4153a8d esp8266/esp_mphal: Make atomic section more atomic.
By disabling ets_loop_iter when the atomic section is active.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 4bf7987f0a cc3200/mods/modmachine: Use common implementation of disable/enable_irq.
This commit changes the cc3200 port to use the common machine
implementation of machine.disable_irq() and machine.enable_irq().  This
eliminates its dependency on the stm32 port's code.  The behaviour of
cc3200 for these functions is changed:
- disable_irq() now returns an (opaque) integer rather than a bool
- enable_irq(state) must be passed and argument, which is the return value
  of disable_irq() rather than a bool

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George f523b86541 extmod/modmachine: Provide common implementation of disable/enable_irq.
The ports esp32, mimxrt, rp2 and samd all shared exactly the same
implementation of machine.disable_irq() and machine.enable_irq(),
implemented in terms of MICROPY_{BEGIN,END}_ATOMIC_SECTION.  This commit
factors these implementations into extmod/modmachine.c.

The cc3200, esp8266, nrf, renesas-ra and stm32 ports do not yet use this
common implementation.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George e1ec6af654 extmod/modmachine: Provide common bindings for 6 bare-metal functions.
Minor changes for consistency are:
- nrf gains: unique_id(), freq() [they do nothing]
- samd: deepsleep() now resets after calling lightsleep()
- esp32: lightsleep()/deepsleep() no longer take kw arg "sleep", instead
  it's positional to match others.  also, passing 0 here will now do a 0ms
  sleep instead of acting like nothing was passed.
  reset_cause() no longer takes any args (before it would just ignore them)
- mimxrt: freq() with an argument and lightsleep() both raise
  NotImplementedError

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 48b5a7b060 extmod/modmachine: Provide common Python bindings for bootloader().
Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George e68aa40d2a extmod/modmachine: Add MICROPY_PY_MACHINE_PIN_BASE option.
And use it in qemu-arm, unix and windows ports to enable PinBase.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 30a63a204d extmod/modmachine: Provide common Python bindings for machine.idle().
And use it in all ports.  The ports are unchanged, except esp8266 which now
just returns None from this function instead of the time elapsed (to match
other ports), and qemu-arm which gains this function.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 7d39db2503 extmod/modmachine: Factor ports' machine module dict to common code.
This is a code factoring to have the dict for the machine module in one
location, and all the ports use that same dict.  The machine.soft_reset()
function implementation is also factored because it's the same for all
ports that did already implement it.  Eventually more functions/bindings
can be factored.

All ports remain functionally the same, except:
- cc3200 port: gains soft_reset, mem8, mem16, mem32, Signal; loses POWER_ON
  (which was a legacy constant, replaced long ago by PWRON_RESET)
- nrf port: gains Signal
- qemu-arm port: gains soft_reset
- unix port: gains soft_reset
- zephyr port: gains soft_reset, mem8, mem16, mem32

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 14432b5da0 extmod/modmachine: Make I2C/SPI defns available when soft impl enabled.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 7b2f13fb69 renesas-ra: Consolidate MICROPY_PY_MACHINE_I2C option.
MICROPY_HW_ENABLE_HW_I2C and MICROPY_PY_MACHINE_I2C are equivalent, so
just use the latter.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George e120c00c95 stm32/modmachine: Only enable machine.I2C if hardware I2C is enabled.
Prior to this change, if a board did not define any hardware I2C pins, via
MICROPY_HW_I2Cx_SCL, then machine.I2C would alias to machine.SoftI2C.

That doesn't really make sense, and SoftI2C should always be used if there
is no hardware implementation.  So this commit makes it so that machine.I2C
is only available if at least one set of I2C hardware pins are defined via
the MICROPY_HW_I2Cx_SCL/SDA macros.

For all boards that define at least one set of I2C hardware pins (which is
most of them) this commit is a no-op.  The only boards that change are:
LEGO_HUB_NO6, LEGO_HUB_NO7, STM32H7B3I_DK.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George b4d288ae44 nrf: Use MICROPY_PY_MACHINE_SPI instead of MICROPY_PY_MACHINE_HW_SPI.
MICROPY_PY_MACHINE_SPI is defined in mpconfigport.h to be equal to
MICROPY_PY_MACHINE_HW_SPI, so they are equivalent options.  The former one
is preferred because it's used by all other ports.

The default in mpconfigport.h is to enable this option, and all boards that
enable SPI have this removed from their mpconfigboard.h file so they pick
up the default.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:10:10 +11:00
Damien George 911662cc10 esp8266/machine_spi: Rename machine_hspi to machine_spi.
This renames the type, functions and file to match other ports.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 15:58:56 +11:00
Damien George c554df57f6 tests/extmod/deflate_compress.py: Add a test for optimal compression.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 12:13:29 +11:00
Damien George 6ba57f760c lib/uzlib: For matches of the same length, take the closest one.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 12:13:29 +11:00
Damien George e182f3862e rp2/cyw43_configport: Implement cyw43_delay_ms as mp_hal_delay_ms.
They do the same thing.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-29 16:25:28 +11:00
Damien George 12ef8a5ba2 rp2/mphalport: Optimise exit of mp_hal_delay_ms loop.
best_effort_wfe_or_timeout() already calls time_reached() and returns the
result of it, so no need to call it again.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-29 16:25:28 +11:00
Damien George fc94399ffe rp2/mpnetworkport: Rework lwIP polling to use soft_timer.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-29 16:25:20 +11:00
Damien George 633c604722 rp2/mpbthciport: Rework HCI polling timer to use soft_timer.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-29 16:23:52 +11:00
Damien George c9a9b2e682 rp2: Integrate soft_timer using the alarm pool.
The alarm pool is used to schedule the callback to soft_timer_handler().

Signed-off-by: Damien George <damien@micropython.org>
2023-11-29 16:23:49 +11:00
Damien George 516cc280e0 shared/runtime/softtimer: Generalise soft_timer to work without SysTick.
If a port defines MICROPY_SOFT_TIMER_TICKS_MS then soft_timer assumes a
SysTick back end, and provides a soft_timer_next variable that sets when
the next call to soft_timer_handler() should occur.

Otherwise, a port should provide soft_timer_get_ms() and
soft_timer_schedule_at_ms() with appropriate semantics (see comments).

Existing users of soft_timer should continue to work as they did.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-29 16:17:12 +11:00
Jeff Epler 9c7067d9ad py/modbuiltins: Share vstr_add_char's implementation of utf8 encoding.
This saves ~84 bytes on trinket m0, and saves 112 bytes on PYBV10.

Signed-off-by: Jeff Epler <jepler@gmail.com>
2023-11-28 23:34:56 +11:00
iabdalkader cfcd0c4022 stm32: Add missing header include for debug builds.
Debug build fails if string.h header is not included.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-11-28 23:32:52 +11:00
Jim Mussared 992cd64555 py/mkrules: Add support for custom manifest variables.
This allows e.g. a board (or make command line) to set

    MICROPY_MANIFEST_MY_VARIABLE = path/to/somewhere
    set(MICROPY_MANIFEST_MY_VARIABLE path/to/somewhere)

and then in the manifest.py they can query this, e.g. via

    include("$(MY_VARIABLE)/path/manifest.py")

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-28 23:28:15 +11:00
Mark Blakeney 094b52b8ad esp32/esp32_rmt: Fix RMT looping.
Commit 7ea06a3e26 moved the
`rmt_write_items()` call to fix RMT looping for ESP32-S3, but broke it for
the other ESP32s.  This commit conditionally compiles the location of that
call.

Signed-off-by: Mark Blakeney <mark.blakeney@bullet-systems.net>
2023-11-23 12:21:28 +11:00
Ihor Nehrutsa d6154925d5 esp32/network_wlan: Fix network.WLAN.status() to return better info.
Prior to this change, after calling connect() the status() method for the
STA interface would either return STAT_GOT_IP or STAT_CONNECTION.  The
latter would be returned because wifi_sta_connect_requested==true and
conf_wifi_sta_reconnects==0 by default.  As such there was no way to know
anything about errors when attempting to connect, such as a bad password.

Now, status() can return STAT_NO_AP_FOUND and STAT_WRONG_PASSWORD when
those conditions are met.

Fixes issue #12930.

Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-11-23 12:11:42 +11:00
Angus Gratton 960eef70e8 esp32/network_wlan: Reduce RAM usage if SPIRAM fails to initialise.
In ESP-IDF, enabling SPIRAM in menuconfig sets some Kconfig options:

- "Wi-Fi Cache TX Buffers" enabled. By default this tries to allocate 32 of
these when Wi-Fi is initialised, which requires 54,400 bytes of free heap.

- Switches "Type of WiFi TX buffers" from Dynamic to Static. This
pre-allocates all of the Wi-Fi transmit buffers.

Not a problem if PSRAM is initialised, but it's quite a lot of RAM if PSRAM
failed to initialise! As we use the same config for PSRAM & no-PSRAM builds
now, this either causes Wi-Fi to fail to initialise (seen on S2) or will
eat quite a lot of RAM.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-23 11:53:39 +11:00
Trent Piepho 92f0469711 esp32/uart: Make compatible with sclk type change in ESP-IDF 5.3.
This type changes when they add LP-UART support for the ESP32-C6 in the dev
version of ESP-IDF 5.3.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2023-11-23 11:51:06 +11:00
Trent Piepho f72a7dde18 esp32/uart: Preserve console UART clock, fix UART console with DFS.
In commit 7c929d44 the console UART was changed to use the UART HAL.
Starting the UART HAL will change the UART clock from whatever it was
already configured at to UART_SCLK_DEFAULT.  There is no "initialize at
existing settings" option.

This clock doesn't work with DFS.

The ESP-IDF code already takes this into account, and when DFS is enabled
it will configure the console UART to use the correct platform-specific
clock that will work with DFS.

The UART HAL init undoes this and sets it back to default.

This change will query the clock before the HAL init, then use the HAL
function to restore it back.  Thus keeping the clock at the "correct"
value, which depends on platform, DFS status, and so on.

The clock frequency will be found using the UART driver function ESP-IDF
code uses for this.  The existing code hard-coded a path that worked if the
clock was the APB clock and would fail otherwise.

The UART_NUM_0 define is removed because driver/uart.h already provides
this same macro.

Signed-off-by: Trent Piepho <tpiepho@gmail.com>
2023-11-23 11:49:08 +11:00
Damien George a85c3c45a6 esp32/boards/ESP32_GENERIC: Reduce size of D2WD variant to fit in flash.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-23 10:39:12 +11:00
Angus Gratton a800ed5ae3 docs/library/esp: Correct the description of esp.osdebug().
The behaviour described in the docs was not correct for either port.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-22 16:48:35 +11:00
Angus Gratton 917b56137f esp32/boards/sdkconfig.base: Fix increasing log level via esp.osdebug().
At some point the config changed such that no messages above Error level
were compiled into the final binary.

Fixes issue #12815.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-22 16:48:15 +11:00
Damien George f397a3ec31 py/objslice: Validate that the argument to indices() is an integer.
Otherwise passing in a non-integer can lead to an invalid memory access.

Thanks to Junwha Hong and Wonil Jang @S2Lab, UNIST for finding the issue.

Fixes issue #13007.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-21 22:28:57 +11:00
Angus Gratton fce8d9fd55 esp32/modsocket: Try garbage collection if the socket limit is reached.
If the hard socket limit (default 16) is reached then it's possible that
socket allocation fails but garbage collection would allow it to succeed.

Perform a GC pass and try again before giving up, similar to the logic
elsewhere in MicroPython that tries a GC pass before raising MemoryError.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-20 19:16:16 +11:00
Angus Gratton 57cce79a46 esp32/modsocket: Implement socket connect timeout.
LWIP doesn't implement a timeout for blocking connect(), and such a timeout
is not required by POSIX.  However, CPython will use the socket timeout for
blocking connect on most platforms.  The "principle of least surprise"
suggests we should support it on ESP32 as well (not to mention it's
useful!).

This provides the additional improvement that external exceptions (like
KeyboardInterrupt) are now handled immediately if they happen during
connect().  Previously Ctrl-C would not terminate a blocking connect until
connect() returned, but now it will.

Fixes issue #8326.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-20 18:48:25 +11:00
Sebastian Romero 6117aa686f renesas-ra/boards/ARDUINO_PORTENTA_C33: Fix incorrect I2C pins.
Also change the number of the interface to 0 as it's connected to IIC0.

Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2023-11-17 15:40:33 +11:00
Sebastian Romero 6f0193335a ports: Fix incorrect identifiers on Arduino boards.
This commit changes the Arduino board identifiers to correspond to their
official names.  This helps to identify boards at runtime.  At the moment
the Arduino Portenta H7 is reported as PORTENTA which is unfortunate as now
there is another Portenta board (Portenta C33) supported in MicroPython.

Also made the other identifiers for flash and network name consistent,
removed the incorrectly used MICROPY_PY_SYS_PLATFORM identifiers, and added
missing MICROPY_PY_NETWORK_HOSTNAME_DEFAULT identifiers.

Boards affected:
- stm32: ARDUINO_PORTENTA_H7, ARDUINO_GIGA, ARDUINO_NICLA_VISION
- renesas-ra: ARDUINO_PORTENTA_C33
- esp32: ARDUINO_NANO_ESP32
- rp2: ARDUINO_NANO_RP2040_CONNECT

Signed-off-by: Sebastian Romero <s.romero@arduino.cc>
2023-11-17 15:24:15 +11:00
stijn a968888f69 py/obj: Fix mp_obj_is_type compilation with C++.
Fixes issue #12951.

Signed-off-by: stijn <stijn@ignitron.net>
2023-11-17 14:31:42 +11:00
Damien George 92741a3438 stm32/boards/STM32H573I_DK: Enable the SD card.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-17 14:17:49 +11:00
Damien George c34941109f stm32/sdcard: Add SD card support for H5 MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-17 14:17:37 +11:00
Rene Straub 0cc100be2c stm32/boards/NUCLEO_H563ZI: Add new NUCLEO-H563ZI board definition.
Configuration:
- Clock is HSE, CPU runs at 250MHz.
- REPL on USB and UART connected to the ST-Link interface.
- Storage is configured for internal flash memory.
- Three LEDs and one user button.
- Ethernet is enabled.

Signed-off-by: Rene Straub <rene@see5.ch>
2023-11-17 13:53:01 +11:00
ThomHPL 70feb123bf stm32/boards/NUCLEO_F446RE: Add UARTs 1, 3 and 4.
Signed-off-by: ThomHPL <thomas.herpoel@gmail.com>
2023-11-17 13:43:11 +11:00
Peter Züger 36e162f116 tests/net_hosted/asyncio_loopback.py: Add loopback test.
Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2023-11-17 13:37:43 +11:00
Peter Züger a23dbdca79 stm32: Add optional lwip loopback support.
MICROPY_PY_LWIP_LOOPBACK must be set at the make level to enable this.

Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2023-11-17 13:37:04 +11:00
Peter Züger 1879db7105 extmod/extmod.mk: Allow enabling lwip loopback support.
Enabling MICROPY_PY_LWIP_LOOPBACK via make will turn on loopback support.

Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2023-11-17 13:35:47 +11:00
Andrew Leech 37c1c5fa49 stm32/mpu: Enable STM32WB mpu use to support qspi flash.
Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2023-11-17 13:17:13 +11:00
Angus Gratton 8b1980ad45 samd: Use unique id for USB serial number.
Replaces the previous all-zeroes "TODO" serial number.

Requires refactoring the low-level unique_id routine out from modmachine.c.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-16 15:03:09 +11:00
Angus Gratton f567a9255a shared/tinyusb: Add a helper for hex string conversion.
Change the rp2 and renesas-ra ports to use the helper function.

Saves copy-pasta, at the small cost of one more function call in the
firmware (if not using LTO).

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-16 14:59:48 +11:00
Angus Gratton 5e3f0e7f85 samd: Switch to shared TinyUSB implementation.
Functionality and code size don't really change, but removes port-specific
code in favour of shared code.

(The MSC implemented in shared/tinyusb depends on some functions in the
pico-sdk, so this change doesn't make this available for samd.)

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-16 14:54:29 +11:00
Angus Gratton 033361da4a samd/mphalport: Run TinyUSB stack while waiting for CDC input/output.
See the commit a00c9d56db for a detailed description of the problem, a
regression introduced in 26d503298.

Same approach here as the linked fix for rp2 (applied unconditionally here
as this port only supports USB-CDC for stdin/stdout).

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-10 08:04:26 +11:00
Damien George a00c9d56db rp2/mphalport: Run TinyUSB stack while waiting for CDC input/output.
The recent change in bcbdee2357 means that
TinyUSB can no longer be run from within a soft (or hard) IRQ handler, ie
when the scheduler is locked.  That means that Python code that calls
`print(...)` from within a scheduled function may block indefinitely if the
USB CDC buffers are full.

This commit fixes that problem by explicitly running the TinyUSB stack when
waiting within stdio tx/rx functions.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-09 17:56:58 +11:00
Damien George d46dc5e173 shared/tinyusb: Expose mp_usbd_task as a public function.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-09 17:56:58 +11:00
stijn 365913953a extmod/vfs_posix_file: Make standard file objects non-const.
Fixes undefined behavior when calling vfs_posix_file_ioctl with
MP_STREAM_CLOSE as request because that casts away the constness and
assigns -1 to the object's fd member.

Fixes issue #12670.

Signed-off-by: stijn <stijn@ignitron.net>
2023-11-09 15:01:34 +11:00
Daniël van de Giessen 3b954698fa extmod/modbluetooth: Initialise nlr_jump_callback_top for IRQ handlers.
Similar to 3883f29485 where this change was
implemented for threads: when the Bluetooth IRQ handler is called the
thread state is not not zero-initialized and thus we need to manually set
this to NULL.

Fixes issue #12239.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-11-09 14:51:20 +11:00
Jim Mussared af52e1ff24 stm32/boards/NUCLEO_WL55: Freeze LoRa driver.
This adds the sync version of the LoRa driver (and the base WL55 driver).

Adds +13.6kiB (212.6 -> 226.2). Limit for this board is 232kiB.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-09 14:47:53 +11:00
Mark Blakeney 2888c5b230 esp32/esp32_rmt: Add RMT.PULSE_MAX constant.
If you have a variable frequency and pulse width, and you want to optimize
pulse resolution, then you must do a calculation beforehand to ensure you
normalize the array to keep all list values within bound.  That calculation
requires RMT.source_freq(), RMT.clock_div(), and this 32767 constant.

Signed-off-by: Mark Blakeney <mark.blakeney@bullet-systems.net>
2023-11-09 13:51:52 +11:00
Mark Blakeney fbb7c32040 esp32/esp32_rmt: Change RMT.source_freq() to class method.
To create an esp32.RMT() instance with an optimum (i.e. highest resolution)
clock_div is currently awkward because you need to know the source clock
frequency to calculate the best clock_div, but unfortunately that is only
currently available as an source_freq() method on the instance after you
have already created it.  So RMT.source_freq() should really be a class
method, not an instance method.  This change is backwards compatible for
existing code because you can still reference that function from an
instance, or now also, from the class.

Signed-off-by: Mark Blakeney <mark.blakeney@bullet-systems.net>
2023-11-09 13:51:47 +11:00
robert-hh f07f90f1ab mimxrt/boards/OLIMEX_RT1010: Adjust the UART pin assignment.
Olimex asked for that, getting a UART at the UEXT1 connector as well.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-11-09 13:41:44 +11:00
Andrew Leech 4679a90097 CODECONVENTIONS: Update for change from black to ruff format.
Also add notes on running pre-commit manually.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2023-11-09 13:36:21 +11:00
Angus Gratton 26d5032980 samd: Switch TinyUSB to run via a scheduled task.
Previously the TinyUSB task was run in the ISR immediately after the
interrupt handler.  This approach gives very similar performance (no change
in CDC throughput tests) but reduces the amount of time spent in the ISR,
and allows TinyUSB callbacks to run in thread mode.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-09 12:30:04 +11:00
Angus Gratton bcbdee2357 rp2: Change to use TinyUSB dcd_event_handler hook.
This change:
- Has a small code size reduction.
- Should slightly improve overall performance.  The old hook code
  seemed to use between 0.1% and 1.6% of the total CPU time doing no-op
  calls even when no USB work was required.
- USB performance is mostly the same, there is a small increase in
  latency for some workloads that seems to because sometimes the hook
  usbd_task() is called at the right time to line up with the next USB host
  request.  This only happened semi-randomly due to the timing of the hook.
  Improving the wakeup latency by switching rp2 to tickless WFE allows the
  usbd_task() to run in time for the next USB host request almost always,
  improving performance and more than offsetting this impact.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-09 12:28:28 +11:00
Angus Gratton 2d363a23cb shared/tinyusb: Schedule TinyUSB task function from dcd_event_handler.
dcd_event_handler() is called from the IRQ when a new DCD event is queued
for processing by the TinyUSB thread mode task.  This lets us queue the
handler to run immediately when MicroPython resumes.

Currently this relies on a linker --wrap hack to work, but a PR has been
submitted to TinyUSB to allow the function to be called inline from
dcd_event_handler() itself.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-09 12:27:33 +11:00
Andrew Leech bbc5a18d09 tools/mpremote: Add ioctl to specify large read buffer size.
Speeds up importing files from mounted filesystem.

Also fix the return code for invalid / unsupported ioctl requests.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2023-11-09 11:30:11 +11:00
Andrew Leech 4cf741062b extmod/vfs_reader: Add file ioctl to set read buffer size.
Can be used to speed up importing a file from a vfs based filesystem.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2023-11-09 11:20:31 +11:00
Damien George dff293840e extmod/machine_i2c: Do a fast poll during I2C.scan().
Fixes issue #12912.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-08 23:34:08 +11:00
stijn 958c6d917d windows: Use the MicroPython logo as application icon.
Add a .ico file with common icon image size, created from
vector-logo-2.png, and embed it into the resulting executable.

Signed-off-by: stijn <stijn@ignitron.net>
2023-11-07 17:22:52 +11:00
Damien George 03eae48847 extmod/machine_adc_block: Factor esp32 ADCBlock bindings to common code.
This is a code factoring to have the Python bindings in one location, and
all the ports use those same bindings.  At this stage only esp32 implements
this class, so the code for the bindings comes from that port.

The documentation is also updated to reflect the esp32's behaviour of
ADCBlock.connect().

Signed-off-by: Damien George <damien@micropython.org>
2023-11-07 16:44:35 +11:00
Jim Mussared 4212799fd8 py/qstr: Special case qstr_find_strn for empty string.
This handles the case where an empty bytes/bytearray/str could pass in
NULL as the str argument (with length zero). This would result in UB in
strncmp. Even though our bare-metal implementation of strncmp handles
this, best to avoid it for when we're using system strncmp.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-07 16:01:50 +11:00
Jim Mussared 9be0623d4c shared/libc/string0: Don't deref args for n==0 case.
C99 says that strncmp has UB for either string being NULL, so the
current behavior is technically correct, but it's an easy fix to handle
this case correctly.

7.1.4: "unless explicitly stated otherwise in the detailed
description... if an argument to a function has ...null pointer.. the
behavior is undefined".

7.21.1: "Unless explicitly stated otherwise in the description of a
particular function in this subclause, pointer arguments on such a call
shall still have valid values, as described in 7.1.4".

Also make the same change for the minimal version in bare-arm/lib.c.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-07 16:01:50 +11:00
Alessandro Gatti bea6ff82fa tools/tinytest-codegen.py: Externalise tests list.
Remove port-specific test directories and excluded tests from
tinytest-codegen, and let it read said information from an external file.
This way tinytest-codegen is not limited to always generate tests for the
`qemu-arm` target.

This allows having port-specific test directory and excluded tests for more
than one QEMU bare-metal target.

The `qemu-arm` port Makefile was modified to work with the generator
changes and a tests profile file was added to said port.

Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2023-11-07 15:53:27 +11:00
robert-hh c35cc63366 samd/pin_af: Fix a typo in a conditional compile.
Thanks to @ricksorensen for finding it.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-11-06 11:11:18 +11:00
robert-hh 59afeb056a samd/machine_uart: Add machine_uart_set_baudrate() function.
Changing the baudrate requires a complete re-configuration of the Sercom
device, which is put into a separate rather large function.  This new
machine_uart_set_baudrate() function will be useful for future drivers such
as Bluetooth.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-11-06 11:10:11 +11:00
robert-hh 2c1f238205 samd/mpconfigport: Set MICROPY_USE_INTERNAL_ERRNO to 1.
Without this, error codes can be misleading.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-11-06 11:09:16 +11:00
robert-hh 6866d17d8f docs/samd: Fix the pinout for SAMD21 Itsy Bitsy Express M0.
And the "Pin", "GPIO" and "Name" key explanations.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-11-06 11:09:09 +11:00
Jim Mussared 47ed06bda2 stm32/boards/make-pins.py: Only support ADC1-3.
e.g. The STM32G4 includes ADC4 & ADC5 which is not currently supported
by the stm32 driver.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-05 08:33:49 +11:00
robert-hh e63d7189bc docs/mimxrt: Change the examples which denote a Pin with a number.
This option was removed in PR #12211.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-11-05 08:30:34 +11:00
robert-hh ae3b1cfab1 mimxrt/modmachine: Fix settings for the MIMXRT1170 board.
These were not changed with commit c0b64a3f2 for using tools/boardgen.py.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-11-05 08:30:18 +11:00
Jim Mussared 09c9c8ac30 stm32/boards/stm32g474_af.csv: Fix final row ADC column.
The original file was missing a trailing , on the final row.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-04 11:00:06 +11:00
Jim Mussared c028f956fc stm32/boards/stm32f4x9_af.csv: Fix DCMI_VSYNC.
This incorrectly had a `(1)` on the end.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-04 09:01:40 +11:00
Jim Mussared 841422817e stm32/boards/make-pins.py: Fix H7 ADC generation.
Fixes are:
- Only emit ADC table entries for pins that aren't cpu-hidden
  (i.e. ignore `X,-Y` rows).
- Only use the P channels on H7.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 19:34:54 +11:00
Angus Gratton 8c432ea2d4 rp2: Remove 1ms timeout to make idle waiting tickless.
The main motivation for doing this was to reduce the latency when the
system is woken by a USB interrupt.  The best_effort_wfe_or_timeout()
function calls into the pico-sdk dynamic timer framework which sets up a
new dynamic timer instance each time, and then has to tear it down before
continuing after a WFE.

Testing Python interrupt latency, it seems to be improved by about 12us
(from average of 46us to 34us running a Pin IRQ).  C-based "scheduled
nodes" should see even lower latency.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-11-03 18:26:51 +11:00
iabdalkader b41055a5a3 rp2/machine_adc: Refactor channel/pin validation code.
This patch ensures that integer channel numbers passed to the ADC
constructor (including temperature sensor) are interpreted as raw
channel numbers, and not cause any GPIO pins to be initialized.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-11-03 18:20:31 +11:00
Maarten van der Schrieck d95f5aa011 rp2/machine_uart: Fix handling of serial break condition.
The FIFO reports not only the bytes read, but also 4 error bits. These were
not checked, leading to NUL value read in case of break and possible
garbage bytes being written on parity/framing error.

This patch addresses the issue that NUL bytes are incorrectly read on
break, and at least provides the boilerplate code and comments for error
handling, that may be implemented in the future.

Signed-off-by: Maarten van der Schrieck <maarten@thingsconnected.nl>
2023-11-03 17:33:28 +11:00
Rene Straub 47ea831c0e stm32: Add STM32H5 support for sleep mode.
Update rtc, machine and powerctrl drivers to support STM32H5 sleep
modes. This makes RTC alarm wakeup working from lightsleep() and
deepsleep().

Changes:
- Determine start reason for machine.reset_cause() in modmachine.c.
- Add proper interrupt clear code in rtc.c.
- Add wakeup functionality in powerctrl_enter_stop_mode(). Remember
  and restore voltage scaling level. Restart HSI48 if it was on before
  entering sleep mode.
- Clear DBGMCU_CR in SystemClock_Config() as for other variants.
  Otherwise debug flags prevent entering sleep mode.

Implementation Notes:
- rtc.c: EXTI_RTSTR1 bits are not present for H5. Code sequence from
  G0/G4/L4/WB/WL would be invalid. RTSTR is only defined for external
  (GPIO) interrupts. Maybe this is also true for other STM32 variants.
- powerctrl_enter_stop_mode() uses complicated, nested conditionals
  to select STM32 variants. To make code slightly better readable,
  comment have been added. A non-nested, #if/#elif sequence would
  make the code more readable. I leave this to the original authors.

Signed-off-by: Rene Straub <rene@see5.ch>
2023-11-03 17:14:05 +11:00
iabdalkader e5014a4d79 stm32: Add configuration options for analog switches.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-11-03 16:27:10 +11:00
Jim Mussared b6a9778484 py/misc: Change sizeof to offsetof for variable-length alloc.
This fixes the case where e.g.

    struct foo_t {
      mp_obj_t x;
      uint16_t y;
      char buf[];
    };

will have `sizeof(struct foo_t)==8`, but `offsetof(struct foo_t, buf)==6`.

When computing the size to allocate for `m_new_obj_var` we need to use
offsetof to avoid over-allocating. This is important especially when it
might cause it to spill over into another GC block.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 16:03:18 +11:00
Mathieu Serandour c85db05244 py/lexer: Change token position for new lines.
Set the position of new line tokens as the end of the preceding line
instead of the beginning of the next line.  This is done by first moving
the pointer to the end of the current line to skip any whitespace, record
the position for the token, then finaly skip any other line and whitespace.

The previous behavior was to skip every new line and whitespace, including
the indent of the next line, before recording the token position.

(Note that both lex->emit_dent and lex->nested_bracket_level equal 0 if
had_physical_newline == true, which allows simplifying the if-logic for
MP_TOKEN_NEWLINE.)

And update the cmd_parsetree.py test expected output, because the position
of the new-line token has changed.

Fixes issue #12792.

Signed-off-by: Mathieu Serandour <mathieu.serandour@numworks.fr>
2023-11-03 15:56:10 +11:00
Damien George 9a4d4db3a1 py/runtime: Remove declaration of function from inside function.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-03 15:21:51 +11:00
Jim Mussared 6ef9b29f88 {cc3200,nrf}/boards/make-pins.py: Add a note about tools/boardgen.py.
It's not worth the effort to update these ports to use boardgen.py, but
put a note just in case anyone uses this as a reference for a new port.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:18:54 +11:00
Jim Mussared 1f804e03f6 renesas-ra/boards/make-pins.py: Update to use tools/boardgen.py.
This removes previously unused functionality to generate pins_ad_const.h,
as well as the unused handling of pin AF in machine_pin.c.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:18:54 +11:00
Jim Mussared c0b64a3f23 mimxrt/boards/make-pins.py: Update to use tools/boardgen.py.
Minor change to remove support for using numeric IDs for machine.Pin.  This
was previously based on the index of the pin in the board csv, but this is
different (and incompatible) with other ports.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:18:54 +11:00
Jim Mussared 4d568a5bd7 samd/boards/make-pins.py: Update to use tools/boardgen.py.
This replaces the previous make-pin-table.py with an implementation based
on boardgen.py.

- MICROPY_PY_MACHINE_PIN_BOARD_CPU macro is removed. This isn't optional
  on other ports, so no need for it to be optional on SAMD.
- pin_af_table is removed, and lookups just search the cpu dict instead
  (this saves N*wordsize bytes of firmware size to have this extra table).
- pins.csv is now BOARD,CPU to match other ports.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:18:32 +11:00
Jim Mussared ff6c2adfd7 stm32/boards/make-pins.py: Add initial support for H7 dual-pad pins.
This fixes the H7 af.csv files to include the dual-pad information, by
listing the ADCs supported on the _C pad with a C_ADC prefix.

Minimal change to make-pins.py to ignore these entries. This will be
implemented later to emit constants (similar to ADC.CORE_TEMP) to access
these channels.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:18:32 +11:00
Jim Mussared 724ebb9916 stm32/boards/make-pins.py: Update to use tools/boardgen.py.
Requires additions to tools/boardgen.py for stm32 pin generation.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:16:49 +11:00
Jim Mussared b4236c7368 stm32: Rename pin_obj_t to machine_pin_obj_t.
This is now consistent with other ports.

Also renamed `pin_{board/cpu}_pins_locals_dict` to
`machine_pin_{board/cpu}_pins_locals_dict`.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:09:08 +11:00
Jim Mussared 286b1b3ed9 stm32/boards: Format stm32 alternate function csv files.
Changes are:
- Pad all cells to make them easier to read.
- Ensure all files have exactly 19 columns (Port,Pin,AF0-15,ADC)

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:08:39 +11:00
Jim Mussared 98dff07bb4 stm32/boards: Fix errors in pins.csv and af.csv.
Fixes are:
- Comment out lines in pins.csv that do not have valid CPU pins.
  It's useful to keep these in the file as "documentation" but in order to
  make make-pins.py stricter they need to be commented out.
- Fix some typos (missing P prefix) in pins.csv.
  This resulted in some missing board pins.
- Fix some typos in af.csv files.
  Some typos of "ADC" and some other that were previously ignored.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:07:10 +11:00
Jim Mussared 4bd6ec9ae4 tools/boardgen.py: Add initial implementation of a common make-pins.py.
For now, this implements the functionality required for esp32 and rp2,
including support for numeric pins, rp2 alternate functions, and rp2
extended pins.

This also updates the rp2 port to use the same structure for pins.h and
pins.csv as for esp32, and moves the pin definitions directly into the
table (rather than having a table of pointers), which is a small code size
improvement.

Support for "hidden" pins in pins.csv is added (matching the stm32
implementation).

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:06:27 +11:00
Jim Mussared b0aec6a0ff esp32/machine_pin: Make irq object a sub-field of pin object.
This simplifies pin generation.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:05:47 +11:00
Jim Mussared 9cabee8252 ports: Standardise arguments and output for make-pins.py script.
All ports now use `--board-csv`, `--prefix`, `--output-souce`,
`--output-header` and no longer write to stdout.  This matches the esp32
implementation.

Ports that have an AF input use `--af-csv` (to match `--board-csv`).

Any additional output files are now prefixed with `output-` (e.g.
`--output-af-const`).

Default arguments are removed (all makefiles should always specify all
arguments, using default values is likely an error).

Replaced the `af-defs-cmp-strings` and `hdr-obj-decls` args for stm32 with
just `mboot-mode`.  Previously they were set on the regular build, now the
logic is reversed so mboot sets it.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:04:35 +11:00
Jim Mussared 1ee5731122 ports: Remove SRC_QSTR_AUTO_DEPS from all ports' Makefiles.
It's unused.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:04:17 +11:00
Jim Mussared 59f3c7facb examples/pins.py: Remove this pins printing example.
It's not supported on all ports, adds complexity to the build to generate
pins_af.py, and can mostly be replicated just by printing the pin objects.

Remove support for generating pins_af.py from all ports (nrf, stm32,
renesas-ra, mimxrt, rp2).

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:03:28 +11:00
Jim Mussared cb37b7bba7 cc3200/boards/make-pins.py: Don't generate qstrs.
The output pins.c can be processed for qstrs like any other C file.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:02:58 +11:00
Jim Mussared df28aa1a59 renesas-ra/boards/make-pins.py: Don't generate qstrs.
The output pins.c can be processed for qstrs like any other C file.

Also remove af_const from Makefile (unimplemented in make-pins.py) and fix
target dependency on ad_const.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:01:30 +11:00
Jim Mussared 3f99dbd634 nrf/boards/make-pins.py: Don't generate qstrs.
The output pins.c can be processed for qstrs like any other C file.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 14:01:04 +11:00
Jim Mussared fc54d25a45 stm32/boards/make-pins.py: Don't generate qstrs.
Qstrs are picked up from the generated pin source files in the usual qstr
processing stage.

Similarly for the stm constant qstrs.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 13:59:19 +11:00
Jim Mussared c3c7c602da rp2/boards/make-pins.py: Don't generate qstrs.
Also remove af-const header, as this is left over from the STM32 version
and unused.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 13:58:07 +11:00
Jim Mussared 2eda513870 py/mkrules.mk: Add rule for compiling auto-generated source files.
This prevents each port Makefile from having to add an explicit rule for
`build-BOARD/pins_BOARD.c`.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 13:57:47 +11:00
Damien George aa329d11ea top: Update .git-blame-ignore-revs for latest formatting commit.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-03 13:32:19 +11:00
Jim Mussared bbd8760bd9 all: Update Python formatting to ruff-format.
This updates a small number of files that change with ruff-format's (vs
black's) rules.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 13:30:41 +11:00
Jim Mussared 303ccca7c6 all: Replace "black" with "ruff format".
- Add config for [tool.ruff.format] to pyproject.toml.
- Update pre-commit to run both ruff and ruff-format (and only check C
  files when running codeformat.py)
- Update CI.
- Simplify codeformat.py to remove all the Python-specific logic (just run
  "ruff format" directly).

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 13:30:38 +11:00
Daniël van de Giessen 7ad84e0422
lib/littlefs: Update LittleFS to v2.8.1.
Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-11-01 17:07:18 +01:00
Andrew Leech 06a7bf967c esp32/usb: Wake main thread when USB receives data.
This improves (decreases) the latency on stdin, on SoCs with built-in USB
and using TinyUSB, like S2 and S3.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2023-11-01 16:27:10 +11:00
Andrew Leech d8a263435f esp32/mphalport: Add function to wake main from separate FreeRTOS task.
Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2023-11-01 16:24:57 +11:00
Alessandro Gatti 95ce61d0ad esp32: Use better build settings for ESP32-C3.
ESP32-C3 is not Xtensa-based, so build settings are now tailored a bit
better following that fact.  ESP-IDF 5.x already adds architecture-specific
modules by itself so there is no need to specify either the `xtensa` or the
`riscv` module in the build settings.

Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2023-11-01 11:38:09 +11:00
Damien George 4cffa848f6 esp32/boards: Reduce size of D2WD and OTA firmware.
Commit c4e63ace66 enabled the SPI Ethernet
driver and that cost about 13k of firwmare size, pushing the firmware over
the limit of the D2WD and OTA board variants available size.

To fix, disable SPI Ethernet on the D2WD variant, and build the OTA variant
with size optimisation rather than performance optimisation.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-01 10:38:52 +11:00
Damien George a614c1d501 extmod: Remove empty utime_mphal.h file.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-31 13:31:54 +11:00
Jim Mussared e579ebb11b teensy: Remove the teensy port.
This port is largely unmaintained, has limited features (the only hardware
support is for GPIO and timer, and no machine module), only supports a
small number of Teensy boards, and can be confused with the mimxrt support
for Teensy 4.x.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
Signed-off-by: Damien George <damien@micropython.org>
2023-10-31 13:04:41 +11:00
Pascal Brunot a8dd69f206 esp32/modmachine: Fix deepsleep() when previous sleep delay was set.
Fixes issue #7158.

Signed-off-by: Pascal Brunot <pascal.brunot@gmail.com>
2023-10-31 12:48:32 +11:00
robert-hh bbbd484f5b esp32/network_lan: Register the hostname setting for Ethernet.
Fixes issue #12817.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-10-31 12:42:36 +11:00
robert-hh 9c244134fb esp32/network_lan: Fix LAN.isconnected().
nic.isconnected() returns now "True", if a) the physical link is up and b)
an IP address is assigned.  The latter happens often by DHCP, in which case
an active connection can be assumed.  If the IP address is set manually,
nic.isconnected() would report "True" as well, if at least the physical
link is up.  This matches WLAN behaviour which returns "True" when the WLAN
has an IP address.

Before, the behaviour of nic.isconneceted() was erratic, returning "True"
sometimes even without a Ethernet cable attached.

Fixes issue #12741.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-10-31 12:42:33 +11:00
robert-hh c4e63ace66 esp32/network_lan: Fix and simplify the code for ETH-SPI devices.
SPI support was not enabled, and was not adapted for esp-idf v5.x.  This
change enables SPI ethernet for all boards and adapts the code for esp-idf
v5.x.  The change follows the sample implementation of @hemakumarm72, but
adds the changes for the other adapters as well.  Further, it simplifies
the code by removing actions from netwwork_lan.c which are done in the
esp-idf drivers later, like setting the default values for .command_bits
and .address_bits, and registering the SPI interface.

Tested with a Wiznet W5500 breakout.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-10-31 12:35:22 +11:00
Daniël van de Giessen b2f220dff8 esp32/boards: Disable ALPN support.
Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-10-31 12:18:16 +11:00
Daniël van de Giessen a1d20e0747 esp32/network_ppp: Reduce PPP thread CPU usage.
Reduces the CPU usage by the PPP thread by sleeping for one tick if
there was nothing to read; preventing the loop using 100% CPU when the
read operation has a zero timeout and immediately returns.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-10-31 12:10:36 +11:00
Daniël van de Giessen f1d6af9819 esp32/machine_uart: Add error checking for IDF API's.
Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-10-31 12:04:33 +11:00
Daniël van de Giessen e676edac79 esp32/mpconfigport: Remove port-specific GAP name.
Instead use the generic default defined in modbluetooth_nimble.c.
This then also allows custom boards to easily override the default
Bluetooth GAP name.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-10-31 12:01:47 +11:00
Daniël van de Giessen f74131134c esp32: Poll serial/JTAG for unread data to prevent blocking.
If data is pushed over serial/JTAG too fast we may fill up stdin_ringbuf
and not be able to read all the data out of the serial/JTAG buffer. Thus
we need to explicitly poll and read the serial/JTAG RX buffer to prevent
blocking (since if the serial/JTAG buffer is already filled, we will not
get another interrupt to transfer it to the stdin ringbuffer).

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-10-31 11:59:15 +11:00
Alessandro Gatti 1cf3085c57 esp32/network_ppp: Allow building with IPv6 disabled.
PPP code assumes that IPv6 support is enabled.  Whilst this is the default,
certain applications may want to disable IPv6 support if not needed (or to
reduce code size).

This makes the code build with CONFIG_LWIP_IPV6 disabled, reducing code by
about 30k in that case.

Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2023-10-31 11:54:25 +11:00
Seon Rozenblum c146017f8a esp32/boards: Update UM board settings to use custom PID/VID.
Signed-off-by: Seon Rozenblum <seon@unexpectedmaker.com>
2023-10-30 17:31:44 +11:00
Seon Rozenblum bdae847082 esp32/boards/UM_TINYWATCHS3: Add new UM TinyWATCH S3 board.
Signed-off-by: Seon Rozenblum <seon@unexpectedmaker.com>
2023-10-30 17:31:21 +11:00
Jim Mussared 64c79a5423 py/qstr: Add support for sorted qstr pools.
This provides a significant performance boost for qstr_find_strn, which is
called a lot during parsing and loading of .mpy files, as well as interning
of string objects (which happens in most string methods that return new
strings).

Also adds comments to explain the "static" qstrs.  These are part of the
.mpy ABI and avoid needing to duplicate string data for QSTRs known to
already be in the firmware.  The static pool isn't currently sorted, but in
the future we could either split the static pool into the sorted regions,
or in the next .mpy version just sort them.

Based on initial work done by @amirgon in #6896.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-30 11:10:02 +11:00
Jim Mussared e910533012 bare-arm/lib: Add minimal strncmp implementation.
Required by upcoming qstr sorting.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-30 11:10:02 +11:00
Jim Mussared 78f4f30cb1 tests/extmod/asyncio_as_uasyncio.py: Fix qstr order dependency.
This test depends on the order in which qstrs are stored in ROM, which
affects the order in which `dir()` will probe the object to see what it
supports.  Because of the lazy-loading in asyncio/__init__.py, if it
tries to do e.g. `wait_for_ms` before `funcs` then it will import funcs,
making `funcs` later succeed. But in the other way around, `funcs` will
initially not be found.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-30 11:10:02 +11:00
Jim Mussared 1a017511d0 tests/perf_bench: Add string/qstr/map tests.
These tests are designed to measure changes in performance relating to:
 - string interning / searching for existing strings
 - map lookup
 - string operations
 - string hashing

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-27 16:16:08 +11:00
iabdalkader 2fda94c286 extmod/network_ninaw10: Fix select flags handling in socket poll.
The flags returned from `select()` were misinterpreted to mean an error had
occurred for the socket, when it's actually just an exceptional condition
for the socket, such as OOB data.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-27 15:49:17 +11:00
Alessandro Gatti b6c369a396 py/asm{arm,thumb,x64,x86,xtensa}: Remove unused macros.
`ASM_MOV_REG_IMM_FIX_U16` and `ASM_MOV_REG_IMM_FIX_WORD` are no longer
used anywhere in the code.

See discussion in #12771.

Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2023-10-27 15:41:02 +11:00
Jim Mussared 6cd99910cd docs/reference/micropython2_migration: Add migration guide.
This is just scaffolding for now, but the idea is that there should be an
addition to this file for every commit that uses the
`MICROPY_PREVIEW_VERSION_2` macro.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-27 15:28:46 +11:00
Jim Mussared 3bf70f16e9 py/mkrules.mk: Add MICROPY_PREVIEW_VERSION_2.
This provides a way to enable features and changes slated for MicroPython
2.x, by running `make MICROPY_PREVIEW_VERSION_2=1`. Also supported for
the cmake ports (except Zephyr).

This is an alternative to having a 2.x development branch (or equivalently,
keeping a 1.x release branch). Any feature or change that needs to be
"hidden" until 2.x can use this flag (either in the Makefile or the
preprocessor).

A good example is changing function arguments or other public API features,
in particular to aid in improving consistency between ports.

When `MICROPY_PREVIEW_VERSION_2` is enabled, the REPL banner is amended to
say "MicroPython (with v2.0 preview) vX.Y.Z", and sys.implementation gets a
new field `_v2` set to `True`.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-27 15:28:46 +11:00
Damien George 3e2706a18d extmod/modmachine: Consolidate mem, i2c and spi headers to modmachine.h.
The contents of machine_mem.h, machine_i2c.h and machine_spi.h have been
moved into extmod/modmachine.h.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 17:40:22 +11:00
Damien George 6989aba93b nrf/modules/machine: Use SPI Python bindings provided by extmod.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 17:37:39 +11:00
Damien George d336c1b79b extmod/modmachine: Consolidate simple machine headers into modmachine.h.
The contents of machine_bitstream.h, machine_pinbase.h, machine_pulse.h and
machine_signal.h have been moved into extmod/modmachine.h.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 16:49:27 +11:00
Damien George 90023b4dcf extmod/modmachine: Clean up decls of machine types to use common ones.
The machine_i2c_type, machine_spi_type and machine_timer_type symbols are
already declared in extmod/modmachine.h and should not be declared anywhere
else.

Also move declarations of machine_pin_type and machine_rtc_type to the
common header in extmod.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 16:20:53 +11:00
Damien George 5b4a2baff6 extmod/machine_uart: Factor ports' UART Python bindings to common code.
This is a code factoring to have the Python bindings in one location, and
all the ports use those same bindings.  For all ports except the two listed
below there is no functional change.

The nrf port has UART.sendbreak() removed, but this method previously did
nothing.

The zephyr port has the following methods added:
- UART.init(): supports setting timeout and timeout_char.
- UART.deinit(): does nothing, just returns None.
- UART.flush(): raises OSError(EINVAL) because it's not implemented.
- UART.any() and UART.txdone(): raise NotImplementedError.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 10:46:42 +11:00
Damien George 95d8b5fd55 extmod/machine_adc: Factor ports' ADC Python bindings to common code.
No functional change, just code factoring to have the Python bindings in
one location, and all the ports use those same bindings.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-23 17:16:45 +11:00
Damien George 48e0986666 nrf/boards: Automatically configure MICROPY_PY_MACHINE_PWM.
This commit makes it so that MICROPY_PY_MACHINE_PWM is enabled if at least
one of MICROPY_PY_MACHINE_HW_PWM and/or MICROPY_PY_MACHINE_SOFT_PWM are
enabled.  This simplifies the configuration for boards, and fixes DVK_BL652
which enabled PWM without selecting software or hardware implementations.

With this change, DVK_BL652 and EVK_NINA_B1 now enable (hardware) PWM.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-23 11:20:49 +11:00
Damien George bb4be837c3 py/makeqstrdefs.py: Print a nicer error when preprocessing stage fails.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-23 10:39:39 +11:00
Damien George 91a3f18391 extmod/machine_i2s: Factor comments, some enums and macros.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George 46ae3b5a34 extmod/machine_i2s: Factor init_helper argument parsing.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George 676f9bb78c extmod/machine_i2s: Factor print function.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George 1477986815 extmod/machine_i2s: Factor I2S.irq method.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George cdd9ad8d62 extmod/machine_i2s: Factor I2S.shift method.
It's exactly the same for all four port implementations.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George a2d7e0da0b extmod/machine_i2s: Factor stream and ring-buf code.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George f2f3ef162d extmod/machine_i2s: Factor ports' I2S Python bindings to common code.
This factors the basic top-level I2S class code from the ports into
extmod/machine_i2s.c:
- I2S class definition and method table.
- The init and deinit method wrappers.
- The make_new code.

Further factoring will follow.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:39:57 +11:00
Damien George 7e7af71527 extmod/machine_pwm: Remove header file and move decls to .c file.
With public declarations moved to extmod/modmachine.h.  It's now mandatory
for a port to define MICROPY_PY_MACHINE_PWM_INCLUDEFILE if it enables
MICROPY_PY_MACHINE_PWM.  This follows how extmod/machine_wdt.c works.

All ports have been updated to work with this modified scheme.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 16:24:46 +11:00
Damien George 60929ec7e2 extmod/machine_wdt: Factor ports' WDT Python bindings to common code.
There are currently 7 ports that implement machine.WDT and a lot of code is
duplicated across these implementations.  This commit factors the common
parts of all these implementations to a single location in
extmod/machine_wdt.c.  This common code provides the top-level Python
bindings (class and method wrappers), and then each port implements the
back end specific to that port.

With this refactor the ports remain functionally the same except for:

- The esp8266 WDT constructor now takes keyword arguments, and accepts the
  "timeout" argument but raises an exception if it's not the default value
  (this port doesn't support changing the timeout).

- The mimxrt and samd ports now interpret the argument to WDT.timeout_ms()
  as signed and if it's negative truncate it to the minimum timeout (rather
  than it being unsigned and a negative value truncating to the maximum
  timeout).

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 15:36:09 +11:00
iabdalkader 2590a34ed7 rp2/boards/ARDUINO_NANO_RP2040_CONNECT: Add external analog pins.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-20 12:18:41 +11:00
iabdalkader 5e52389f99 rp2/machine_adc: Add support for external ADC channels.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-20 12:18:33 +11:00
iabdalkader 4358faab0c drivers/ninaw10: Add support for external ADC channels.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-20 12:18:29 +11:00
iabdalkader 7bbf7910fe extmod/network_ninaw10: Raise an error if nina_ioctl fails.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-20 12:18:00 +11:00
iabdalkader 9ed39553f2 drivers/ninaw10: Add ioctl for reading analog pins.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-20 12:17:55 +11:00
Christian Walther 7be16e0540 extmod/vfs_posix: Additional tests for coverage of error cases.
Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:09 +02:00
Christian Walther be28829ae8 extmod/vfs_posix: Fix getcwd() on non-root VFS.
The unwritten API contract expected of a VFS.getcwd() by mp_vfs_getcwd()
is that its return value should be either "" or "/" when the CWD is at
the root of the VFS and otherwise start with a slash and not end with a
slash. This was not correctly implemented in VfsPosix for instances with
a non-empty root - the required leading slash, if any, was cut off
because the root length includes a trailing slash. This would result in
missing slashes in the middle of the return value of os.getcwd() or in
uninitialized garbage from beyond a string's null terminator when the
CWD was at the VFS root.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:09 +02:00
Christian Walther 0c4fb16871 extmod/vfs_posix: Fix relative paths on non-root VFS.
The unwritten API contract expected of a VFS by mp_vfs_lookup_path() is
that paths passed in are relative to the root of the VFS if they start
with '/' and relative to the current directory of the VFS otherwise.
This was not correctly implemented in VfsPosix for instances with a
non-empty root - all paths were interpreted relative to the root. Fix
that. Since VfsPosix tracks its CWD using the "external" CWD of the Unix
process, the correct handling for relative paths is to pass them through
unmodified.

Also, when concatenating absolute paths, fix an off-by-one resulting in
a harmless double slash (the root path already has a trailing slash).

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:09 +02:00
Christian Walther 5f7065f57a extmod/vfs_posix: Fix accidentally passing tests.
These tests test an unrealistic situation and only pass by accident due
to a bug. The upcoming fix for the bug would make them fail.

The unrealistic situation is that VfsPosix methods are called with
relative paths while the current working directory is somewhere outside
of the root of the VFS. In the intended use of VFS objects via
os.mount() (as opposed to calling methods directly as the tests do),
this never happens, as mp_vfs_lookup_path() directs incoming calls to
the VFS that contains the CWD.

Make the testing situation realistic by changing the working directory
to the root of the VFS before calling methods on it, as the subsequent
relative path accesses expect.

Thanks to the preceding commit, the tests still pass, but still for the
wrong reason. The following commit "Fix relative paths on non-root VFS"
will make them pass for the correct reason.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:08 +02:00
Christian Walther e3ba6f952b extmod/vfs_posix: Fix relative root path.
A VfsPosix created with a relative root path would get confused when
chdir() was called on it and become unable to properly resolve absolute
paths, because changing directories effectively shifted its root. The
simplest fix for that would be to say "don't do that", but since the
unit tests themselves do it, fix it by making a relative path absolute
before storing it.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:08 +02:00
Seon Rozenblum 86c7b957a8 esp32/boards: Update UM board image names for consistency.
Signed-off-by: Seon Rozenblum <seon@unexpectedmaker.com>
2023-10-19 18:21:09 +11:00
Jim Mussared 3883f29485 py/modthread: Initialise nlr_jump_callback_top on threads.
The main thread gets this because the thread state is in bss, but
subsequent threads need this field to be initialised.

Also added a note to mpstate.h to help avoid missing this in the future.

Fixes issue #12695.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-18 09:18:23 +11:00
Kwabena W. Agyeman e78471416b mimxrt/modmachine: Add support for machine.deepsleep.
Signed-off-by: "Kwabena W. Agyeman" <kwagyeman@live.com>
2023-10-17 22:52:18 +11:00
Kwabena W. Agyeman 433158076f mimxrt/machine_rtc: Add RTC alarm/wakeup functionality.
Following the documented Python machine.RTC API.

Signed-off-by: "Kwabena W. Agyeman" <kwagyeman@live.com>
2023-10-17 22:51:53 +11:00
Kwabena W. Agyeman 64ad676424 mimxrt/boards: Define missing SNVS pins for all processors.
Signed-off-by: "Kwabena W. Agyeman" <kwagyeman@live.com>
2023-10-17 22:51:42 +11:00
Jim Mussared c2361328e1 github/workflows: Pin ruff to 0.1.0 and change flags for new version.
The `--format` flag was changed to `--output-format` in the recent update.

Pin to this version to prevent further updates from breaking (e.g. through
new rules or other changes).

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-17 13:56:33 +11:00
Damien George 971f1cf987 stm32/powerctrl: Add support for frequency scaling with HSI on H5 MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-17 12:41:47 +11:00
Damien George e15882ad2b stm32/boards/STM32H573I_DK: Enable ETH and DAC peripherals.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-17 11:44:16 +11:00
Rene Straub 51da8cc28b stm32/eth: Add Ethernet support for H5 MCUs.
This commit implements Ethernet support for STM32H5.  Changes are:

- Add Cortex-M33 MPU code.  Ethernet driver requires MPU to define cache
  strategy for DMA buffers (descriptors and frames).
- Add support for STM32H5 Ethernet controller.  The controller is mostly
  compatible with the STM32H7.  However the descriptor layout is different.
- Adapt clocking and reset for STM32H5.

Tested on NUCLEO-H563ZI and STM32H573I-DK, using ping and iperf3.  TCP
rates of 80-90 Mbits/sec were achievable.

Signed-off-by: Rene Straub <rene@see5.ch>
Signed-off-by: Damien George <damien@micropython.org>
2023-10-17 11:40:54 +11:00
iabdalkader 8b12923da2 stm32/boards/ARDUINO_GIGA: Fix name of pins in board init.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-17 00:35:16 +11:00
robert-hh f84b4617cb rp2/cyw43_configport: Use m_tracked_calloc and m_tracked_free.
When using malloc and free there were out-of-memory situations depending on
the arm-none-eabi package version.  This commit changes malloc/free to use
the MicroPython GC heap instead.

Signed-off-by: robert-hh <robert@hammelrath.com>
Signed-off-by: Damien George <damien@micropython.org>
2023-10-16 23:36:54 +11:00
iabdalkader 4074f828dd stm32/boards/ARDUINO_GIGA: Add QSPI fix/workaround to early init.
This workaround fixes an issue with some production boards that have
an older QSPI flash part revision, which can't handle floating pins.
Note those pins can be reconfigured and reused later.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-16 23:14:13 +11:00
Thomas Ackermann ac4f79592b docs/library/io: Remove io.FileIO and io.TextIOWrapper.
FileIO and TextIOWrapper were removed in
e65d1e69e8.  Remove them also from the
documentation.

Signed-off-by: Thomas Ackermann <th.acker@arcor.de>
2023-10-16 23:07:13 +11:00
Jim Mussared 8eb7721b4a extmod/modframebuf: Remove FrameBuffer1 from natmod build.
This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-16 12:18:43 +11:00
Jim Mussared 03a9fa227d extmod/modframebuf: Fix FrameBuffer get-buffer implementation.
This wasn't correctly accounting for the bits-per-pixel and was returning a
bufinfo struct with the incorrect length.  Instead, just forward directly
to the underlying buffer object.

Fixes issue #12563.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-16 12:18:08 +11:00
Jim Mussared d040478d8a extmod/modframebuf: Validate FrameBuffer bounds against input buffer.
This ensures that the buffer is large enough for the specified width,
height, bits-per-pixel, and stride.

Also makes the legacy FrameBuffer1 constructor re-use the FrameBuffer
make_new to save some code size.

Fixes issue #12562.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-16 12:17:51 +11:00
Damien George a1be5e1439 docs/reference/mpyfiles: Document change in .mpy sub-version.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-16 11:28:32 +11:00
Damien George 6967ff3c58 py/persistentcode: Bump .mpy sub-version.
This is required because the previous commit changed the .mpy native ABI.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-16 11:25:31 +11:00
Damien George 9b63421fb3 py/dynruntime: Add mp_get_buffer.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-16 11:23:11 +11:00
Damien George 9c7ea9b14a py/obj: Generalise mp_get_buffer so it can raise if a flag is set.
This allows mp_get_buffer_raise() to be changed to a simple inline function
that in the majority of cases costs the same (in code size) to call as the
original mp_get_buffer_raise(), because the flags argument is a constant.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-16 11:22:55 +11:00
Damien George 516385c4cc py/objboundmeth: Optimise check for types in binary_op.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-13 15:29:09 +11:00
Ned Konz 66c62353ce tests/basics/boundmeth1.py: Add tests for bound method equality/hash.
This commit adds tests for bound method comparison and hashing to support
the changes in the previous commit.

Signed-off-by: Ned Konz <ned@productcreationstudio.com>
2023-10-13 15:15:49 +11:00
Daniël van de Giessen 4f5e165d0b py/objboundmeth: Support comparing and hashing bound methods.
This behaviour matches CPython.  It's useful to be able to store bound
method objects in dicts/sets, and compare for equality, eg when storing
them in a list and using list.remove().

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-10-13 15:11:49 +11:00
Matthias Urlichs 5f0bd33b73 extmod/asyncio: Emit errors to stderr, not stdout.
Sometimes these are different file descriptors, not to mention the Unix
port, so use stderr to distinguish these error messages.

CPython prints to stdout, but it does it via a call to the logging module.
We don't want to introduce a dependency on logging, so printing to stderr
is a good alternative.  One can override default_exception_handler() if
needed.
2023-10-13 14:55:54 +11:00
Damien George 05cb1406ad extmod/moductypes: Validate that uctypes.struct addr argument is an int.
Fixes issue #12660.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-12 15:47:15 +11:00
Jim Mussared 5015779a6f py/builtinevex: Handle invalid filenames for execfile.
If a non-string buffer was passed to execfile, then it would be passed
as a non-null-terminated char* to mp_lexer_new_from_file.

This changes mp_lexer_new_from_file to take a qstr instead (as in almost
all cases a qstr will be created from this input anyway to set the
`__file__` attribute on the module).

This now makes execfile require a string (not generic buffer) argument,
which is probably a good fix to make anyway.

Fixes issue #12522.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-12 15:17:59 +11:00
robert-hh 480659b1ac ports: Make all ports skip execution of main.py if boot.py fails.
That can be caused e.g. by an exception.  This feature is implemented in
some way already for the stm32, renesas-ra, mimxrt and samd ports.  This
commit adds it for the rp2, esp8266, esp32 and nrf ports.  No change for
the cc3200 and teensy ports.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-10-12 11:53:29 +11:00
Andrew Leech d2a9d70c09 tools/ci.sh: Ensure enough commits are fetched for a common ancestor.
This commit updates the ci script to automatically fetch all upstream if
the common commit hasn't been found; this should preserve the speed of CI
checks for most PR's, and use a reliable but slow fetch if needed for older
ones.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2023-10-11 14:05:14 +11:00
Glenn Moloney 9f835df35e esp32,esp8266: Rename MICROPY_ESPNOW to MICROPY_PY_ESPNOW.
For consistency with other Python-level modules.

Also add the corresponding missing preprocessor guard to esp32/modespnow.c,
so that this port compiles if MICROPY_PY_ESPNOW and MICROPY_PY_NETWORK_WLAN
are set to 0.

Fixes #12622.

Signed-off-by: Glenn Moloney <glenn.moloney@gmail.com>
2023-10-10 17:56:36 +11:00
robert-hh a06f4c8df4 mimxrt/led: Fix LED init call from main, and simplify led_init.
led_init() was not called, and therefore the machine.LED class seemed not
to work.  led_init() now uses mp_hal_pin_output() to configure the pin.

Signed-off-by: robert-hh <robert@hammelrath.com>
2023-10-09 17:10:45 +11:00
Matthias Urlichs 3fb1bb131f py/vm: Don't emit warning when using "raise ... from None".
"Raise SomeException() from None" is a common Python idiom to suppress
chained exceptions and thus shouldn't trigger a warning on a version of
Python that doesn't support them in the first place.
2023-10-09 09:46:02 +11:00
Jim Mussared 5232847771 README.md: Update CI badges.
- Fix URL for the unix badge.
- Add stm32 CI badge.
- Add docs CI badge (linking to the documentation)
- Make docs CI run on push (so we get a badge generated).

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-06 16:39:55 +11:00
Jim Mussared 69e34b6b6b all: Switch to new preview build versioning scheme.
See https://github.com/micropython/micropython/issues/12127 for details.

Previously at the point when a release is made, we update mpconfig.h
and set a git tag. i.e. the version increments at the release.

Now the version increments immediately after the release. The workflow is:
1. Final commit in the cycle updates mpconfig.h to set (X, Y, 0, 0) (i.e.
   clear the pre-release state).
2. This commit is tagged "vX.Y.0".
3. First commit for the new cycle updates mpconfig.h to set (X, Y+1, 0, 1)
   (i.e. increment the minor version, set the pre-release state).
4. This commit is tagged "vX.Y+1.0-preview".

The idea is that a nightly build is actually a "preview" of the _next_
release. i.e. any documentation describing the current release may not
actually match the nightly build. So we use "preview" as our semver
pre-release identifier.

Changes in this commit:
 - Add MICROPY_VERSION_PRERELEASE to mpconfig.h to allow indicating that
   this is not a release version.
 - Remove unused MICROPY_VERSION integer.
 - Append "-preview" to MICROPY_VERSION_STRING when the pre-release state
   is set.
 - Update py/makeversionhdr.py to no longer generate MICROPY_GIT_HASH.
 - Remove the one place MICROPY_GIT_HASH was used (it can use
   MICROPY_GIT_TAG instead).
 - Update py/makeversionhdr.py to also understand
   MICROPY_VERSION_PRERELEASE in mpconfig.h.
 - Update py/makeversionhdr.py to convert the git-describe output into
   semver-compatible "X.Y.Z-preview.N.gHASH".
 - Update autobuild.sh to generate filenames using the new scheme.
 - Update remove_old_firmware.py to match new scheme.
 - Update mpremote's pyproject.toml to handle the "-preview" suffix in the
   tag. setuptools_scm maps to this "rc0" to match PEP440.
 - Fix docs heading where it incorrectly said "vvX.Y.Z" for release docs.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-06 12:10:14 +11:00
1718 zmienionych plików z 60208 dodań i 43476 usunięć

Wyświetl plik

@ -1,3 +1,15 @@
# 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
# all: Fix various spelling mistakes found by codespell 2.2.6.
cf490a70917a1b2d38ba9b58e763e0837d0f7ca7

2
.gitattributes vendored
Wyświetl plik

@ -8,10 +8,12 @@
# These are binary so should never be modified by git.
*.a binary
*.ico binary
*.png binary
*.jpg binary
*.dxf binary
*.mpy binary
*.der binary
# These should also not be modified by git.
tests/basics/string_cr_conversion.py -text

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

@ -11,20 +11,10 @@ jobs:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
- name: Install packages
run: source tools/ci.sh && ci_code_formatting_setup
run: source tools/ci.sh && ci_c_code_formatting_setup
- name: Run code formatting
run: source tools/ci.sh && ci_code_formatting_run
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@v4
- 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 }}
@ -36,7 +42,7 @@ jobs:
run: echo $PR_NUMBER > pr_number
- name: Upload diff
if: github.event_name == 'pull_request'
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: code-size-report
path: |

Wyświetl plik

@ -15,7 +15,7 @@ jobs:
steps:
- name: 'Download artifact'
id: download-artifact
uses: actions/github-script@v6
uses: actions/github-script@v7
with:
result-encoding: string
script: |
@ -56,7 +56,7 @@ jobs:
run: unzip code-size-report.zip
- name: Post comment to pull request
if: steps.download-artifact.outputs.result == 'ok'
uses: actions/github-script@v6
uses: actions/github-script@v7
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |

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

@ -13,6 +13,6 @@ jobs:
- uses: actions/checkout@v4
with:
fetch-depth: '100'
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
- name: Check commit message formatting
run: source tools/ci.sh && ci_commit_formatting_run

Wyświetl plik

@ -1,6 +1,7 @@
name: Build docs
on:
push:
pull_request:
paths:
- docs/**
@ -15,7 +16,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
- name: Install Python packages
run: pip install -r docs/requirements.txt
- name: Build docs

Wyświetl plik

@ -16,13 +16,13 @@ jobs:
# Setting this to zero means fetch all history and tags,
# which hatch-vcs can use to discover the version tag.
fetch-depth: 0
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
- name: Install build tools
run: pip install build
- name: Build mpremote wheel
run: cd tools/mpremote && python -m build --wheel
- name: Archive mpremote wheel
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: mpremote
path: |

Wyświetl plik

@ -18,11 +18,40 @@ concurrency:
cancel-in-progress: true
jobs:
build_idf50:
build_idf:
strategy:
fail-fast: false
matrix:
ci_func: # names are functions in ci.sh
- esp32_build_cmod_spiram_s2
- esp32_build_s3_c3
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v4
- name: Install packages
run: source tools/ci.sh && ci_esp32_idf50_setup
- name: Build
run: source tools/ci.sh && ci_esp32_build
- id: idf_ver
name: Read the ESP-IDF version
run: source tools/ci.sh && echo "IDF_VER=$IDF_VER" | tee "$GITHUB_OUTPUT"
- name: Cached ESP-IDF install
id: cache_esp_idf
uses: actions/cache@v4
with:
path: |
./esp-idf/
~/.espressif/
!~/.espressif/dist/
~/.cache/pip/
key: esp-idf-${{ steps.idf_ver.outputs.IDF_VER }}
- name: Install ESP-IDF packages
if: steps.cache_esp_idf.outputs.cache-hit != 'true'
run: source tools/ci.sh && ci_esp32_idf_setup
- name: ccache
uses: hendrikmuhs/ccache-action@v1.2
with:
key: esp32-${{ matrix.ci_func }}
- name: Build ci_${{matrix.ci_func }}
run: source tools/ci.sh && ci_${{ matrix.ci_func }}

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

@ -18,20 +18,19 @@ concurrency:
cancel-in-progress: true
jobs:
build_pyb:
build_stm32:
strategy:
fail-fast: false
matrix:
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
- name: Install packages
run: source tools/ci.sh && ci_stm32_setup
- name: Build
run: source tools/ci.sh && ci_stm32_pyb_build
- name: Build ci_${{matrix.ci_func }}
run: source tools/ci.sh && ci_${{ matrix.ci_func }}
build_nucleo:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v4
- name: Install packages
run: source tools/ci.sh && ci_stm32_setup
- name: Build
run: source tools/ci.sh && ci_stm32_nucleo_build

Wyświetl plik

@ -1,28 +0,0 @@
name: teensy port
on:
push:
pull_request:
paths:
- '.github/workflows/*.yml'
- 'tools/**'
- 'py/**'
- 'extmod/**'
- 'shared/**'
- 'lib/**'
- 'drivers/**'
- 'ports/teensy/**'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install packages
run: source tools/ci.sh && ci_teensy_setup
- name: Build
run: source tools/ci.sh && ci_teensy_build

Wyświetl plik

@ -55,6 +55,18 @@ jobs:
if: failure()
run: tests/run-tests.py --print-failures
standard_v2:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build
run: source tools/ci.sh && ci_unix_standard_v2_build
- name: Run main test suite
run: source tools/ci.sh && ci_unix_standard_v2_run_tests
- name: Print failures
if: failure()
run: tests/run-tests.py --print-failures
coverage:
runs-on: ubuntu-latest
steps:
@ -76,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
@ -184,7 +197,7 @@ jobs:
runs-on: macos-11.0
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: '3.8'
- name: Build

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,10 +1,13 @@
# https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
name: Python code lint with ruff
name: Python code lint and formatting with ruff
on: [push, pull_request]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install --user ruff
- run: ruff --format=github .
# 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

@ -2,8 +2,8 @@ repos:
- repo: local
hooks:
- id: codeformat
name: MicroPython codeformat.py for changed files
entry: tools/codeformat.py -v -f
name: MicroPython codeformat.py for changed C files
entry: tools/codeformat.py -v -c -f
language: python
- id: verifygitlog
name: MicroPython git commit message format checker
@ -12,6 +12,16 @@ repos:
verbose: true
stages: [commit-msg]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.265
# 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

@ -53,13 +53,16 @@ are then certifying and signing off against the following:
Code auto-formatting
====================
Both C and Python code are auto-formatted using the `tools/codeformat.py`
script. This uses [uncrustify](https://github.com/uncrustify/uncrustify) to
format C code and [black](https://github.com/psf/black) to format Python code.
After making changes, and before committing, run this tool to reformat your
changes to the correct style. Without arguments this tool will reformat all
source code (and may take some time to run). Otherwise pass as arguments to
the tool the files that changed and it will only reformat those.
Both C and Python code formatting are controlled for consistency across the
MicroPython codebase. C code is formatted using the `tools/codeformat.py`
script which uses [uncrustify](https://github.com/uncrustify/uncrustify).
Python code is linted and formatted using
[ruff & ruff format](https://github.com/astral-sh/ruff).
After making changes, and before committing, run `tools/codeformat.py` to
reformat your C code and `ruff format` for any Python code. Without
arguments this tool will reformat all source code (and may take some time
to run). Otherwise pass as arguments to the tool the files that changed,
and it will only reformat those.
uncrustify
==========
@ -101,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
==========================
@ -151,12 +170,22 @@ Tips:
* To ignore the pre-commit message format check temporarily, start the commit
message subject line with "WIP" (for "Work In Progress").
Running pre-commit manually
===========================
Once pre-commit is installed as per the previous section it can be manually
run against the MicroPython python codebase to update file formatting on
demand, with either:
* `pre-commit run --all-files` to fix all files in the MicroPython codebase
* `pre-commit run --file ./path/to/my/file` to fix just one file
* `pre-commit run --file ./path/to/my/folder/*` to fix just one folder
Python code conventions
=======================
Python code follows [PEP 8](https://legacy.python.org/dev/peps/pep-0008/) and
is auto-formatted using [black](https://github.com/psf/black) with a line-length
of 99 characters.
is auto-formatted using [ruff format](https://docs.astral.sh/ruff/formatter)
with a line-length of 99 characters.
Naming conventions:
- Module names are short and all lowercase; eg pyb, stm.

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)
@ -78,8 +82,6 @@ used during the build process and is not part of the compiled source code.
/*/stm32*.h (BSD-3-clause)
/usbdev (MCD-ST Liberty SW License Agreement V2)
/usbhost (MCD-ST Liberty SW License Agreement V2)
/teensy
/core (PJRC.COM)
/zephyr
/src (Apache-2.0)
/tools

Wyświetl plik

@ -1,4 +1,4 @@
[![CI badge](https://github.com/micropython/micropython/workflows/unix%20port/badge.svg)](https://github.com/micropython/micropython/actions?query=branch%3Amaster+event%3Apush) [![codecov](https://codecov.io/gh/micropython/micropython/branch/master/graph/badge.svg?token=I92PfD05sD)](https://codecov.io/gh/micropython/micropython)
[![Unix CI badge](https://github.com/micropython/micropython/actions/workflows/ports_unix.yml/badge.svg)](https://github.com/micropython/micropython/actions?query=branch%3Amaster+event%3Apush) [![STM32 CI badge](https://github.com/micropython/micropython/actions/workflows/ports_stm32.yml/badge.svg)](https://github.com/micropython/micropython/actions?query=branch%3Amaster+event%3Apush) [![Docs CI badge](https://github.com/micropython/micropython/actions/workflows/docs.yml/badge.svg)](https://docs.micropython.org/) [![codecov](https://codecov.io/gh/micropython/micropython/branch/master/graph/badge.svg?token=I92PfD05sD)](https://codecov.io/gh/micropython/micropython)
The MicroPython project
=======================
@ -119,7 +119,6 @@ In addition, the following ports are provided in this repository:
- [rp2](ports/rp2) -- Raspberry Pi RP2040 (including Pico and Pico W).
- [samd](ports/samd) -- Microchip (formerly Atmel) SAMD21 and SAMD51.
- [stm32](ports/stm32) -- STMicroelectronics STM32 family (including F0, F4, F7, G0, G4, H7, L0, L4, WB)
- [teensy](ports/teensy) -- Teensy 3.x.
- [webassembly](ports/webassembly) -- Emscripten port targeting browsers and NodeJS.
- [zephyr](ports/zephyr) -- Zephyr RTOS.

Wyświetl plik

@ -19,56 +19,56 @@ import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath("."))
# The MICROPY_VERSION env var should be "vX.Y.Z" (or unset).
micropy_version = os.getenv("MICROPY_VERSION") or "latest"
micropy_all_versions = (os.getenv("MICROPY_ALL_VERSIONS") or "latest").split(",")
url_pattern = "%s/en/%%s" % (os.getenv("MICROPY_URL_PREFIX") or "/",)
# The members of the html_context dict are available inside topindex.html
micropy_version = os.getenv('MICROPY_VERSION') or 'latest'
micropy_all_versions = (os.getenv('MICROPY_ALL_VERSIONS') or 'latest').split(',')
url_pattern = '%s/en/%%s' % (os.getenv('MICROPY_URL_PREFIX') or '/',)
html_context = {
'cur_version':micropy_version,
'all_versions':[
(ver, url_pattern % ver) for ver in micropy_all_versions
"cur_version": micropy_version,
"all_versions": [(ver, url_pattern % ver) for ver in micropy_all_versions],
"downloads": [
("PDF", url_pattern % micropy_version + "/micropython-docs.pdf"),
],
'downloads':[
('PDF', url_pattern % micropy_version + '/micropython-docs.pdf'),
],
'is_release': micropy_version != 'latest',
"is_release": micropy_version != "latest",
}
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinxcontrib.jquery',
"sphinx.ext.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinxcontrib.jquery",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
templates_path = ["templates"]
# The suffix of source filenames.
source_suffix = '.rst'
source_suffix = ".rst"
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = 'MicroPython'
copyright = '- The MicroPython Documentation is Copyright © 2014-2023, Damien P. George, Paul Sokolovsky, and contributors'
project = "MicroPython"
copyright = "- The MicroPython Documentation is Copyright © 2014-2023, Damien P. George, Paul Sokolovsky, and contributors"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@ -80,41 +80,41 @@ version = release = micropy_version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['build', '.venv']
exclude_patterns = ["build", ".venv"]
# The reST default role (used for this markup: `text`) to use for all
# documents.
default_role = 'any'
default_role = "any"
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# keep_warnings = False
# Global include files. Sphinx docs suggest using rst_epilog in preference
# of rst_prolog, so we follow. Absolute paths below mean "from the base
@ -126,144 +126,148 @@ rst_epilog = """
# -- Options for HTML output ----------------------------------------------
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only import and set the theme if we're building docs locally
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.']
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except:
html_theme = 'default'
html_theme_path = ['.']
html_theme = "default"
html_theme_path = ["."]
else:
html_theme_path = ['.']
html_theme_path = ["."]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = ['.']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = '../../logo/trans-logo.png'
# html_logo = '../../logo/trans-logo.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'static/favicon.ico'
html_favicon = "static/favicon.ico"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
html_static_path = ["static"]
# Add a custom CSS file for HTML generation
html_css_files = [
'custom.css',
"custom.css",
]
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%d %b %Y'
html_last_updated_fmt = "%d %b %Y"
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {"index": "topindex.html"}
# If false, no module index is generated.
#html_domain_indices = True
# html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'MicroPythondoc'
htmlhelp_basename = "MicroPythondoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Include 3 levels of headers in PDF ToC
'preamble': r'\setcounter{tocdepth}{2}',
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Include 3 levels of headers in PDF ToC
"preamble": r"\setcounter{tocdepth}{2}",
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'MicroPython.tex', 'MicroPython Documentation',
'Damien P. George, Paul Sokolovsky, and contributors', 'manual'),
(
master_doc,
"MicroPython.tex",
"MicroPython Documentation",
"Damien P. George, Paul Sokolovsky, and contributors",
"manual",
),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# latex_domain_indices = True
# Enable better Unicode support so that `make latexpdf` doesn't fail
latex_engine = "xelatex"
@ -273,12 +277,17 @@ latex_engine = "xelatex"
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'micropython', 'MicroPython Documentation',
['Damien P. George, Paul Sokolovsky, and contributors'], 1),
(
"index",
"micropython",
"MicroPython Documentation",
["Damien P. George, Paul Sokolovsky, and contributors"],
1,
),
]
# If true, show URL addresses after external links.
#man_show_urls = False
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
@ -287,23 +296,29 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'MicroPython', 'MicroPython Documentation',
'Damien P. George, Paul Sokolovsky, and contributors', 'MicroPython', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"MicroPython",
"MicroPython Documentation",
"Damien P. George, Paul Sokolovsky, and contributors",
"MicroPython",
"One line description of project.",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('https://docs.python.org/3.5', None)}
intersphinx_mapping = {"python": ("https://docs.python.org/3.5", None)}

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
@ -141,7 +151,7 @@ These are working configurations for LAN interfaces of popular boards::
# Olimex ESP32-GATEWAY: power controlled by Pin(5)
# Olimex ESP32 PoE and ESP32-PoE ISO: power controlled by Pin(12)
lan = network.LAN(mdc=machine.Pin(23), mdio=machine.Pin(18), power=machine.Pin(5),
lan = network.LAN(mdc=machine.Pin(23), mdio=machine.Pin(18), power=machine.Pin(5),
phy_type=network.PHY_LAN8720, phy_addr=0,
ref_clk=machine.Pin(17), ref_clk_mode=machine.Pin.OUT)
@ -330,6 +340,19 @@ possible at the same frequency.
See more examples in the :ref:`esp32_pwm` tutorial.
DAC (digital to analog conversion)
----------------------------------
On the ESP32, DAC functionality is available on pins 25, 26.
On the ESP32S2, DAC functionality is available on pins 17, 18.
Use the DAC::
from machine import DAC, Pin
dac = DAC(Pin(25)) # create an DAC object acting on a pin
dac.write(128) # set a raw analog value in the range 0-255, 50% now
ADC (analog to digital conversion)
----------------------------------
@ -637,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

@ -201,10 +201,12 @@ class Lock
TCP stream connections
----------------------
.. function:: open_connection(host, port)
.. function:: open_connection(host, port, ssl=None)
Open a TCP connection to the given *host* and *port*. The *host* address will be
resolved using `socket.getaddrinfo`, which is currently a blocking call.
If *ssl* is a `ssl.SSLContext` object, this context is used to create the transport;
if *ssl* is ``True``, a default context is used.
Returns a pair of streams: a reader and a writer stream.
Will raise a socket-specific ``OSError`` if the host could not be resolved or if
@ -212,12 +214,14 @@ TCP stream connections
This is a coroutine.
.. function:: start_server(callback, host, port, backlog=5)
.. function:: start_server(callback, host, port, backlog=5, ssl=None)
Start a TCP server on the given *host* and *port*. The *callback* will be
called with incoming, accepted connections, and be passed 2 arguments: reader
and writer streams for the connection.
If *ssl* is a `ssl.SSLContext` object, this context is used to create the transport.
Returns a `Server` object.
This is a coroutine.

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

@ -62,12 +62,35 @@ Functions
.. function:: flash_erase(sector_no)
.. function:: osdebug(level)
.. function:: osdebug(uart_no)
Turn esp os debugging messages on or off.
.. note:: This is the ESP8266 form of this function.
The *level* parameter sets the threshold for the log messages for all esp components.
The log levels are defined as constants:
Change the level of OS serial debug log messages. On boot,
OS serial debug log messages are disabled.
``uart_no`` is the number of the UART peripheral which should receive
OS-level output, or ``None`` to disable OS serial debug log messages.
.. function:: osdebug(uart_no, [level])
:no-index:
.. note:: This is the ESP32 form of this function.
Change the level of OS serial debug log messages. On boot, OS
serial debug log messages are limited to Error output only.
The behaviour of this function depends on the arguments passed to it. The
following combinations are supported:
``osdebug(None)`` restores the default OS debug log message level
(``LOG_ERROR``).
``osdebug(0)`` enables all available OS debug log messages (in the
default build configuration this is ``LOG_INFO``).
``osdebug(0, level)`` sets the OS debug log message level to the
specified value. The log levels are defined as constants:
* ``LOG_NONE`` -- No log output
* ``LOG_ERROR`` -- Critical errors, software module can not recover on its own
@ -77,6 +100,15 @@ Functions
* ``LOG_VERBOSE`` -- Bigger chunks of debugging information, or frequent messages
which can potentially flood the output
.. note:: ``LOG_DEBUG`` and ``LOG_VERBOSE`` are not compiled into the
MicroPython binary by default, to save size. A custom build with a
modified "``sdkconfig``" source file is needed to see any output
at these log levels.
.. note:: Log output on ESP32 is automatically suspended in "Raw REPL" mode,
to prevent communications issues. This means OS level logging is never
seen when using ``mpremote run`` and similar tools.
.. function:: set_native_code_location(start, length)
**Note**: ESP8266 only

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()
@ -193,7 +193,7 @@ numbers specified in ``write_pulses`` are multiplied by the resolution to
define the pulses.
``clock_div`` is an 8-bit divider (0-255) and each pulse can be defined by
multiplying the resolution by a 15-bit (0-32,768) number. There are eight
multiplying the resolution by a 15-bit (1-``PULSE_MAX``) number. There are eight
channels (0-7) and each can have a different clock divider.
So, in the example above, the 80MHz clock is divided by 8. Thus the
@ -226,7 +226,7 @@ For more details see Espressif's `ESP-IDF RMT documentation.
``100``) and the output level to apply the carrier to (a boolean as per
*idle_level*).
.. method:: RMT.source_freq()
.. classmethod:: RMT.source_freq()
Returns the source clock frequency. Currently the source clock is not
configurable so this will always return 80MHz.
@ -264,10 +264,10 @@ For more details see Espressif's `ESP-IDF RMT documentation.
**Mode 3:** *duration* and *data* are lists or tuples of equal length,
specifying individual durations and the output level for each.
Durations are in integer units of the channel resolution (as described
above), between 1 and 32767 units. Output levels are any value that can
be converted to a boolean, with ``True`` representing high voltage and
``False`` representing low.
Durations are in integer units of the channel resolution (as
described above), between 1 and ``PULSE_MAX`` units. Output levels
are any value that can be converted to a boolean, with ``True``
representing high voltage and ``False`` representing low.
If transmission of an earlier sequence is in progress then this method will
block until that transmission is complete before beginning the new sequence.
@ -290,6 +290,13 @@ For more details see Espressif's `ESP-IDF RMT documentation.
Passing in no argument will not change the channel. This function returns
the current channel number.
Constants
---------
.. data:: RMT.PULSE_MAX
Maximum integer that can be set for a pulse duration.
Ultra-Low-Power co-processor
----------------------------

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

@ -86,16 +86,6 @@ Functions
Classes
-------
.. class:: FileIO(...)
This is type of a file open in binary mode, e.g. using ``open(name, "rb")``.
You should not instantiate this class directly.
.. class:: TextIOWrapper(...)
This is type of a file open in text mode, e.g. using ``open(name, "rt")``.
You should not instantiate this class directly.
.. class:: StringIO([string])
.. class:: BytesIO([string])

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.
@ -39,9 +39,9 @@ Methods
Configure the ADC peripheral. *bits* will set the resolution of the
conversion process.
.. method:: ADCBlock.connect(channel)
ADCBlock.connect(source)
ADCBlock.connect(channel, source)
.. method:: ADCBlock.connect(channel, *, ...)
ADCBlock.connect(source, *, ...)
ADCBlock.connect(channel, source, *, ...)
Connect up a channel on the ADC peripheral so it is ready for sampling,
and return an :ref:`ADC <machine.ADC>` object that represents that connection.
@ -56,3 +56,6 @@ Methods
If both *channel* and *source* are given then they are connected together
and made ready for sampling.
Any additional keyword arguments are used to configure the returned ADC object,
via its :meth:`init <machine.ADC.init>` method.

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`
@ -39,6 +39,33 @@ class SSLContext
Create a new SSLContext instance. The *protocol* argument must be one of the ``PROTOCOL_*``
constants.
.. method:: SSLContext.load_cert_chain(certfile, keyfile)
Load a private key and the corresponding certificate. The *certfile* is a string
with the file path of the certificate. The *keyfile* is a string with the file path
of the private key.
.. admonition:: Difference to CPython
:class: attention
MicroPython extension: *certfile* and *keyfile* can be bytes objects instead of
strings, in which case they are interpreted as the actual certificate/key data.
.. method:: SSLContext.load_verify_locations(cafile=None, cadata=None)
Load the CA certificate chain that will validate the peer's certificate.
*cafile* is the file path of the CA certificates. *cadata* is a bytes object
containing the CA certificates. Only one of these arguments should be provided.
.. method:: SSLContext.get_ciphers()
Get a list of enabled ciphers, returned as a list of strings.
.. method:: SSLContext.set_ciphers(ciphers)
Set the available ciphers for sockets created with this context. *ciphers* should be
a list of strings in the `IANA cipher suite format <https://wiki.mozilla.org/Security/Cipher_Suites>`_ .
.. method:: SSLContext.wrap_socket(sock, *, server_side=False, do_handshake_on_connect=True, server_hostname=None)
Takes a `stream` *sock* (usually socket.socket instance of ``SOCK_STREAM`` type),
@ -77,6 +104,12 @@ class SSLContext
Set or get the behaviour for verification of peer certificates. Must be one of the
``CERT_*`` constants.
.. note::
``ssl.CERT_REQUIRED`` requires the device's date/time to be properly set, e.g. using
`mpremote rtc --set <mpremote_command_rtc>` or ``ntptime``, and ``server_hostname``
must be specified when on the client side.
Exceptions
----------

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

@ -28,7 +28,7 @@ MIMXRT1060-EVK Debug USB D0/D1 D7/D6 D8/D9
MIMXRT1064-EVK Debug USB D0/D1 D7/D6 D8/D9
MIMXRT1170-EVK Debug USB D0/D1 D12/D11 D10/D13
Adafruit Metro M7 - D0/D1 D7/D3 A1/A0
Olimex RT1010Py - RxD/TxD D5/D6 -
Olimex RT1010Py - RxD/TxD D7/D8 D5/D6
Seeed ARCH MIX - J3_19/J3_20 J4_16/J4_17 J4_06/J4_07
================= =========== =========== =========== ===========
@ -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

@ -92,9 +92,7 @@ Use the :ref:`machine.Pin <machine.Pin>` class::
Available Pins follow the ranges and labelling of the respective board, like:
- 0-33 for Teensy 4.0,
- 0-21 for the MIMXRT10xx-EVK board, or 'D0-Dxx', or 'A0-Ann',
- 0-14 for the Olimex RT1010Py board, or 'D0'-'Dxx' and 'A0'-'Ann'
- 'D0-Dxx', or 'A0-Ann' for Teensy 4.0, MIMXRT10xx-EVK ns Olimex board,
- 'J3_xx', 'J4_xx', 'J5_xx' for the Seeed ARCH MIX board,
or the pin names of the Pin.board or Pin.cpu classes.
@ -106,9 +104,9 @@ Notes:
* At the MIMXRT1010_EVK, pins D4, D5 and D9 of the Arduino connector are by
default not connected to the MCU. For details refer to the schematics.
* At the MIMXRT1170_EVK board, the inner rows of the Arduino connectors are assigned as follows:
- D16 - D23: J9, odd pin numbers; D17 is by default not connected.
- D24 - D27: J26, odd pin numbers; J63-J66 have to be closed to enable these pins.
- D29 - D36: J25, odd pin numbers; D29 and D30 are by default not connected.
- 'D16' - 'D23': J9, odd pin numbers; 'D17' is by default not connected.
- 'D24' - 'D27': J26, odd pin numbers; J63-J66 have to be closed to enable these pins.
- 'D29' - 'D36': J25, odd pin numbers; 'D29' and 'D30' are by default not connected.
There's a higher-level abstraction :ref:`machine.Signal <machine.Signal>`
which can be used to invert a pin. Useful for illuminating active-low LEDs
@ -146,22 +144,22 @@ handling signal groups. ::
from machine import Pin, PWM
# create PWM object from a pin and set the frequency and duty cycle
pwm2 = PWM(Pin(2), freq=2000, duty_u16=32768)
pwm2 = PWM(Pin('D2'), freq=2000, duty_u16=32768)
pwm2.freq() # get the current frequency
pwm2.freq(1000) # set/change the frequency
pwm2.duty_u16() # get the current duty cycle, range 0-65535
pwm2.duty_u16(200) # set the duty cycle, range 0-65535
pwm2.deinit() # turn off PWM on the pin
# create a complementary signal pair on Pin 2 and 3
pwm2 = PWM((2, 3), freq=2000, duty_ns=20000)
pwm2 = PWM(('D2', 'D3'), freq=2000, duty_ns=20000)
# Create a group of four synchronized signals.
# Start with Pin(4) at submodule 0, which creates the sync pulse.
pwm4 = PWM(Pin(4), freq=1000, align=PWM.HEAD)
# Pins 5, 6, and 9 are pins at the same module
pwm5 = PWM(Pin(5), freq=1000, duty_u16=10000, align=PWM.HEAD, sync=True)
pwm6 = PWM(Pin(6), freq=1000, duty_u16=20000, align=PWM.HEAD, sync=True)
pwm9 = PWM(Pin(9), freq=1000, duty_u16=30000, align=PWM.HEAD, sync=True)
# Start with Pin('D4') at submodule 0, which creates the sync pulse.
pwm4 = PWM(Pin('D4'), freq=1000, align=PWM.HEAD)
# Pins D5, D6, and D9 are pins at the same module
pwm5 = PWM(Pin('D5'), freq=1000, duty_u16=10000, align=PWM.HEAD, sync=True)
pwm6 = PWM(Pin('D6', freq=1000, duty_u16=20000, align=PWM.HEAD, sync=True)
pwm9 = PWM(Pin('D9'), freq=1000, duty_u16=30000, align=PWM.HEAD, sync=True)
pwm3 # show the PWM objects properties
@ -256,7 +254,7 @@ Use the :ref:`machine.ADC <machine.ADC>` class::
from machine import ADC
adc = ADC(Pin(32)) # create ADC object on ADC pin
adc = ADC(Pin('A2')) # create ADC object on ADC pin
adc.read_u16() # read value, 0-65536 across voltage range 0.0v - 3.3v
The resolution of the ADC is 12 bit with 10 to 11 bit accuracy, irrespective of the
@ -274,7 +272,7 @@ Software SPI (using bit-banging) works on all pins, and is accessed via the
# construct a SoftSPI bus on the given pins
# polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin('D0'), mosi=Pin('D2'), miso=Pin('D4'))
spi.init(baudrate=200000) # set the baudrate
@ -303,7 +301,7 @@ rates (up to 30Mhz). Hardware SPI is accessed via the
from machine import SPI, Pin
spi = SPI(0, 10000000)
cs_pin = Pin(6, Pin.OUT, value=1)
cs_pin = Pin('D6', Pin.OUT, value=1)
cs_pin(0)
spi.write('Hello World')
cs_pin(1)
@ -311,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:
@ -331,7 +329,7 @@ accessed via the :ref:`machine.SoftI2C <machine.SoftI2C>` class::
from machine import Pin, SoftI2C
i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100000)
i2c = SoftI2C(scl=Pin('D5'), sda=Pin('D4'), freq=100000)
i2c.scan() # scan for devices
@ -365,7 +363,7 @@ See :ref:`machine.I2S <machine.I2S>`. Example using a Teensy 4.1 board with a si
external Codec like UDA1334.::
from machine import I2S, Pin
i2s = I2S(2, sck=Pin(26), ws=Pin(27), sd=Pin(7),
i2s = I2S(2, sck=Pin('D26'), ws=Pin('D27'), sd=Pin('D7'),
mode=I2S.TX, bts=16,format=I2S.STEREO,
rate=44100,ibuf=40000)
i2s.write(buf) # write buffer of audio samples to I2S device
@ -397,7 +395,7 @@ Example using the Teensy audio shield::
from machine import I2C, I2S, Pin
from sgtl5000 import CODEC
i2s = I2S(1, sck=Pin(21), ws=Pin(20), sd=Pin(7), mck=Pin(23),
i2s = I2S(1, sck=Pin('D21'), ws=Pin('D20'), sd=Pin('D7'), mck=Pin('D23'),
mode=I2S.TX, bits=16,rate=44100,format=I2S.STEREO,
ibuf=40000,
)
@ -445,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
--------------
@ -475,7 +473,7 @@ The OneWire driver is implemented in software and works on all pins::
from machine import Pin
import onewire
ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12
ow = onewire.OneWire(Pin('D12')) # create a OneWire bus on GPIO12
ow.scan() # return a list of devices on the bus
ow.reset() # reset the bus
ow.readbyte() # read a byte
@ -505,12 +503,12 @@ The DHT driver is implemented in software and works on all pins::
import dht
import machine
d = dht.DHT11(machine.Pin(4))
d = dht.DHT11(machine.Pin('D4'))
d.measure()
d.temperature() # eg. 23 (°C)
d.humidity() # eg. 41 (% RH)
d = dht.DHT22(machine.Pin(4))
d = dht.DHT22(machine.Pin('D4'))
d.measure()
d.temperature() # eg. 23.6 (°C)
d.humidity() # eg. 41.3 (% RH)

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

@ -1,9 +1,10 @@
import os
# Directory that the project lives in, aka ../..
SITE_ROOT = '/'.join(os.path.dirname(__file__).split('/')[0:-2])
SITE_ROOT = "/".join(os.path.dirname(__file__).split("/")[0:-2])
TEMPLATE_DIRS = (
"%s/templates/" % SITE_ROOT, # Your custom template directory, before the RTD one to override it.
"%s/readthedocs/templates/" % SITE_ROOT, # Default RTD template dir
"%s/templates/"
% SITE_ROOT, # Your custom template directory, before the RTD one to override it.
"%s/readthedocs/templates/" % SITE_ROOT, # Default RTD template dir
)

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

@ -31,3 +31,4 @@ implementation and the best practices to use them.
asm_thumb2_index.rst
filesystem.rst
pyboard.py.rst
micropython2_migration.rst

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

@ -0,0 +1,81 @@
.. _micropython2_migration:
MicroPython 2.0 Migration Guide
===============================
MicroPython 2.0 is the (currently in development, not yet available) next major
release of MicroPython.
After maintaining API compatibility for almost a decade with the ``1.x`` series, in
order to unblock some project-wide improvements MicroPython 2.0 will introduce a
small number of breaking API changes that will require some programs to be
updated. This guide explains how to update your Python code to accommodate these
changes.
This document is a work-in-progress. As more work is done on MicroPython 2.0,
more items will be added to the lists below.
**Note:** There are currently no MicroPython 2.0 firmware builds available for
download. You can build it yourself by enabling the ``MICROPY_PREVIEW_VERSION_2``
config option. As it gets closer to being ready for release, builds will be
provided for both ``1.x.y`` and ``2.0.0-preview``.
Hardware and peripherals
------------------------
Overview
~~~~~~~~
The goal is to improve consistency in the :mod:`machine` APIs across different
ports, making it easier to write code, documentation, and tutorials that work on
any supported microcontroller.
This means that some ports' APIs need to change to match other ports.
Changes
~~~~~~~
*None yet*
OS & filesystem
---------------
Overview
~~~~~~~~
The primary goal is to support the ability to execute :term:`.mpy files <.mpy
file>` directly from the filesystem without first copying them into RAM. This
improves code deployment time and reduces memory overhead and fragmentation.
Additionally, a further goal is to support a more flexible way of configuring
partitions, filesystem types, and options like USB mass storage.
Changes
~~~~~~~
*None yet*
CPython compatibility
---------------------
Overview
~~~~~~~~
The goal is to improve compatibility with CPython by removing MicroPython
extensions from CPython APIs. In most cases this means moving existing
MicroPython-specific functions or classes to new modules.
This makes it easier to write code that works on both CPython and MicroPython,
which is useful for development and testing.
Changes
~~~~~~~
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,9 @@ and .mpy version.
=================== ============
MicroPython release .mpy version
=================== ============
v1.20 and up 6.1
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
v1.11 4
@ -101,6 +103,8 @@ 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
4 to 5 5716c5cf65e9b2cb46c2906f40302401bdd27517

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,44 +17,53 @@ Adafruit ItsyBitsy M0 Express pin assignment table
=== ==== ============ ==== ==== ====== ====== ====== ======
Pin GPIO Pin name IRQ ADC Serial Serial TCC/TC TCC/TC
=== ==== ============ ==== ==== ====== ====== ====== ======
0 PA11 D0 11 19 0/3 2/3 1/1 0/3
1 PA10 D1 10 18 0/2 2/2 1/0 0/2
2 PA14 D2 14 - 2/2 4/2 3/0 0/4
3 PA09 D3 9 17 0/1 2/1 0/1 1/3
4 PA08 D4 - 16 0/0 2/0 0/0 1/2
5 PA15 D5 15 - 2/3 4/3 3/1 0/5
7 PA21 D7 5 - 5/3 3/3 7/1 0/7
9 PA07 D9 7 7 - 0/3 1/1 -
10 PA18 D10 2 - 1/2 3/2 3/0 0/2
11 PA16 D11 0 - 1/0 3/0 2/0 0/6
12 PA19 D12 3 - 1/3 3/3 3/1 0/3
13 PA17 D13 1 - 1/1 3/1 2/1 0/7
14 PA02 A0 2 0 - - - -
15 PB08 A1 8 2 - 4/0 4/0 -
16 PB09 A2 9 3 - 4/1 4/1 -
17 PA04 A3 4 4 - 0/0 0/0 -
18 PA05 A4 5 5 - 0/1 0/1 -
19 PB02 A5 2 - - 5/0 6/0 -
20 PA22 SDA 6 - 3/0 5/0 4/0 0/4
21 PA23 SCL 7 - 3/1 5/1 4/1 0/5
22 PB10 MOSI 10 - - 4/2 5/0 0/4
23 PA12 MISO 12 - 2/0 4/0 2/0 0/6
24 PB11 SCK 11 - - 4/3 5/1 0/5
25 PA00 DOTSTAR_CLK 0 - - 1/0 2/0 -
26 PA01 DOTSTAR_DATA 1 - - 1/1 2/1 -
27 PB22 FLASH_MOSI 6 - - 5/2 7/0 -
28 PB03 FLASH_MISO 3 - - 5/1 6/1 -
29 PB23 FLASH_SCK 7 - - 5/3 7/1 -
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
9 PA09 D3 9 17 0/1 2/1 0/1 1/3
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 -
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 -
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 -
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 -
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 - - - - -
=== ==== ============ ==== ==== ====== ====== ====== ======
Description of the columns:
- *Pin* - The number that is expected at ``machine.Pin(n)``, if the pin is given
as a number. This is NOT the GPIO number, but the board pin number, as
given in the board specific definition file.
- *GPIO* - The GPIO number.
- *Pin Name* - The name of a Pin which is expected argument to ``machine.Pin("name")``.
as a number.
- *GPIO* - The GPIO name, which can be used as argument to ``machine.Pin("name")``.
- *Pin Name* - The boards name, which can be used as argument to ``machine.Pin("name")``.
- *IRQ* - The IRQ number assigned to that GPIO, used internally by ``Pin.irq()``. When
using ``Pin.irq()``, different pins must use different IRQs
- *ADC* - The ADC channel assigned to the pin. When using ADC, different pins must
@ -183,10 +192,9 @@ Pin GPIO Pin name IRQ ADC ADC Serial Serial TC PWM PWM
Description of the columns:
- *Pin* - The number that is expected at ``machine.Pin(n)``, if the pin is given
as a number. This is NOT the GPIO number, but the board pin number, as
given in the board specific definition file.
- *GPIO* - The GPIO number.
- *Pin Name* The name of a Pin which is expected argument to ``machine.Pin("name")``.
as a number.
- *GPIO* - The GPIO name, which can be used as argument to ``machine.Pin("name")``.
- *Pin Name* - The boards name, which can be used as argument to ``machine.Pin("name")``.
- *IRQ* - The IRQ number assigned to that GPIO, used internally by ``Pin.irq()``. When
using ``Pin.irq()``, different pins must use different IRQs
- *ADC* - The ADC0/1 channel assigned to the pin. When using ADC, different pins must
@ -340,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
@ -356,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
@ -375,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
=== ==== ============ ==== ==== ==== ====== ====== ===== ===== =====
@ -862,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
@ -876,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:
@ -913,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

@ -9,7 +9,7 @@
{% if is_release %}
<div class="wy-alert wy-alert-danger">
<p>
This is the v{{ release }} version of the MicroPython
This is the {{ release }} version of the MicroPython
documentation. The <a href="/en/latest/{{ pagename }}.html">latest
development version</a> of this page may be more current.
</p>

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

@ -49,9 +49,9 @@ extern uint8_t mp_bluetooth_hci_cmd_buf[4 + 256];
#include "uart.h"
// Provided by the port.
extern pyb_uart_obj_t mp_bluetooth_hci_uart_obj;
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,11 +64,11 @@ 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) {
MICROPY_EVENT_POLL_HOOK
mp_event_wait_indefinite();
}
buf[i] = c;
}
@ -88,7 +88,7 @@ STATIC int cywbt_hci_cmd_raw(size_t len, uint8_t *buf) {
int sz = buf[2] - 3;
for (int c, i = 0; i < sz; ++i) {
while ((c = mp_bluetooth_hci_uart_readchar()) == -1) {
MICROPY_EVENT_POLL_HOOK
mp_event_wait_indefinite();
}
buf[i] = c;
}
@ -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,7 +29,10 @@
#include "py/runtime.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "extmod/machine_pulse.h"
#if MICROPY_PY_MACHINE_PULSE
#include "extmod/modmachine.h"
#include "drivers/dht/dht.h"
// Allow the open-drain-high call to be DHT specific for ports that need it
@ -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

@ -34,9 +34,7 @@
#include <string.h>
#include "py/runtime.h"
#include "modmachine.h"
#include "extmod/machine_spi.h"
#include "mpconfigboard.h"
#include "extmod/modmachine.h"
#ifdef MICROPY_HW_WIFI_LED
#include "led.h"
#endif
@ -46,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

@ -42,9 +42,13 @@
#define NINA_GPIO_MODE (0x50)
#define NINA_GPIO_READ (0x53)
#define NINA_GPIO_READ_ANALOG (0x54)
#define NINA_GPIO_WRITE (0x51)
#define NINA_GPIO_IS_INPUT_ONLY(p) ((p >= 34 && p <= 36) || (p == 39))
#define NINA_GPIO_IS_INPUT_ONLY(p) ((p >= 3 && p <= 6))
#define NINA_GPIO_IS_ADC_CHANNEL(p) ((p >= 3 && p <= 6))
// This maps logical pin ID (0..MICROPY_HW_PIN_EXT_COUNT) to
// physical pins on the Nina module.
static uint8_t pin_map[MICROPY_HW_PIN_EXT_COUNT] = {
27, // LEDR
25, // LEDG
@ -55,10 +59,30 @@ static uint8_t pin_map[MICROPY_HW_PIN_EXT_COUNT] = {
35, // A7
};
// This maps logical pin ID (0..MICROPY_HW_PIN_EXT_COUNT) to
// ADC channel numbers on the Nina module.
static uint8_t adc_map[MICROPY_HW_PIN_EXT_COUNT] = {
-1, // LEDR
-1, // LEDG
-1, // LEDB
6, // A4
3, // A5
0, // A6
7, // A7
};
void machine_pin_ext_init(void) {
nina_init();
}
bool machine_pin_ext_is_adc_channel(const machine_pin_obj_t *self) {
return NINA_GPIO_IS_ADC_CHANNEL(self->id);
}
uint32_t machine_pin_ext_to_adc_channel(const machine_pin_obj_t *self) {
return adc_map[self->id];
}
void machine_pin_ext_set(machine_pin_obj_t *self, bool value) {
if (self->id >= 0 && self->id < MICROPY_HW_PIN_EXT_COUNT) {
uint8_t buf[] = {pin_map[self->id], value};
@ -76,8 +100,14 @@ bool machine_pin_ext_get(machine_pin_obj_t *self) {
return value;
}
uint16_t machine_pin_ext_read_u16(uint32_t channel) {
uint16_t buf = channel;
nina_ioctl(NINA_GPIO_READ_ANALOG, sizeof(buf), (uint8_t *)&buf, 0);
return buf;
}
void machine_pin_ext_config(machine_pin_obj_t *self, int mode, int value) {
if (mode == MACHINE_PIN_MODE_IN) {
if (mode == MACHINE_PIN_MODE_IN || mode == MACHINE_PIN_MODE_ANALOG) {
mode = NINA_GPIO_INPUT;
self->is_output = false;
} else if (mode == MACHINE_PIN_MODE_OUT) {
@ -89,7 +119,7 @@ void machine_pin_ext_config(machine_pin_obj_t *self, int mode, int value) {
if (self->id >= 0 && self->id < MICROPY_HW_PIN_EXT_COUNT) {
uint8_t buf[] = {pin_map[self->id], mode};
if (mode == NINA_GPIO_OUTPUT) {
if (NINA_GPIO_IS_INPUT_ONLY(buf[0])) {
if (NINA_GPIO_IS_INPUT_ONLY(self->id)) {
mp_raise_ValueError("only Pin.IN is supported for this pin");
}
machine_pin_ext_set(self, value);

Wyświetl plik

@ -75,12 +75,13 @@ static int nina_hci_cmd(int ogf, int ocf, size_t param_len, const uint8_t *param
// Receive HCI event packet, initially reading 3 bytes (HCI Event, Event code, Plen).
for (mp_uint_t start = mp_hal_ticks_ms(), size = 3, i = 0; i < size;) {
while (!mp_bluetooth_hci_uart_any()) {
MICROPY_EVENT_POLL_HOOK
mp_uint_t elapsed = mp_hal_ticks_ms() - start;
// Timeout.
if ((mp_hal_ticks_ms() - start) > HCI_COMMAND_TIMEOUT) {
if (elapsed > HCI_COMMAND_TIMEOUT) {
error_printf("timeout waiting for HCI packet\n");
return -1;
}
mp_event_wait_ms(HCI_COMMAND_TIMEOUT - elapsed);
}
buf[i] = mp_bluetooth_hci_uart_readchar();

Wyświetl plik

@ -35,9 +35,7 @@
#include <string.h>
#include "py/runtime.h"
#include "modmachine.h"
#include "extmod/machine_spi.h"
#include "mpconfigboard.h"
#include "extmod/modmachine.h"
#include "nina_bsp.h"
#include "nina_wifi_drv.h"

Wyświetl plik

@ -684,6 +684,14 @@ int nina_ioctl(uint32_t cmd, size_t len, uint8_t *buf, uint32_t iface) {
return -1;
}
break;
case NINA_CMD_GET_ANALOG_READ: {
if (len != 2 || nina_send_command_read_vals(NINA_CMD_GET_ANALOG_READ,
1, ARG_8BITS, NINA_ARGS(ARG_BYTE(buf[0])),
1, ARG_8BITS, NINA_VALS({(uint16_t *)&len, buf})) != 0) {
return -1;
}
break;
}
default:
return 0;
}

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

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