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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
This was previously hard-coded to "Micropy" / "Mass Storage" / "1.0".
Now allow it to be overridden by a board.
Also change "Micropy" to "MicroPy" and "1.0" to "1.00" to match stm32.
This work was funded through GitHub Sponsors.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
The DHCP server broadcasts messages. They are being sent via the default
netif which might be completely the wrong network. We want to send
messages to the netif we got the original message from.
Original author: [Peter Harper](https://github.com/peterharperuk)
Source: https://github.com/raspberrypi/pico-examples/pull/392
Signed-off-by: Samveen <samveen@samveen.in>
There are enough places that implement __exit__ by forwarding directly to
mp_stream_close that this saves code size.
For the cases where __exit__ is a no-op, additionally make their
MP_STREAM_CLOSE ioctl handled as a no-op.
This work was funded through GitHub Sponsors.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
On targets that provide a reference TinyUSB implementation, like ESP32,
the SDK already defines and implements standard callback functions such
as tud_cdc_line_state_cb(). This causes a symbol clash when enabling
shared implementations like the MicroPython 1200 touch functionality.
To avoid this symbol clash, add an optional macro to allow ports to
use a different function name in the shared implementation.
Signed-off-by: Luca Burelli <l.burelli@arduino.cc>
Previously sys.path could be modified by append/pop or slice assignment.
This allows `sys.path = [...]`, which can be simpler in many cases, but
also improves CPython compatibility.
It also allows sys.path to be set to a tuple which means that you can
clear sys.path (e.g. temporarily) with no allocations.
This also makes sys.path (and sys.argv for consistency) able to be disabled
via mpconfig. The unix port (and upytesthelper) require them, so they
explicitly verify that they're enabled.
This work was funded through GitHub Sponsors.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
This fixes:
- type-comparison (E721): do not compare types, use isinstance().
- string-dot-format-missing-arguments (F524): .format call is missing
argument(s) for placeholder(s): {message}.
- f-string-missing-placeholders (F541).
- is-literal (F632): Use != to compare constant literals.
The last one is fixed by just comparing for truthfulness of `state`.
This reverts commit 0613d3e356.
The value of CFG_TUD_CDC_EP_BUFSIZE should match the endpoint size,
otherwise data may stay in the lower layers of the USB stack (and not
passed up to the higher layers) until a total of CFG_TUD_CDC_EP_BUFSIZE
bytes have been received, which may not happen for a long time.
Fixes issue #11253.
Signed-off-by: Damien George <damien@micropython.org>
Helps prevent the filesystem from getting formatted by mistake, among other
things. For example, on a Pico board, entering Ctrl+D and Ctrl+C fast many
times will eventually wipe the filesystem (without warning or notice).
Further rationale: Ctrl+C is used a lot by automation scripts (eg mpremote)
and UI's (eg Mu, Thonny) to get the board into a known state. If the board
is not responding for a short time then it's not possible to know if it's
just a slow start up (eg in _boot.py), or an infinite loop in the main
application. The former should not be interrupted, but the latter should.
The only way to distinguish these two cases would be to wait "long enough",
and if there's nothing on the serial after "long enough" then assume it's
running the application and Ctrl+C should break out of it. But defining
"long enough" is impossible for all the different boards and their possible
behaviour. The solution in this commit is to make it so that frozen
start-up code cannot be interrupted by Ctrl+C. That code then effectively
acts like normal C start-up code, which also cannot be interrupted.
Note: on the stm32 port this was never seen as an issue because all
start-up code is in C. But now other ports start to put more things in
_boot.py and so this problem crops up.
Signed-off-by: David Grayson <davidegrayson@gmail.com>
Previously, setting MICROPY_HW_ENABLE_USBDEV to 0 caused build errors. The
change affects the nrf and samd ports as well, so MICROPY_HW_ENABLE_USBDEV
had to be explicitly enabled there.
The configuration options MICROPY_HW_ENABLE_USBDEV and
MICROPY_HW_ENABLE_UART_REPL are independent, and can be enabled or disabled
by a board.
Signed-off-by: Damien George <damien@micropython.org>
The C-level printf is usually used for internal debugging prints, and a
port/board may want to redirect this somewhere other than stdout.
Signed-off-by: Damien George <damien@micropython.org>
The previous computation incorrectly assumed that the uint32_t ticks
counter MICROPY_SOFT_TIMER_TICKS_MS was in the range [0,0x80000000) where
its actually [0,0xffffffff]. This means the diff calculation can be
simplified compared to the original implementation copied from
utime_mphal.c, which has to deal with a ticks range constrained by the
small int range.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
Before, both uwTick and mp_hal_ticks_ms() were used as clock source. That
assumes, that these two are synchronous and start with the same value,
which may be not the case for all ports. If the lag between uwTick and
mp_hal_ticks_ms() is larger than the timer interval, the timer would either
rush up until the times are synchronous, or not start until uwTick wraps
over.
As suggested by @dpgeorge, MICROPY_SOFT_TIMER_TICKS_MS is now used in
softtimer.c, which has to be defined in a port's mpconfigport.h with
the variable that holds the SysTick counter.
Note that it's not possible to switch everything in softtimer.c to use
mp_hal_ticks_ms() because the logic in SysTick_Handler that schedules
soft_timer_handler() uses (eg on mimxrt) the uwTick variable directly
(named systick_ms there), and mp_hal_ticks_ms() uses a different source
timer. Thus it is made fully configurable.
This drops the `.cpu` directive from the ARM gchelper_*.s files. Having
this directive breaks the linker when targeting older CPUs (e.g. `-mthumb
-mthumb-interwork` for `-mcpu=arm7tdmi`). The actual target CPU should be
determined by the compiler options.
The exact CPU doesn't actually matter, but rather the supported assembly
instruction set. So the files are renamed to *_thumb1.s and *thumb2.s to
indicate the instruction set support instead of the CPU support.
Signed-off-by: David Lechner <david@pybricks.com>
App the mp_ prefix to usbd_ symbols and files which are defined here and
not in TinyUSB.
rp2 only for now. This includes some groundwork for dynamic USB devices
(defined in Python).
This work was funded through GitHub Sponsors.
Signed-off-by: Angus Gratton <angus@redyak.com.au>
Instead of being an explicit field, it's now a slot like all the other
methods.
This is a marginal code size improvement because most types have a make_new
(100/138 on PYBV11), however it improves consistency in how types are
declared, removing the special case for make_new.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
The goal here is to remove a slot (making way to turn make_new into a slot)
as well as reduce code size by the ~40 references to mp_identity_getiter
and mp_stream_unbuffered_iter.
This introduces two new type flags:
- MP_TYPE_FLAG_ITER_IS_ITERNEXT: This means that the "iter" slot in the
type is "iternext", and should use the identity getiter.
- MP_TYPE_FLAG_ITER_IS_CUSTOM: This means that the "iter" slot is a pointer
to a mp_getiter_iternext_custom_t instance, which then defines both
getiter and iternext.
And a third flag that is the OR of both, MP_TYPE_FLAG_ITER_IS_STREAM: This
means that the type should use the identity getiter, and
mp_stream_unbuffered_iter as iternext.
Finally, MP_TYPE_FLAG_ITER_IS_GETITER is defined as a no-op flag to give
the default case where "iter" is "getiter".
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>