Compare commits

...

875 Commits

Author SHA1 Message Date
Daniel Thompson 6b1aabac14 py/objboundmeth: Implement equality comparisons
Currently different bound method instances will compare as unequal even
when both instances bind the same method and object. This is different
to the CPython implementation and, for example, will cause problems
when working with lists that contain callbacks since things like
list.remove() will not work correctly.

Fix this the obvious way by introducing a binary op and implementing
MP_BINARY_OP_EQUAL. A simple test case is provided.

Currently this is unconditionally compiled and on a Thumb2 system
(ports/nrf) it resulted in a 68 byte increase in code size.

Signed-off-by: Daniel Thompson <daniel@redfelineninja.org.uk>
2020-11-14 12:09:58 +00:00
Jim Mussared 61d1e4b01b extmod/nimble: Make stm32 and unix NimBLE ports use synchronous events.
This changes stm32 from using PENDSV to run NimBLE to use the MicroPython
scheduler instead.  This allows Python BLE callbacks to be invoked directly
(and therefore synchronously) rather than via the ringbuffer.

The NimBLE UART HCI and event processing now happens in a scheduled task
every 128ms.  When RX IRQ idle events arrive, it will also schedule this
task to improve latency.

There is a similar change for the unix port where the background thread now
queues the scheduled task.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared 81e92d3d6e extmod/modbluetooth: Re-instate optional no-ringbuf modbluetooth.
This requires that the event handlers are called from non-interrupt context
(i.e. the MicroPython scheduler).

This will allow the BLE stack (e.g. NimBLE) to run from the scheduler
rather than an IRQ like PENDSV, and therefore be able to invoke Python
callbacks directly/synchronously.  This allows writing Python BLE handlers
for events that require immediate response such as _IRQ_READ_REQUEST (which
was previous a hard IRQ) and future events relating to pairing/bonding.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared 6d9fdff8d0 extmod/nimble: Poll startup directly rather than using NimBLE sem.
Using a semaphore (the previous approach) will only run the UART, whereas
for startup we need to also run the event queue.

This change makes it run the full scheduler hook.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared c398e46b29 extmod/modbluetooth: Combine gattc-data-available callbacks into one.
Instead of having the stack indicate a "start", "data"..., "end", pass
through the data in one callback as an array of chunks of data.

This is because the upcoming non-ringbuffer modbluetooth implementation
cannot buffer the data in the ringbuffer and requires instead a single
callback with all the data, to pass to the Python callback.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared 4559bcb467 unix: Make mp_hal_delay_ms run MICROPY_EVENT_POLL_HOOK.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Andrew Leech de60aa7d6b unix: Handle pending events/scheduler in MICROPY_EVENT_POLL_HOOK.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared 3d890e7ab4 extmod/modbluetooth: Make UUID type accessible outside modbluetooth.c.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared c75ce37910 tests/run-multitests.py: Add a -p flag to run permutations of instances.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared ccfd535af4 tests/multi_bluetooth: Improve reliability of event waiting.
Use the same `wait_for_event` in all tests that doesn't hold a reference to
the event data tuple and handles repeat events.

Also fix a few misc reliability issues around timeouts and sequencing.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared 309fb822e6 tests/run-multitests.py: Fix diff order, show changes relative to truth.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:18:20 +11:00
Damien George cc2a35b7b2 stm32/rtc: Validate the RTC prescaler on boot and change if incorrect.
Devices with RTC backup-batteries have been shown (very rarely) to have
incorrect RTC prescaler values.  Such incorrect values mean the RTC counts
fast or slow, and will be wrong forever if the power/backup-battery is
always present.

This commit detects such a state at start up (hard reset) and corrects it
by reconfiguring the RTC prescaler values.

Signed-off-by: Damien George <damien@micropython.org>
2020-11-13 11:23:52 +11:00
Damien George a0623a081c stm32/Makefile: Allow boards to extend all SRC variables.
And rename SRC_HAL -> HAL_SRC_C and SRC_USBDEV -> USBDEV_SRC_C for
consistency with other source variables.

Follow on from 0fff2e03fe

Signed-off-by: Damien George <damien@micropython.org>
2020-11-13 11:22:28 +11:00
Arrowana 922f81dfd1 extmod/machine_mem: Only allow integers in machine.memX subscript.
Prior to this change machine.mem32['foo'] (or using any other non-integer
subscript) could result in a fault due to 'foo' being interpreted as an
integer.  And when writing code it's hard to tell if the fault is due to a
bad subscript type, or an integer subscript that specifies an invalid
memory address.

The type of the object used in the subscript is now tested to be an
integer by using mp_obj_get_int_truncated instead of
mp_obj_int_get_truncated.  The performance hit of this change is minimal,
and machine.memX objects are more for convenience than performance (there
are many other ways to read/write memory in a faster way),

Fixes issue #6588.
2020-11-13 11:13:37 +11:00
Jonathan Hogg 8a917ad252 esp32/machine_pin: Reset pin if init sets mode.
This will forcibly grab the pin back from the ADC if it has previously been
associated with it.

Fixes #5771.
2020-11-12 15:27:41 +11:00
SĂ©bastien NEDJAR b04240cb77 stm32/Makefile: Make the generation of `firmware.bin` explicit.
The file `$(BUILD)/firmware.bin` was used by the target `deploy-stlink` and
`deploy-openocd` but it was generated indirectly by the target
`firmware.dfu`.

As this file could be used to program boards directly by a Mass Storage
copy, it's better to make it explicitly generated.

Additionally, some target are refactored to remove redundancy and be more
explicit on dependencies.
2020-11-12 15:22:44 +11:00
Jim Mussared a7932ae4e6 tools/makeqstrdefs.py: Run qstr preprocessing in parallel.
This gives a substantial speedup of the preprocessing step, i.e. the
generation of qstr.i.last.  For example on a clean build, making
qstr.i.last:

    21s -> 4s on STM32 (WB55)
    8.9 -> 1.8s on Unix (dev).

Done in collaboration with @stinos.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-12 15:04:53 +11:00
Damien George d7e1526593 py/binary: Fix sign extension setting wide integer on 32-bit archs.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 22:18:24 +11:00
Damien George bdfb584b29 extmod/moductypes: Fix storing to (U)INT64 arrays on 32-bit archs.
Fixes issue #6583.

Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 22:18:24 +11:00
Damien George 1fef5662ab py/mpz: Do sign extension in mpz_as_bytes for negative values.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 22:18:24 +11:00
Damien George 7789cd5f16 lib/utils/pyexec: Add MICROPY_BOARD hooks before/after executing code.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 21:47:13 +11:00
Damien George b99300b53e stm32/boardctrl: Define MICROPY_BOARD_EARLY_INIT alongside others.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 21:47:13 +11:00
Damien George 4c3976bbca stm32: Add MICROPY_BOARD calls in various places in stm32_main.
For a board to have full configurability of the soft reset loop.

Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 21:41:04 +11:00
Damien George 1e297c8898 stm32/main: Move update_reset_mode to outside the soft-reset loop.
Running the update inside the soft-reset loop will mean that (on boards
like PYBD that use a bootloader) the same reset mode is used each
reset loop, eg factory reset occurs each time.

Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 21:41:04 +11:00
Jim Mussared b7883ce74c extmod/nimble/nimble.mk: Add -Wno-old-style-declaration.
This is needed since -Wextra was added to the build in
bef412789e

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-05 10:14:19 +11:00
Jim Mussared 2ae3c890bd extmod/btstack/btstack.mk: Add -Wimplicit-fallthrough=0.
This is needed since -Wextra was added to the build in
bef412789e

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-05 10:13:12 +11:00
Damien George ed7ddd4dd4 tests/micropython/extreme_exc.py: Unlink alloc'd lists earlier in chain.
To help the GC collect this memory that's no longer needed after the test.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 23:35:36 +11:00
Damien George 97960dc7de stm32: Support C++ code and user C modules written in C++.
Also build user C modules as part of the stm32 CI.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 23:35:36 +11:00
Damien George df3b466d6c stm32/boards: Factor out common data/bss/heap/stack linker sections.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 23:31:59 +11:00
Damien George a866f868f8 unix/Makefile: Move coverage.c and coveragecpp.cpp to coverage variant.
So that g++ is not needed to build a non-coverage unix variant.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 23:30:04 +11:00
Damien George dbb13104ca docs/develop/cmodules.rst: Add link to source code for user C example.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 23:10:43 +11:00
stijn 25c4563f26 examples: Add example code for user C modules, both C and C++.
Add working example code to provide a starting point for users with files
that they can just copy, and include the modules in the coverage test to
verify the complete user C module build functionality.  The cexample module
uses the code originally found in cmodules.rst, which has been updated to
reflect this and partially rewritten with more complete information.
2020-10-29 15:30:42 +11:00
stijn fad4079778 esp32,unix: Support building C++ code.
Support building .cpp files and linking them into the micropython
executable in a way similar to how it is done for .c files.  The main
incentive here is to enable user C modules to use C++ files (which are put
in SRC_MOD_CXX by py.mk) since the core itself does not utilize C++.

However, to verify build functionality a unix overage test is added.  The
esp32 port already has CXXFLAGS so just add the user modules' flags to it.
For the unix port use a copy of the CFLAGS but strip the ones which are not
usable for C++.
2020-10-29 15:29:50 +11:00
stijn 0153148fd2 py/py.mk: Support C++ code for user C modules.
Support C++ code in .cpp files by providing CXX counterparts of the
_USERMOD_ flags we have for C already.  This merely enables the Makefile of
user C modules to use variables specific to C++ compilation, it is still up
to each port's main Makefile to also include these in the build.
2020-10-29 15:29:20 +11:00
stijn 78c8b55067 docs: Fix reference to QSTR_GEN_CFLAGS Makefile flag. 2020-10-29 15:28:18 +11:00
stijn e498a8bd13 py: Workaround clang error when building misc.h with C++ compiler. 2020-10-29 15:28:14 +11:00
stijn 8e94fa0d2e py/makeqstrdefs.py: Support preprocessing C++ files for QSTR generation.
When SCR_QSTR contains C++ files they should be preprocessed with the same
compiler flags (CXXFLAGS) as they will be compiled with, to make sure code
scanned for QSTR occurrences is effectively the code used in the rest of
the build.  The 'split SCR_QSTR in .c and .cpp files and process each with
different flags' logic isn't trivial to express in a Makefile and the
existing principle for deciding which files to preprocess was already
rather complicated, so the actual preprocessing is moved into
makeqstrdefs.py completely.
2020-10-29 15:27:30 +11:00
stijn f1666419a8 py/mkrules.mk: Add target for compiling C++ files.
Move the target from the ESP32 Makefile since that does what is needed
already, but also include files from user C modules as is done for the C
files.
2020-10-29 15:27:18 +11:00
stijn 2b9f0586e7 py/makeqstrdefs.py: Process C++ files as well.
Preprocessed C++ code isn't different from C code when it comes to QSTR
instances so process it as well.
2020-10-29 15:27:11 +11:00
stijn 1b723937e3 py/makeqstrdefs.py: Fix beaviour when scanning non-C preprocessed files.
When process_file() is passed a preprocessed C++ file for instance it won't
find any lines containing .c files and the last_fname variable remains
None, so handle that gracefully.
2020-10-29 15:26:35 +11:00
Damien George 6f34800884 extmod/modurandom: Support urandom.seed() without an argument.
If a port provides MICROPY_PY_URANDOM_SEED_INIT_FUNC as a source of
randomness then this will be used when urandom.seed() is called without
an argument (or with None as the argument) to seed the pRNG.

Other related changes in this commit:
- mod_urandom___init__ is changed to call seed() without arguments, instead
  of explicitly passing in the result of MICROPY_PY_URANDOM_SEED_INIT_FUNC.
- mod_urandom___init__ will only ever seed the pRNG once (before it could
  seed it again if imported by, eg, random and then urandom).
- The Yasmarang state is moved to the BSS for builds where the state is
  guaranteed to be initialised on import of the (u)random module.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 14:15:16 +11:00
Damien George 3e455e9792 stm32/rng: Use SysTick+RTC+unique-id to seed pRNG for MCUs without RNG.
The same seed will only occur if the board is the same, the RTC has the
same time (eg freshly powered up) and the first call to this function (eg
via an "import random") is done at exactly the same time since reset.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 14:14:40 +11:00
robert 59019d7f75 stm32/mpconfigport.h: Seed the urandom module on import.
For seeding the rng_get function is used, which is also the heart of
uos.urandom and pyb.rng, and is a hardware RNG where available.
2020-10-29 14:12:53 +11:00
robert 057193e855 esp8266/mpconfigport.h: Seed the urandom module on import.
For seeding, the hardware RNG of the esp8266 is used.
2020-10-29 14:12:44 +11:00
robert b4062894df esp32/mpconfigport.h: Seed the urandom module on import.
For seeding, the RNG function of the ESP-IDF is used, which is told to be a
true RNG, at least when WiFi or Bluetooth is enabled.  Seeding on import is
as per CPython.  To obtain a reproducible sequence of pseudo-random numbers
one must explicitly seed with a known value.
2020-10-29 14:11:08 +11:00
Damien George 03a1f94ea1 extmod/vfs_lfs: Support mounting LFS filesystems in read-only mode.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 11:43:52 +11:00
Damien George 0118c07916 stm32/machine_adc: Fix ADC auto-calibration to run when ADC not enabled.
Prior to this commit, the ADC calibration code was never executing because
ADVREGEN bit was set making the CR register always non-zero.

This commit changes the logic so that ADC calibration is always run when
the ADC is disabled and an ADC channel is initialised.  It also uses the LL
API functions to do the calibration, to make sure it is done correctly on
each MCU variant.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 11:09:43 +11:00
Damien George 368c1a0961 tests/thread/stress_schedule.py: Assign globals before running test.
When threading is enabled without the GIL then there can be races between
the threads accessing the globals dict.  Avoid this issue by making sure
all globals variables are allocated before starting the threads.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-28 00:54:30 +11:00
Emil Renner Berthing 05f95682e7 unix: Enable more warnings. 2020-10-22 11:54:11 +02:00
Emil Renner Berthing bef412789e mpy-cross: Enable more warnings. 2020-10-22 11:54:11 +02:00
Emil Renner Berthing ccd92335a1 py, extmod: Introduce and use MP_FALLTHROUGH macro.
Newer GCC versions are able to warn about switch cases that fall
through.  This is usually a sign of a forgotten break statement, but in
the few cases where a fall through is intended we annotate it with this
macro to avoid the warning.
2020-10-22 11:53:16 +02:00
Emil Renner Berthing dde3db21fc extmod: Disable -Wmissing-field-initializers for lfs2. 2020-10-22 11:47:36 +02:00
Emil Renner Berthing f1f6ef7b17 py/vmentrytable: Ignore GCC -Woverride-init.
Like Clang, GCC warns about this file, but only with -Woverride-init
which is enabled by -Wextra. Disable the warnings for this file just
like we do for Clang to make -Wextra happy.
2020-10-22 11:47:36 +02:00
Emil Renner Berthing 9aa58cf8ba py, extmod: Add explicit initializers for default values.
When compiling with -Wextra which includes -Wmissing-field-initializers
GCC will warn that the defval field of mp_arg_val_t is not initialized.
This is just a warning as it is defined to be zero initialized, but since
it is a union it makes sense to be explicit about which member we're
going to use, so add the explicit initializers and get rid of the
warning.
2020-10-22 11:47:36 +02:00
Emil Renner Berthing fdd6fa389e py: Use unsigned comparison of chars.
On x86 chars are signed, but we're comparing a char to '0' + unsigned int,
which is promoted to an unsigned int. Let's promote the char to unsigned
before doing the comparison to avoid weird corner cases.
2020-10-22 11:47:36 +02:00
Emil Renner Berthing 6d3aa16443 py/objexcept: Compare mp_emergency_exception_buf_size signed.
mp_emergency_exception_buf_size is signed, so let's make sure we compare
it as such.
2020-10-22 11:47:36 +02:00
Emil Renner Berthing 6324c3e054 py/scope: Name and use id_kind_type_t.
The function scope_find_or_add_id used to take a scope_kind_t enum and
save it in an uint8_t. Saving an enum in a uint8_t is fine, but
everywhere this function is called it is not actually given a
scope_kind_t but an anonymous enum instead. Let's give this enum a name
and use that as the argument type.

This doesn't change the generated code, but is a C type mismatch that
unfortunately doesn't show up unless you enable -Wenum-conversion.
2020-10-22 11:40:56 +02:00
Kevin Thomas 6eebdbc495 docs/reference/glossary.rst: Fix minor grammar error, An -> A. 2020-10-22 15:40:11 +11:00
Damien George 581d43b774 stm32/usbd_cdc_interface: Check and handle CDC TX wrap-overflow.
If the device is not connected over USB CDC to a host then all output to
the CDC (eg initial boot messages) is written to the CDC TX buffer with
wrapping, so that the most recent data is retained when the USB CDC is
eventually connected (eg so the REPL banner is displayed upon connection).

This commit fixes a bug in this behaviour, which was likely introduced in
e4fcd216e0, where the initial data in the CDC
TX buffer is repeated multiple times on first connection of the device to
the host.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-22 15:32:41 +11:00
iabdalkader a93d9b8c2d stm32: Fix broken build when FAT FS multi-partition is disabled. 2020-10-22 14:58:29 +11:00
Andrew Leech 97108fce57 esp32/mpconfigport.h: Enable MICROPY_PY_DELATTR_SETATTR.
To align with unix and stm32 ports.
2020-10-21 11:11:48 +11:00
Andrew Leech 32c99174e1 unix/mpconfigport.h: Enable MICROPY_PY_DELATTR_SETATTR.
This is a generally useful feature and because it's part of the object
model it cannot be added at runtime by some loadable Python code, so enable
it on the standard unix build.
2020-10-20 23:47:50 +11:00
Howard Lovatt 4842060366 docs/library/machine.Timer.rst: Add mention of constructor arguments. 2020-10-20 17:23:54 +11:00
Howard Lovatt cf6845b1cf docs/library/machine.Signal.rst: Correct typo: usecases to use cases. 2020-10-20 17:21:30 +11:00
Howard Lovatt 23f9439f44 docs/library/machine.rst: Correct minor typo: timout to timeout. 2020-10-20 17:19:47 +11:00
Howard Lovatt 3bc0ecbcd9 docs/library/btree.rst: Correct method typo: __detitem__ to __delitem__. 2020-10-20 17:13:02 +11:00
awachtler 56e0932485 tools/upip.py: Support explicit port number in host.
Adding a port number other then 443 to a PyPI URL may be needed if a local
server like devpi is used.
2020-10-20 12:44:30 +11:00
Damien George 18518e26a7 ports: Use correct in/out endpoint size in TUD_CDC_DESCRIPTOR.
The last argument of TUD_CDC_DESCRIPTOR() is the endpoint size (or
wMaxPacketSize), not the CDC RX buffer size (which can be larger than the
endpoint size).

Signed-off-by: Damien George <damien@micropython.org>
2020-10-17 15:49:16 +11:00
Jim Mussared 893f75546c stm32/boards/NUCLEO_WB55/rfcore_firmware.py: Increase GET_STATE timeout.
When installing WS firmware, the very first GET_STATE can take several
seconds to respond (especially with the larger binaries like
BLE_stack_full).

Allows stm.rfcore_sys_hci to take an optional timeout, defaulting to
SYS_ACK_TIMEOUT_MS (which is 250ms).

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-10-16 10:45:03 +11:00
Jim Mussared dfb63b5613 stm32/boards/NUCLEO_WB55/rfcore_firmware.py: Fix bad variable name.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-10-16 10:44:58 +11:00
Jim Mussared 520bb88d70 stm32/boards/NUCLEO_WB55/rfcore_firmware.py: Fix flash unlock.
The flash can sometimes be in an already-unlocked state, and attempting to
unlock it again will cause an immediate reset.  So make _Flash.unlock()
check FLASH_CR_LOCK to get the current state.

Also fix some magic numbers for FLASH_CR_LOCK AND FLASH_CR_STRT.

The machine.reset() could be removed because it no longer crashes now that
the flash unlock is fixed.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-10-16 10:43:36 +11:00
Jim Mussared b137d064e9 py/objtype: Handle __dict__ attribute when type has no locals. 2020-10-10 00:16:32 +11:00
Jim Mussared 880875bea1 py/objdict: Add mp_const_empty_dict_obj, use it for mp_const_empty_map. 2020-10-10 00:16:26 +11:00
Jim Mussared fa12bfc227 stm32/rfcore: Update to support WS=1.9.0.0.4.
This WS update to 1.9.0.0.4 broke the workaround used in rfcore for
OCF_CB_SET_EVENT_MASK2, so fix it to support WS 1.8 and 1.9.
2020-10-09 23:52:35 +11:00
Jim Mussared 222ec1a4a8 stm32/boards/NUCLEO_WB55: Add standalone WB55 FUS/WS firmware updater.
This commit adds a script that can be run on-device to install FUS and WS
binaries from the filesystem.  Instructions for use are provided in
the rfcore_firmware.py file.

The commit also removes unneeded functionality from the existing rfcore.py
debug script (and renames it rfcore_debug.py).
2020-10-08 17:39:15 +11:00
Jim Mussared 7c76a2dfcf stm32/rfcore: Add Python API for basic rfcore operations.
The new functions provide FUS/WS status, version and SYS HCI commands:
- stm.rfcore_status()
- stm.rfcore_fw_version(fw_id)
- stm.rfcore_sys_hci(ogf, ocf, cmd)
2020-10-08 17:37:11 +11:00
iabdalkader 9855b9cd82 stm32/sdcard: Fix H7 build when using SDMMC2.
Changes are:
- Fix missing IRQ handler when SDMMC2 is used instead of SDMMC1 with H7
  MCUs.
- Removed outdated H7 series compatibility macros.
- Defined common IRQ handler macro for F4 series.
2020-10-06 23:33:38 +11:00
iabdalkader 7497d891a7 stm32/sdio: Don't change any DMA2 settings on H7 MCUs.
DMA2 clock and registers should be left in their current state in the H7
build.
2020-10-06 23:31:08 +11:00
Damien George 1dc64359da esp32: Use path relative to root for netutils/timeutils headers.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-06 12:32:20 +11:00
Damien George 0fff2e03fe stm32/Makefile: Allow boards to extend SRC_C, SRC_O and OBJ variables.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-02 15:46:13 +10:00
Damien George 817b80a102 unix/variants: Enable MICROPY_DEBUG_PARSE_RULE_NAME on coverage build.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 15:26:43 +10:00
Damien George 843dcd4f85 py/parse: Expose rule-name printing as MICROPY_DEBUG_PARSE_RULE_NAME.
So it can be enabled without modifying the source.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 15:26:43 +10:00
Damien George d4b61b0017 extmod/utime_mphal: Add generic utime.time_ns() function.
It requires mp_hal_time_ns() to be provided by a port.  This function
allows very accurate absolute timestamps.

Enabled on unix, windows, stm32, esp8266 and esp32.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 14:20:42 +10:00
Damien George 905a18aafe unix,windows: Implement mp_hal_time_ns using gettimeofday.
This provides microsecond accuracy.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 14:20:42 +10:00
Damien George 98182a97c5 docs: Update I2C and SPI docs to add reference to SoftI2C and SoftSPI.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 12:57:10 +10:00
Damien George 71f3ade770 ports: Support legacy soft I2C/SPI construction via id=-1 arg.
With a warning that this way of constructing software I2C/SPI is
deprecated.  The check and warning will be removed in a future release.

This should help existing code to migrate to the new SoftI2C/SoftSPI types.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 12:57:10 +10:00
Damien George 39d50d129c ports: Add SoftI2C and SoftSPI to machine module where appropriate.
Previous commits removed the ability for one I2C/SPI constructor to
construct both software- or hardware-based peripheral instances.  Such
construction is now split to explicit soft and non-soft types.

This commit makes both types available in all ports that previously could
create both software and hardware peripherals: machine.I2C and machine.SPI
construct hardware instances, while machine.SoftI2C and machine.SoftSPI
create software instances.

This is a breaking change for use of software-based I2C and SPI.  Code that
constructed I2C/SPI peripherals in the following way will need to be
changed:

    machine.I2C(-1, ...)            ->  machine.SoftI2C(...)
    machine.I2C(scl=scl, sda=sda)   ->  machine.SoftI2C(scl=scl, sda=sda)

    machine.SPI(-1, ...)            ->  machine.SoftSPI(...)
    machine.SPI(sck=sck, mosi=mosi, miso=miso)
                        ->  machine.SoftSPI(sck=sck, mosi=mosi, miso=miso)

Code which uses machine.I2C and machine.SPI classes to access hardware
peripherals does not need to change.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 12:57:10 +10:00
Damien George 9e0533b9e1 extmod/machine_spi: Remove "id" arg in SoftSPI constructor.
The SoftSPI constructor is now used soley to create SoftSPI instances, it
can no longer delegate to create a hardware-based SPI instance.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 12:57:10 +10:00
Damien George aaed33896b extmod/machine_i2c: Remove "id" arg in SoftI2C constructor.
The SoftI2C constructor is now used soley to create SoftI2C instances, it
can no longer delegate to create a hardware-based I2C instance.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 12:57:10 +10:00
Damien George c35deb2625 extmod/machine_i2c: Rename type to SoftI2C and add custom print method.
Also rename machine_i2c_type to mp_machine_soft_i2c_type.  These changes
make it clear that it's a soft-I2C implementation, and match SoftSPI.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 12:57:10 +10:00
Mike Wadsten c711c0049e py/makeversionhdr.py: Match only git tags which look like versions.
Some downstream projects may use tags in their repositories for more than
just designating MicroPython releases.  In those cases, the
makeversionhdr.py script would end up using a different tag than intended.
So tell `git describe` to only match tags that look like a MicroPython
version tag, such as `v1.12` or `v2.0`.
2020-10-01 11:01:43 +10:00
David Lechner ee7568ca8d docs/reference/packages.rst: Fix typo, remove duplicate "port".
Fixes #6485.
2020-09-30 23:32:24 +10:00
Maureen Helm 997ec9e8cc zephyr: Update build instructions to v2.4.0.
Updates the zephyr port build instructions to use the latest zephyr
release tag.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-09-30 23:21:53 +10:00
Maureen Helm c2a7aac906 travis: Update zephyr build to v2.4.0.
Updates CI to use the latest zephyr release tag.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-09-30 23:21:53 +10:00
Maureen Helm f842e32155 zephyr: Const-ify struct device instance pointers.
Zephyr v2.4.0 added a const qualifier to usages of struct device to
allow storing device driver instances exclusively in flash and thereby
reduce ram footprint.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-09-30 23:21:53 +10:00
Maureen Helm ce49be43b1 zephyr: Replace zephyr integer types with C99 types.
Zephyr v2.4.0 stopped using custom integer types in favor of C99 types
instead.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-09-30 23:21:53 +10:00
Andrew Leech 319437d4bd extmod/modure: Allow \\ in re.sub replacements. 2020-09-30 23:18:34 +10:00
Jim Mussared 0fd0eb00aa examples/bluetooth: Update to use positional-only args to irq().
To match 6a6a5f9e15.
2020-09-26 21:19:18 +10:00
Damien George 9123b67d64 tests/run-tests: Use -BS flags when running CPython.
The use of -S ensures that only the CPython standard library is accessible,
which makes tests run the same regardless of any site-packages that are
installed.  It also improves start-up time of CPython, reducing the overall
time spent running the test suite.

tests/basics/containment.py is updated to work around issue with old Python
versions not being able to str-format a dict-keys object, which becomes
apparent when -S is used.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-25 12:27:23 +10:00
Damien George c8ade2bd7f docs/develop: Add notes on prerequisite tools for building native .mpy.
Signed-off-by: Damien George <damien@micropython.org>
2020-09-25 12:25:29 +10:00
Damien George 81f2162ca0 extmod/modbluetooth: Change module-owned bytes objects to memoryview.
A read-only memoryview object is a better representation of the data, which
is owned by the ubluetooth module and may change between calls to the
user's irq callback function.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-25 12:23:11 +10:00
Damien George 50e34f979c py/objarray.h: Add mp_obj_memoryview_init() helper function.
Signed-off-by: Damien George <damien@micropython.org>
2020-09-25 12:23:11 +10:00
Iyassou Shimels ca017841d6 py/objstr: Make bytes(bytes_obj) return bytes_obj.
Calling the bytes constructor on a bytes object returns the original bytes
object.  This saves allocating a new instance, and matches CPython.

Signed-off-by: Iyassou Shimels <s.iyassou@gmail.com>
2020-09-24 11:04:58 +10:00
stijn bada8c9231 windows: Update build instructions in README.
Make the instructions more complete by documenting all needed steps for
starting from scratch.  Also add a section for MSYS2 since the Travis build
uses it as well and it's a good alternative for Cygwin.  Remove the mingw32
reference since it's not readily available anymore in most Linux distros
nor compiles successfully.
2020-09-23 22:22:13 +10:00
Damien George 71adf506ce extmod/vfs: Fix lookup of entry in root dir so it fails correctly.
Prior to this commit, uos.chdir('/') followed by uos.stat('noexist') would
succeed that stat even though the entry did not exist (some other functions
like listdir would have similar issues).  This is because, if the current
directory was the root and the path was relative, mp_vfs_lookup_path would
return success for bad paths.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-23 16:23:35 +10:00
Damien George 3e16763201 stm32/rfcore: Fix FUS layout and size of ipcc_device_info_table_t.
The device info table has a different layout when core 2 is in FUS mode.
In particular it's larger than the 32 bytes used when in WS mode and if the
correct amount of space is not allocated then the end of the table may be
overwritten with other data (eg with FUS version 0.5.3).  So update the
structure to fix this.

Also update rfcore.py to disable IRQs (which are enabled by rfcore.c), to
not depend on uctypes, and to not require the asm_thumb emitter.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-22 14:08:22 +10:00
Damien George 42342fa3cb tests/basics: Add test for MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS ops.
And enable this feature on unix, the coverage variant.  The .exp test file
is needed so the test can run on CPython versions prior to "@=" operator
support.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 18:40:42 +10:00
Damien George c410a86814 tests/basics: Enable == and != special-method tests now that they work.
These work since 3aab54bf43

Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 18:40:42 +10:00
Tweako 8af9796b16 stm32/led: Support PWM output without TIM3.
For example, the STM32WB55 doesn't have TIM3 but can still drive LEDs using
PWM on other timers.
2020-09-18 18:37:11 +10:00
Jim Mussared 9d1983f078 py/dynruntime.h: Add mp_import_* and mp_load/store_*.
These functions already exist in the fun table, and this commit just adds
convenience macros for them.
2020-09-18 18:34:02 +10:00
Damien George 8f20cdc353 all: Rename absolute time-based functions to include "epoch".
For time-based functions that work with absolute time there is the need for
an Epoch, to set the zero-point at which the absolute time starts counting.
Such functions include time.time() and filesystem stat return values.  And
different ports may use a different Epoch.

To make it clearer what functions use the Epoch (whatever it may be), and
make the ports more consistent with their use of the Epoch, this commit
renames all Epoch related functions to include the word "epoch" in their
name (and remove references to "2000").

Along with this rename, the following things have changed:

- mp_hal_time_ns() is now specified to return the number of nanoseconds
  since the Epoch, rather than since 1970 (but since this is an internal
  function it doesn't change anything for the user).

- littlefs timestamps on the esp8266 have been fixed (they were previously
  off by 30 years in nanoseconds).

Otherwise, there is no functional change made by this commit.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 17:20:34 +10:00
Damien George bd7af6151d ports: Add utime.gmtime() function.
To portably get the Epoch.  This is simply aliased to localtime() on ports
that are not timezone aware.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 16:25:36 +10:00
Damien George b28758054b esp8266: Remove release-specific manifest, disable osdebug by default.
This commit removes release-specific builds for the esp8266 and makes the
normal build of the GENERIC board more like the release build.  This makes
esp8266 like all the other ports, for which there is no difference between
a daily build and a release build, making things less confusing.

Release builds were previously defined by UART_OS=-1 (disable OS messages)
and using manifest_release.py to include more frozen modules.

The changes in this commit are:
- Remove manifest_release.py.
- Add existing modules from manifest_release.py (except example code)
  to the GENERIC board's manifest.py file.
- Change UART_OS default to -1 to disable OS messages by default.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 16:01:42 +10:00
Mirko Vogt ecb36d2439 esp32/modnetwork: Re-enable PPP support for IDF-SDK >=v4.
PPP support was disabled in 96008ff59a -
marked as "unsupported" due to an early IDF v4 release.  With the currently
supported IDF v4.x version - 4c81978a - it appears to be working just fine.
2020-09-18 15:57:21 +10:00
Jim Mussared 52d6eeb409 esp32/boards/sdkconfig.base: Set default IDF log level to ERROR.
This commit changes the default logging level on all esp32 boards to ERROR.
The esp32 port is now stable enough that it makes sense to remove the info
logs to make the output cleaner, and to match other ports.  More verbose
logging can always be reenabled via esp.osdebug().

This also fixes issue #6354, error messages from NimBLE: the problem is
that ble.active(True) will cause the IDF's NimBLE port to reset the
"NimBLE" tag back to the default level (which was INFO prior to this
commit).  Even if the user had previously called esp.osdebug(None), because
the IDF is setting the "NimBLE" tag back to the default (INFO), the
messages will continue to be shown.

The one quirk is that if the user does want to see the additional logging,
then they must call esp.osdebug(0, 3) after ble.active(True) to undo the
IDF setting the level back to the default (now ERROR).  This means that
it's impossible (via Python/esp.osdebug) to see stack-startup logging,
you'd have to recompile with the default level changed back to INFO.
2020-09-18 15:53:56 +10:00
Damien George 5c503de521 travis: Install setuptools for black code formatting.
Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 15:13:31 +10:00
Jim Mussared 3086d35e16 tests/multi_bluetooth/ble_mtu.py: Add multitest for BLE MTU. 2020-09-18 12:51:21 +10:00
Jim Mussared 06dda48144 tests/run-multitests.py: Show test/truth diff. 2020-09-18 12:51:21 +10:00
Jim Mussared 857e2c8fd5 extmod/modbluetooth: Implement MTU. 2020-09-18 12:51:21 +10:00
Jim Mussared f271b96b5c docs/library/ubluetooth.rst: Add docs for MTU API. 2020-09-18 12:51:21 +10:00
Jim Mussared fe642ced43 tests/multi_bluetooth: Update UUID format in .exp files. 2020-09-18 12:51:21 +10:00
Jim Mussared c200759290 docs/library/ubluetooth.rst: Clarify peripheral/central vs server/client
Previously this documentation assumed peripheral=server and central=client,
but this is not accurate or true to the implementation.
2020-09-15 15:42:59 +10:00
Jim Mussared 5be3bfcb7e extmod/modbluetooth: Print UUIDs correctly.
In particular, the printed string can now be re-evaluated to construct the
same UUID object.
2020-09-15 15:29:13 +10:00
Jim Mussared 19faf55090 docs/library/ubluetooth.rst: Clarify position/kw arguments.
Almost all ubluetooth functions are positional-only, but some have optional
args.  Make this clearer and show what the defaults are.
2020-09-15 15:28:59 +10:00
Jim Mussared 6a6a5f9e15 extmod/modbluetooth: Make BLE.irq() method positional only.
Simplifcation now that the trigger arg has been removed.
2020-09-15 15:28:45 +10:00
Jim Mussared 504522bd02 extmod/modbluetooth: Fix handling of optional data/uuid args.
For the following 3 functions, previously the code relied on whether the
arg was passed at all, to make it optional.  Now it allows them to be
explicitly `None` to indicate they are not used:

- gatts_notify(..., [data])
- gattc_discover_services(..., [uuid])
- gattc_discover_characteristics(..., [uuid])

Also ensure that the uuid arguments are actually instances of the uuid
type, and fix handling of the 5th arg in gattc_discover_characteristics().
2020-09-15 15:23:51 +10:00
Damien George b31cb21a39 stm32/servo: Fix angle and speed methods to work again with -ve args.
Fixes a regression introduced by 70affd9ba2

Fixes issue #6403

Signed-off-by: Damien George <damien@micropython.org>
2020-09-12 13:47:59 +10:00
Damien George acdb0608b7 py/parse: Pass in an mp_print_t to mp_parse_node_print.
So the output can be redirected if needed.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-11 23:00:03 +10:00
Damien George 85f2b239d8 py/showbc: Pass in an mp_print_t struct to all bytecode-print functions.
So the output can be redirected if needed.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-11 17:22:28 +10:00
Jim Mussared 50efce8174 esp32/mpconfigport.h: Remove duplicate uhashlib registration. 2020-09-11 11:03:29 +10:00
stijn 70bec41089 windows: Show test failures in the Appveyor builds. 2020-09-11 10:56:02 +10:00
stijn 5b94c61097 windows/Makefile: Support freezing modules.
Alter the build flags as needed to support freezing modules with a
manifest.  This makes freezing works just like it does for e.g. the unix
port.
2020-09-11 10:52:52 +10:00
stijn 2a9ea69fa9 windows/msvc: Support freezing modules.
Support freezing modules via manifest.py for consistency with the other
ports.  In essence this comes down to calling makemanifest.py and adding
the resulting .c file to the build.  Note the file with preprocessed qstrs
has been renamed to match what makemanifest.py expects and which is also
the name all other ports use.
2020-09-11 10:52:35 +10:00
stijn 4b35aa5730 tools: Write msvc-compatible frozen content.
The msvc compiler doesn't accept zero-sized arrays so let the freezing
process generate compatible C code in case no modules are found and the
involved arrays are all empty.  This doesn't affect the functionality in
any way because those arrays only get accessed when mp_frozen_mpy_names
contains names, i.e.  when modules are actually found.
2020-09-11 10:51:55 +10:00
Damien George 373b400632 extmod/modussl_axtls: Reduce size of code that makes exception.
Change in code size (for ports that use axtls) is:

   unix x64:  -152 -0.030% [incl -160(data)]
unix nanbox:  -112 -0.025% [incl -96(data)]
    esp8266:   -64 -0.009% GENERIC

Signed-off-by: Damien George <damien@micropython.org>
2020-09-11 10:22:19 +10:00
stijn 2e54d9d146 py: Fix handling of NaN in certain pow implementations.
Adds a new compile-time option MICROPY_PY_MATH_POW_FIX_NAN for use with
toolchains that don't handle pow-of-NaN correctly.
2020-09-11 10:04:57 +10:00
Damien George 8d5a40c86e py/objfloat: Fix handling of negative float to power of nan.
Prior to this commit, pow(-2, float('nan')) would return (nan+nanj), or
raise an exception on targets that don't support complex numbers.  This is
fixed to return simply nan, as CPython does.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-11 10:03:57 +10:00
Damien George 709398daae stm32/rtc.h: Include py/obj.h to make header self contained.
Signed-off-by: Damien George <damien@micropython.org>
2020-09-10 20:46:40 +10:00
Damien George 547688c58c stm32/usb: Don't nul pyb_hid_report_desc if MICROPY_HW_USB_HID disabled.
So this code can be used if pyb_hid_report_desc is not included in the
port's root pointer list.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-10 20:46:35 +10:00
Damien George 27e117307d nrf: Remove unnecessary includes of mpconfigport.h and its header guard.
The mpconfigport.h file is an internal header and should only ever be
included once by mpconfig.h.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-09 00:13:34 +10:00
Damien George 75344af4ca nrf/main: Make mp_builtin_open signature match that in py/builtin.h.
Signed-off-by: Damien George <damien@micropython.org>
2020-09-09 00:13:34 +10:00
Damien George 4f2fe34623 tools/mpy-tool.py: Fix merge of multiple mpy files to POP_TOP correctly.
MP_BC_CALL_FUNCTION will leave the result on the Python stack, so that
result must be discarded by MP_BC_POP_TOP.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-09 00:11:51 +10:00
Albort Xue 5f50568b1f mimxrt/boards: Add MIMXRT1064_EVK board. 2020-09-09 00:06:33 +10:00
Jim Mussared 632e3b7acc stm32/boards/NUCLEO_WB55: Add Python helper code for rfcore.
This allows prototyping rfcore.c improvements from Python.

This was mostly written by @dpgeorge with small modifications to work after
rfcore_init() by @jimmo.
2020-09-08 23:54:02 +10:00
Jim Mussared e2390d5a2f stm32/rfcore: Enable RX IRQ on BLE IPCC channel for better performance.
Before this change there was up to a 128ms delay on incoming payloads from
CPU2 as it was polled by SysTick.  Now the RX IRQ immediately schedules the
PendSV.
2020-09-08 23:53:12 +10:00
Jim Mussared 8b4ebd7166 stm32/rfcore: Refactor some helper funcs, and remove some magic numbers.
Also explain what the payload fixup code is doing.
2020-09-08 23:53:12 +10:00
Jim Mussared 01f2d77614 stm32/rfcore: Fix length matching in HCI parser. 2020-09-08 23:53:12 +10:00
Jim Mussared 5eda362e0a tests/multi_bluetooth: Make ble_gap_connect robust against event timing. 2020-09-08 23:53:12 +10:00
Jim Mussared 0f28020a68 stm32/powerctrlboot: Acquire HSEM5 on STM32WB during SystemClock_Config.
This is required to allow using WS firmware newer than 1.1.1 concurrently
with USB (e.g. USB VCP).  It prevents CPU2 from modifying the CLK48 config
on boot.

Tested on WS=1.8 FUS=1.1.

See AN5289 and https://github.com/micropython/micropython/issues/6316
2020-09-08 23:53:12 +10:00
Jim Mussared 9c9cc7a02f stm32/boards/USBDONGLE_WB55: Add USE_MBOOT support. 2020-09-08 23:53:12 +10:00
Jim Mussared 30e8162ac4 stm32/rfcore: Update rfcore.c to match how ST examples work.
- Split tables and buffers into SRAM2A/2B.
- Use structs rather than word offsets to access tables.
- Use FLASH_IPCCDBA register value rather than option bytes directly.
2020-09-08 23:53:02 +10:00
Jim Mussared b27edb8073 stm32/make-stmconst.py: Add support for WB55 header files. 2020-09-08 23:23:23 +10:00
Jim Mussared 126f972c34 extmod/nimble: Add timeout for HCI sync on startup.
This allows `ble.active(1)` to fail correctly if the HCI controller is
unavailable.

It also avoids an infine loop in the NimBLE event handler where NimBLE
doesn't correctly detect that the HCI controller is unavailable and keeps
trying to reset.

Furthermore, it fixes an issue where GATT service registrations were left
allocated, which led to a bad realloc if the stack was activated multiple
times.
2020-09-08 12:53:24 +10:00
Jim Mussared 311b8519af esp32: Pin MicroPython and NimBLE tasks to core 0.
MicroPython and NimBLE must be on the same core, for synchronisation of the
BLE ringbuf and the MicroPython scheduler.  However, in the current IDF
versions (3.3 and 4.0) there are issues (see e.g. #5489) with running
NimBLE on core 1.

This change - pinning both tasks to core 0 - makes it possible to reliably
run the BLE multitests on esp32 boards.
2020-09-08 12:53:24 +10:00
Jim Mussared 99a29ec705 extmod/btstack: Detect HCI UART init failure. 2020-09-08 12:53:24 +10:00
Andrew Leech 6077c63a45 stm32/mpbthciport: Increase char timeout of BT HCI UART.
The 2ms used previously was not long enough and it could lose HCI sync.

Also print error on tx failure to make this more obvious in the future.
2020-09-08 12:53:24 +10:00
Andrew Leech 8b00aeab8f extmod/btstack: Add btstack support for _IRQ_GATTS_READ_REQUEST. 2020-09-08 12:53:24 +10:00
Jim Mussared 52a2ce45de extmod/modbluetooth: Allow using mp_hal_get_mac as a static address.
Generally a controller should either have its own public address hardcoded,
or loaded by the driver (e.g. cywbt43).

However, for a controller that has no public address where you still want a
long-term stable address, this allows you to use a static address generated
by the port.  Typically on STM32 this will be an LAA, but a board might
override this.
2020-09-08 12:53:24 +10:00
Jim Mussared 67d8139e2b docs/library/ubluetooth.rst: Document BLE address modes. 2020-09-08 12:53:24 +10:00
Jim Mussared 26b66804e9 tests/multi_bluetooth: Update to new config('mac') behaviour. 2020-09-08 12:53:24 +10:00
Jim Mussared c4af714d58 extmod/modbluetooth: Implement configuration of address modes.
Changes `BLE.config('mac')` to return a tuple (addr_mode, addr).

Adds `BLE.config(addr_mode=...)` to set the addressing mode.
2020-09-08 12:53:24 +10:00
Jim Mussared 1b1b22905e unix: Implement BLE H4 HCI UART for btstack/nimble.
This commit adds support for using Bluetooth on the unix port via a H4
serial interface (distinct from a USB dongle), with both BTstack and NimBLE
Bluetooth stacks.

Note that MICROPY_PY_BLUETOOTH is now disabled for the coverage variant.
Prior to this commit Bluetooth was anyway not being built on Travis because
libusb was not detected.  But now that bluetooth works in H4 mode it will
be built, and will lead to a large decrease in coverage because Bluetooth
tests cannot be run on Travis.
2020-09-08 12:53:24 +10:00
Jim Mussared feed69aa5c unix/Makefile: Always enable -f*-sections regardless of DEBUG setting. 2020-09-08 12:53:16 +10:00
Jim Mussared aa18ab7db2 extmod/nimble: Implement NimBLE mutex. 2020-09-08 11:41:31 +10:00
Jim Mussared f3f31ac959 extmod/nimble: Make nimble_malloc work with allocated size. 2020-09-08 11:41:31 +10:00
Jim Mussared 5b08676d6a extmod/nimble: Set struct alignment correctly on 64-bit arch. 2020-09-08 11:41:31 +10:00
Jim Mussared ed14435a8e extmod/modbluetooth: Refactor stack/hci/driver/port bindings.
Previously the interaction between the different layers of the Bluetooth
stack was different on each port and each stack.  This commit defines
common interfaces between them and implements them for cyw43, btstack,
nimble, stm32, unix.
2020-09-08 11:41:31 +10:00
Jim Mussared e46aac24ba extmod/modbluetooth: Rename logging macro to be just DEBUG_printf.
And prefix the debug message with "btstack:" or "nimble:", depending on the
context.  Also use correct format specifier for %zu.
2020-09-08 10:48:23 +10:00
Jim Mussared 5ff265a3db stm32/modbluetooth_hci: Use a static mp_irq_obj_t for BT HCI UART IRQ.
So that the IRQ handler does not need to be traced by the GC.
2020-09-08 10:47:27 +10:00
Jim Mussared 23109988c2 stm32/uart: Allow static IRQ handler registration.
This will allow the HCI UART to use a non-heap mp_irq_obj_t, which avoids
needing to make a root pointer for it.
2020-09-08 10:46:30 +10:00
Damien George 3ff7079277 lib/utils/mpirq: Add mp_irq_init func, and clean up unused init method.
mp_irq_init() is useful when the IRQ object is allocated by the caller.

The mp_irq_methods_t.init method is not used anywhere so has been removed.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-04 12:40:38 +10:00
Damien George 5e69926ea0 stm32/mpconfigport.h: Enable MICROPY_PY_REVERSE_SPECIAL_METHODS.
It's a useful core feature.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-04 10:45:39 +10:00
Damien George 38959ed8f1 lib/libm: Reduce size of static two_over_pi array.
Thanks to Jeff Epler for the idea.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-04 00:45:56 +10:00
stijn 40ad8f1666 all: Rename "sys" module to "usys".
This is consistent with the other 'micro' modules and allows implementing
additional features in Python via e.g. micropython-lib's sys.

Note this is a breaking change (not backwards compatible) for ports which
do not enable weak links, as "import sys" must now be replaced with
"import usys".
2020-09-04 00:10:24 +10:00
Damien George b0932fcf2e all: Bump version to 1.13.
Signed-off-by: Damien George <damien@micropython.org>
2020-09-02 12:01:26 +10:00
Damien George 0e6ef40359 tests/extmod: Add tests for verifying FAT and littlefs mtime values.
Verifies mtime timestamps on files match the value returned by time.time().

Also update vfs_fat_ramdisk.py so it doesn't check FAT timestamp of the
root, because that may change across runs/ports.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-02 00:19:38 +10:00
Damien George a909c21587 unix/fatfs_port: Fix month offset in timestamp calculation.
Signed-off-by: Damien George <damien@micropython.org>
2020-09-02 00:19:06 +10:00
Damien George 2a72e90ab8 extmod/vfs: Add option to use 1970 as Epoch.
By setting MICROPY_EPOCH_IS_1970 a port can opt to use 1970/1/1 as the
Epoch for timestamps returned by stat().  And this setting is enabled on
the unix and windows ports because that's what they use.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-01 12:36:28 +10:00
Damien George 0385b21597 unix/modos: Support larger integer range in uos.stat fields.
On 32-bit builds these stat fields will overflow a small-int, so use
mp_obj_new_int_from_uint to construct the int object.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-01 12:36:28 +10:00
Damien George c70e599659 extmod/vfs: Support larger integer range in VFS stat time fields.
On ports like unix where the Epoch is 1970/1/1 and atime/mtime/ctime are in
seconds since the Epoch, this value will overflow a small-int on 32-bit
systems.  So far this is only an issue on 32-bit unix builds that use the
VFS layer (eg dev and coverage unix variants) but the fix (using
mp_obj_new_int_from_uint instead of MP_OBJ_NEW_SMALL_INT) is there for all
ports so as to not complicate the code, and because they will need the
range one day.

Also apply a similar fix to other fields in VfsPosix.stat because they may
also be large.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-01 12:36:28 +10:00
Damien George 40153b800a esp32/mphalport: Fix mp_hal_time_ns offset.
gettimeofday returns seconds since 2000/1/1 so needs to be adjusted to
seconds since 1970/1/1 to give the correct return value of mp_hal_time_ns.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-31 00:49:58 +10:00
Damien George 836bca9956 unix/variants: Fix fast and freedos variants so they build again.
This regressed in bd2fff6687

Signed-off-by: Damien George <damien@micropython.org>
2020-08-30 13:48:26 +10:00
Damien George d1995e50eb extmod/modlwip: Fix error return for TCP recv when not connected.
This commit fixes the cases when a TCP socket is in STATE_NEW,
STATE_LISTENING or STATE_CONNECTING and recv() is called on it.  It now
raises ENOTCONN instead of a random error code due to it previously
indexing beyond the start of error_lookup_table[].

Signed-off-by: Damien George <damien@micropython.org>
2020-08-30 13:20:51 +10:00
Damien George 06659077a8 all: Update Python code to conform to latest black formatting.
Updating to Black v20.8b1 there are two changes that affect the code in
this repository:

- If there is a trailing comma in a list (eg [], () or function call) then
  that list is now written out with one line per element.  So remove such
  trailing commas where the list should stay on one line.

- Spaces at the start of """ doc strings are removed.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-29 15:18:01 +10:00
Damien George 0c7354afaf tests: Split out complex reverse-op tests to separate test file.
So they can be skipped if __rOP__'s are not supported on the target.  Also
fix the typo in the complex_special_methods.py filename.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-29 14:12:20 +10:00
Damien George 40d174ac7d stm32/powerctrl.h: Include stdbool.h to get definition of bool.
Signed-off-by: Damien George <damien@micropython.org>
2020-08-29 14:00:24 +10:00
Damien George 338b12d3c8 LICENSE,docs: Update copyright year range to include 2020.
Signed-off-by: Damien George <damien@micropython.org>
2020-08-29 13:58:20 +10:00
Damien George a93a378e93 zephyr/README: Update required Zephyr version and mention new features.
Signed-off-by: Damien George <damien@micropython.org>
2020-08-28 16:42:32 +10:00
Michael Buesch cef678b2db extmod/machine_i2c: Fix buffer overrun if 'addrsize' is bigger than 32.
The memory operation functions read_mem() and write_mem() create a
temporary buffer on the local C stack for the address bytes with the size
of 4 bytes.  This buffer is filled in a loop from the user supplied address
and address length.  If the user supplied 'addrsize' is bigger than 32, the
local buffer is overrun.

Fix this by raising an exception for invalid 'addrsize' values.

Signed-off-by: Michael Buesch <m@bues.ch>
2020-08-27 12:39:11 +10:00
stijn 0c3f9d58a5 tests/run-tests: Make test output directory configurable.
A configurable result directory is advantageous because it enables
using a dedicated location, eventually outside of the source tree,
instead of forcing the output files into a fixed directory which might
also contain other files already. For that reason the default output
directory also has been changed to tests/results/.
2020-08-27 11:12:08 +10:00
stijn 405893afc6 tests/run-tests: Use absolute paths where possible.
Replace some usages of paths relative to the current working directory
with absolute paths relative to the tests directory.

Fixes and resulting changes:
- default values of MICROPYTHON and MPYCROSS are absolute paths and
  always correct
- likewise, the correct full paths for tools and extmod directories
  are appended to sys.path
- printing/cleaning failures works properly since it expects the .exp
  and .out files in the tests directory which is also where they
  are written to now, plus no more need for changing directories

This fixes #5872 and allows running custom tests which use run-tests
without having to cd to the tests directory first, and the test output
still is in the tests/ directory instead of the current working directory.

Discovery of tests and all skip test logic based on paths relative to
the current working directory remains unchanged which essentially means
that for running most of MicroPython's own tests, run-tests must still
be ran from within it's directory, so document that.
2020-08-27 11:12:08 +10:00
Roberto Colistete Jr 91c5d168c0 nrf/Makefile: Improve user C modules support.
Add CFLAGS_EXTRA to CFLAGS. Include LDFLAGS_MOD to the compilation.
And, add SRC_MOD to SRC_QSTR.
2020-08-26 22:14:40 +02:00
Damien George 5fb276de33 tests/extmod: Make uasyncio_fair test more reliable by adjusting sleeps.
With sleep(0.2) a multiple of sleep(0.1), the order of task 2 and 3
execution is not well defined, and depends on the precision of the system
clock and how fast the rest of the code runs.  So change 0.2 to 0.18 to
make the test more reliable.

Also fix a typo of t3/t4, and cancel t4 at the end.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-26 17:05:52 +10:00
Andrew Leech a80a146858 extmod/bluetooth: Support active scanning in BLE.gap_scan().
This adds an additional optional parameter to gap_scan() to select active
scanning, where scan responses are returned as well as normal scan results.
This parameter is False by default which retains the existing behaviour.
2020-08-26 15:00:11 +10:00
Jim Mussared 0bc2c1c105 extmod/modbluetooth: Fix race between READ_REQUEST and other IRQs.
The READ_REQUEST callback is handled as a hard interrupt (because the BLE
stack needs an immediate response from it so it can continue) and so calls
to Python require extra protection:

- the caller-owned tuple passed into the callback must be separate from the
  tuple used by other callback events (which are soft interrupts);

- the GC and scheduler must be locked during callback execution.
2020-08-26 14:57:36 +10:00
Jim Mussared 3d9a7ed02f extmod/btstack: Implement GAP scan duration_ms parameter.
This commit makes scanning work when duration_ms is set to zero.  Prior to
this it would not work with duration_ms set to zero.
2020-08-26 14:55:52 +10:00
Damien George 2acc087880 extmod/vfs_lfs: Add mtime support to littlefs files.
This commit adds support for modification time of files on littlefs v2
filesystems, using file attributes.  For some background see issue #6114.

Features/properties of this implementation:
- Only supported on littlefs2 (not littlefs1).
- Uses littlefs2's general file attributes to store the timestamp.
- The timestamp is 64-bits and stores nanoseconds since 1970/1/1 (if the
  range to the year 2554 is not enough then additional bits can be added to
  this timestamp by adding another file attribute).
- mtime is enabled by default but can be disabled in the constructor, eg:
  uos.mount(uos.VfsLfs2(bdev, mtime=False), '/flash')
- It's fully backwards compatible, existing littlefs2 filesystems will work
  without reformatting and timestamps will be added transparently to
  existing files (once they are opened for writing).
- Files without timestamps will open correctly, and stat will just return 0
  for their timestamp.
- mtime can be disabled or enabled each mount time and timestamps will only
  be updated if mtime is enabled (otherwise they will be untouched).

Signed-off-by: Damien George <damien@micropython.org>
2020-08-25 17:35:19 +10:00
Damien George ee50a6effe py/mphal.h: Introduce mp_hal_time_ns and implement on various ports.
This should return a 64-bit value being the number of nanoseconds since
1970/1/1.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 16:13:44 +10:00
Damien George badd351150 lib/timeutils: Add helper functions to deal with nanosecs since 1970.
Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 15:41:10 +10:00
Damien George 92899354d9 unix/fatfs_port: Implement get_fattime.
Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 14:45:57 +10:00
Damien George 55c76eaac1 extmod/uasyncio: Truncate negative sleeps to 0.
Otherwise a task that continuously awaits on a large negative sleep can
monopolise the scheduler (because its wake time is always less than
everything else in the pairing heap).

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 12:17:06 +10:00
Damien George 20948a3d54 tests/extmod: Add test for uasyncio.sleep of a negative time.
It should take 0 time to await on a negative sleep.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 12:17:06 +10:00
Damien George 5f9b105244 py/runtime: Fix builtin compile() in "single" mode so it prints exprs.
As per CPython behaviour, compile(stmt, "file", "single") should create
code which prints to stdout (via __repl_print__) the results of any
expressions in stmt.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 11:38:46 +10:00
Damien George 448319a745 tools/makemanifest.py: Use os.makedirs to make path for generated files.
The existing implementation of mkdir() in this file is not sophisticated
enough to work correctly on all operating systems (eg Mac can raise
EISDIR).  Using the standard os.makedirs() function handles all cases
correctly.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 11:18:48 +10:00
Martin Milata 492cf34fd8 tools/mpy-tool.py: Fix offset of line number info.
Signed-off-by: Martin Milata <martin@martinmilata.cz>
2020-08-21 16:17:07 +10:00
Michael Buesch 60cf2c0959 tools/pyboard.py: Replace eval() of received data with alternative.
Prior to this commit, pyboard.py used eval() to "parse" file data received
from the board.  Using eval() on received data from a device is dangerous,
because a malicious device may inject arbitrary code execution on the PC
that is doing the operation.

Consider the following scenario:

Eve may write a malicious script to Bob's board in his absence.  On return
Bob notices that something is wrong with the board, because it doesn't work
as expected anymore.  He wants to read out boot.py (or any other file) to
see what is wrong.  What he gets is a remote code execution on his PC.

Proof of concept:

Eve:

  $ cat boot.py
  _print = print
  print = lambda *x, **y: _print("os.system('ls /; echo Pwned!')", end="\r\n\x04")
  $ ./pyboard.py -f cp boot.py :
  cp boot.py :boot.py

Bob:

  $ ./pyboard.py -f cp :boot.py /tmp/foo
  cp :boot.py /tmp/foo
  bin   chroot  dev  home  lib32  media  opt   root  sbin  sys  usr
  boot  config  etc  lib   lib64  mnt    proc  run   srv   tmp  var
  Pwned!

There's also the possibility that the device is malfunctioning and sends
random and possibly dangerous data back to the PC, to be eval'd.

Fix this problem by using ast.literal_eval() to parse the received bytes,
instead of eval().

Signed-off-by: Michael Buesch <m@bues.ch>
2020-08-21 16:08:03 +10:00
Dave Hylands 8727c4e2ec stm32/pin_defs_stm32: Fix pin printing to show IN mode correctly.
Prior to this commit, if you configure a pin as an output type (I2C in this
example) and then later configure it back as an input, then it will report
the type incorrectly.  Example:

    >>> import machine
    >>> b6 = machine.Pin('B6')
    >>> b6
    Pin(Pin.cpu.B6, mode=Pin.IN)
    >>> machine.I2C(1)
    I2C(1, scl=B6, sda=B7, freq=420000)
    >>> b6
    Pin(Pin.cpu.B6, mode=Pin.ALT_OPEN_DRAIN, pull=Pin.PULL_UP, af=Pin.AF4_I2C1)
    >>> b6.init(machine.Pin.IN)
    >>> b6
    Pin(Pin.cpu.B6, mode=Pin.ALT_OPEN_DRAIN, af=Pin.AF4_I2C1)

With this commit the last print now works:

    >>> b6
    Pin(Pin.cpu.B6, mode=Pin.IN)
2020-08-21 13:42:47 +10:00
Zenix27 e76c7466b6 docs: Change `\*` to `*` in argument lists.
Latest versions of Sphinx (at least 3.1.0) do not need the `*` escaped and
will render the `\` in the output if it is there, so remove it.

Fixes issue #6209.
2020-08-21 12:24:13 +10:00
Maureen Helm 17689a71f6 travis: Add zephyr build to CI.
Adds a job to build the zephyr port in CI using the same docker container
that the zephyr project uses for its own CI.

Always make clean zephyr builds to ensure we don't just rebuild C code, but
we also rebuild Kconfig and dts.  This is required when switching between
boards, which have different Kconfigs and device trees.

Uses the tagged zephyr 2.3.0 release.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-08-21 11:37:10 +10:00
Maureen Helm ac94e06f0b zephyr: Include storage/flash_map.h unconditionally.
Include storage/flash_map.h unconditionally so we always have access to the
FLASH_AREA_LABEL_EXISTS macro, even if CONFIG_FLASH_MAP is not defined.

This fixes a build error for the qemu_x86 board:

main.c:108:63: error: missing binary operator before token "("
  108 |     #elif defined(CONFIG_FLASH_MAP) && FLASH_AREA_LABEL_EXISTS(storage)
      |                                                               ^
../../py/mkrules.mk:88: recipe for target 'build/genhdr/qstr.i.last' failed

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-08-21 11:23:43 +10:00
Damien George 60f5b941e0 extmod/vfs_reader: Fix mp_reader_new_file to open file in "rb" mode.
mp_reader_new_file() is used to read in files for importing, either .py or
.mpy files, for the lexer and persistent code loader respectively.  In both
cases the file should be opened in raw bytes mode: the lexer handles
unicode characters itself, and .mpy files contain 8-bit bytes by nature.

Before this commit importing was working correctly because, although the
file was opened in text mode, all native filesystem implementations (POSIX,
FAT, LFS) would access the file in raw bytes mode via mp_stream_rw()
calling mp_stream_p_t.read().  So it was only an issue for non-native
filesystems, such as those implemented in Python.  For Python-based
filesystem implementations, a call to mp_stream_rw() would go via IOBase
and then to readinto() at the Python level, and readinto() is only defined
on files opened in raw bytes mode.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-12 23:40:50 +10:00
Damien George b731bd0ce6 tools/makemanifest.py: Print nicely formatted errors from mpy-cross.
If mpy-cross exits with an error be sure to print that error in a way that
is readable, instead of a long bytes object.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-08 14:46:05 +10:00
Damien George 9883d8e818 py/persistentcode: Maintain root ptr list of imported native .mpy code.
On ports where normal heap memory can contain executable code (eg ARM-based
ports such as stm32), native code loaded from an .mpy file may be reclaimed
by the GC because there's no reference to the very start of the native
machine code block that is reachable from root pointers (only pointers to
internal parts of the machine code block are reachable, but that doesn't
help the GC find the memory).

This commit fixes this issue by maintaining an explicit list of root
pointers pointing to native code that is loaded from an .mpy file.  This
is not needed for all ports so is selectable by the new configuration
option MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE.  It's enabled by default
if a port does not specify any special functions to allocate or commit
executable memory.

A test is included to test that native code loaded from an .mpy file does
not get reclaimed by the GC.

Fixes #6045.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-02 22:34:09 +10:00
Damien George 8da40baa47 tests/micropython: Improve .mpy import tests to run on more targets.
All imports are now tested to see if the test should be skipped,
UserFile.read is removed, and UserFile.readinto is made more efficient.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-26 22:44:59 +10:00
Damien George 0c0cef9870 tests: Move .mpy import tests from import/ to micropython/ dir.
These tests are specific to MicroPython so have a better home in the
micropython/ test subdir, and putting them here allows them to be run by
all targets, not just those that have access to the local filesystem (eg
the unix port).

Signed-off-by: Damien George <damien@micropython.org>
2020-07-26 22:04:31 +10:00
Damien George 952de5cb77 tools/makemanifest.py: Use errno.EEXIST instead of number 17.
To make this code more portable, across different platforms.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-26 10:56:24 +10:00
Damien George 441460d81f extmod/uasyncio: Add StreamReader.readexactly(n) method.
It raises on EOFError instead of an IncompleteReadError (which is what
CPython does).  But the latter is derived from EOFError so code compatible
with MicroPython and CPython can be written by catching EOFError (eg see
included test).

Fixes issue #6156.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-25 23:10:05 +10:00
Damien George fd2ff867a0 stm32/usbdev: Fix calculation of SCSI LUN size with multiple LUNs.
The SCSI driver calls GetCapacity to get the block size and number of
blocks of the underlying block-device/LUN.  It caches these values and uses
them later on to verify that reads/writes are within the bounds of the LUN.
But, prior to this commit, there was only one set of cached values for all
LUNs, so the bounds checking for a LUN could use incorrect values, values
from one of the other LUNs that most recently updated the cached values.
This would lead to failed SCSI requests.

This commit fixes this issue by having separate cached values for each LUN.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-25 01:12:07 +10:00
Jonathan Hogg 37e1b5c891 py/compile: Don't await __aiter__ special method in async-for.
MicroPython's original implementation of __aiter__ was correct for an
earlier (provisional) version of PEP492 (CPython 3.5), where __aiter__ was
an async-def function.  But that changed in the final version of PEP492 (in
CPython 3.5.2) where the function was changed to a normal one.  See
https://www.python.org/dev/peps/pep-0492/#why-aiter-does-not-return-an-awaitable
See also the note at the end of this subsection in the docs:
https://docs.python.org/3.5/reference/datamodel.html#asynchronous-iterators
And for completeness the BPO: https://bugs.python.org/issue27243

To be consistent with the Python spec as it stands today (and now that
PEP492 is final) this commit changes MicroPython's behaviour to match
CPython:  __aiter__ should return an async-iterable object, but is not
itself awaitable.

The relevant tests are updated to match.

See #6267.
2020-07-25 00:58:18 +10:00
Josh Lloyd fe7d47971f docs/esp32: Fix machine.Timer quickref to specify HW timers.
Also remove trailing spaces on other lines.
2020-07-25 00:50:06 +10:00
Howard Lovatt 47289f4bc9 docs/library: Update pyb.UART to correct pyboard UART availability.
On original pyboard UART 5 isn't available; added pyboard D availability.
2020-07-25 00:46:29 +10:00
Howard Lovatt 4a7c2731c5 docs/library: Update pyb.Timer to add missing args and defaults to init. 2020-07-25 00:34:48 +10:00
Howard Lovatt cf9be201d7 docs/library: Update pyb.SPI init method to add descr about "ti" arg. 2020-07-25 00:28:16 +10:00
Glenn Ruben Bakke caaaa2b1f4 nrf: Enable more features for all targets.
Enabling the following features for all targets, except for nrf51
targets compiled to be used with SoftDevice:

- MICROPY_PY_ARRAY_SLICE_ASSIGN
- MICROPY_PY_SYS_STDFILES
- MICROPY_PY_UBINASCII
2020-07-22 12:54:20 +02:00
Glenn Ruben Bakke 0a79e18398 nrf: Split mpconfigport.h into multiple files.
Splitting mpconfigport.h into multiple device specific
files in order to facilitate variations between devices.

Due to the fact that the devices might have variations in
features and also variations in flash size it makes sense
that some devices offers more functionality than others
without being limited by restricted devices.

For example more micropython features can be activated for
nrf52840 with 1MB flash, compared to nrf51 with 256KB.
2020-07-22 12:54:20 +02:00
Damien George d9b7261024 lib/libc: Fix string0's implementation of strncpy.
Fixing 98e583430f, the semantics of strncpy
require that the remainder of dst be filled with null bytes.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-22 16:29:54 +10:00
Zoltán Vörös 27767aafa2 lib/libm_dbl: Add round.c source code.
This code is imported from musl, to match existing code in libm_dbl.

The file is also added to the build in stm32/Makefile.  It's not needed by
the core code but, similar to c5cc64175b,
allows round() to be used by user C modules or board extensions.
2020-07-21 11:07:19 +10:00
Damien George a853fff838 py/obj.h: Fix mp_seq_replace_slice_no_grow to use memmove not memcpy.
Because the argument arrays may overlap, as show by the new tests in this
commit.

Also remove the debugging comments for these macros, add a new comment
about overlapping regions, and separate the macros by blank lines to make
them easier to read.

Fixes issue #6244.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-21 01:05:59 +10:00
Damien George 895b1dbdda tests/basics: Split out memoryview slice-assign tests to separate file.
Signed-off-by: Damien George <damien@micropython.org>
2020-07-21 01:05:59 +10:00
Damien George f80b1d8535 lib/stm32lib: Update library for H7 v1.6.0 and WB v1.6.0.
Changes in this new library version are:
- Update H7 HAL to v1.6.0.
- Update WB HAL to v1.6.0.
- Add patches to fix F4 ll_uart clock selection for UART9/UART10.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-21 01:02:58 +10:00
Kenneth Ryerson 76fefad18b esp32/network_lan: Add support for IP101 PHY.
Signed-off-by: Kenneth Ryerson <kenneth.ryerson@gmail.com>
2020-07-21 00:59:47 +10:00
Jonathan Hogg 5f0e9d1bac docs/library: Update documentation of esp32's RMT.
This explains how looping now works, and removes the warning about calling
wait_done().
2020-07-21 00:57:35 +10:00
Jonathan Hogg 7dbef5377c esp32/esp32_rmt: Properly fix looping behaviour of RMT.
A previous commit 3a9d948032 can cause
lock-ups of the RMT driver, so this commit reverses that, adds a loop_en
flag, and explicitly controls the TX interrupt in write_pulses().  This
provides correct looping, non-blocking writes and sensible behaviour for
wait_done().

See also #6167.
2020-07-21 00:57:14 +10:00
Thorsten von Eicken 5264478007 extmod/modussl_mbedtls: Integrate shorter error strings.
The stm32 and esp32 ports now use shorter error strings for mbedtls errors.
Also, MBEDTLS_ERROR_C is enabled on stm32 by default to get these strings.
2020-07-21 00:31:05 +10:00
Thorsten von Eicken 3e758ef235 lib/mbedtls_errors: Add code to patch mbedtls for shortened error strs.
The file `mbedtls_errors/mp_mbedtls_errors.c` can be used instead of
`mbedtls/library/error.c` to give shorter error strings, reducing the build
size of the error strings from about 12-16kB down to about 2-5kB.
2020-07-20 23:53:27 +10:00
Thorsten von Eicken 98e583430f lib/libc: Add implementation of strncpy. 2020-07-20 23:42:04 +10:00
Thorsten von Eicken 9aa214077e extmod/modussl: Improve exception error messages.
This commit adds human readable error messages when mbedtls or axtls raise
an exception.  Currently often just an EIO error is raised so the user is
lost and can't tell whether it's a cert error, buffer overrun, connecting
to a non-ssl port, etc.  The axtls and mbedtls error raising in the ussl
module is modified to raise:

    OSError(-err_num, "error string")

For axtls a small error table of strings is added and used for the second
argument of the OSErrer.  For mbedtls the code uses mbedtls' built-in
strerror function, and if there is an out of memory condition it just
produces OSError(-err_num).  Producing the error string for mbedtls is
conditional on them being included in the mbedtls build, via
MBEDTLS_ERROR_C.
2020-07-20 23:41:45 +10:00
Jim Mussared c7f7c0214c docs/library: For ubluetooth, add docs for _IRQ_GATTS_INDICATE_DONE. 2020-07-20 23:28:31 +10:00
Jim Mussared 9d823a5d9a extmod/modbluetooth: Add event for "indicate acknowledgement".
This commit adds the IRQ_GATTS_INDICATE_DONE BLE event which will be raised
with the status of gatts_indicate (unlike notify, indications require
acknowledgement).

An example of its use is added to ble_temperature.py, and to the multitests
in ble_characteristic.py.

Implemented for btstack and nimble bindings, tested in both directions
between unix/btstack and pybd/nimble.
2020-07-20 23:26:41 +10:00
Jim Mussared 3c7ca2004c extmod/modbluetooth: Fix so it builds in peripheral-only mode. 2020-07-20 23:25:56 +10:00
Jim Mussared 43ceadac55 extmod/modbluetooth: Ignore unused self_in in ble_gatts_indicate. 2020-07-20 23:25:22 +10:00
Jim Mussared b7698841b2 docs/library: Add gatts_indicate() doc to ubluetooth.rst.
Also clarify behavior of `gatts_notify` and add some TODOs about adding an
event for indication acknowledgement.
2020-07-18 14:34:44 +10:00
Jim Mussared 89a95b7c85 examples/bluetooth: Add simple UART demo with central and peripheral. 2020-07-18 14:34:29 +10:00
Jim Mussared e152d0c197 extmod/btstack: Schedule notify/indicate/write ops for bg completion.
The goal of this commit is to allow using ble.gatts_notify() at any time,
even if the stack is not ready to send the notification right now.  It also
addresses the same issue for ble.gatts_indicate() and ble.gattc_write()
(without response).  In addition this commit fixes the case where the
buffer passed to write-with-response wasn't copied, meaning it could be
modified by the caller, affecting the in-progress write.

The changes are:

- gatts_notify/indicate will now run in the background if the ACL buffer is
  currently full, meaning that notify/indicate can be called at any time.

- gattc_write(mode=0) (no response) will now allow for one outstanding
  write.

- gattc_write(mode=1) (with response) will now copy the buffer so that it
  can't be modified by the caller while the write is in progress.

All four paths also now track the buffer while the operation is in
progress, which prevents the GC free'ing the buffer while it's still
needed.
2020-07-18 14:23:47 +10:00
Jim Mussared 07aec4681f examples/bluetooth: In ble_advertising.py, skip appearance if not set. 2020-07-18 14:23:20 +10:00
Jim Mussared 5d0be97bd9 unix: Make the MICROPY_xxx_ATOMIC_SECTION mutex recursive.
This mutex is used to make the unix port behave more like bare metal, i.e.
it allows "IRQ handlers" to run exclusively by making the mutex recursive.
2020-07-18 14:22:06 +10:00
Glenn Ruben Bakke 342800c9a2 travis: Change nrf pca10056 board to build with s140 SoftDevice.
It might compile fine with S132 as SoftDevice for nRF52840.
However, there might be different hardware on the SoC which in
turn could make it fail.

SoftDevice S140 is correct BLE stack for nRF52840 SoC and would
provide a more accurate test build.
2020-07-17 13:07:32 +02:00
Matt Trentini 486cb6dd4a nrf: Add board definition for nRF52840-MDK-USB-Dongle. 2020-07-16 23:47:13 +10:00
Glenn Ruben Bakke d9e8edc8bc travis: Add pca10090 build to nrf job. 2020-07-16 11:51:52 +02:00
Glenn Ruben Bakke 411e1157e7 travis: Install newer toolchain for nrf job.
Update toolchain to GNU Arm Embedded Toolchain.
2020-07-16 11:51:52 +02:00
Glenn Ruben Bakke 95d0d1c486 nrf/boards: Enable RTCounter machine module for nrf9160 boards.
Resolves dependencies for MICROPY_PY_TIME_TICKS which
requires to link against nrfx_rtc.c functions by setting
MICROPY_PY_MACHINE_RTCOUNTER to 1.
2020-07-16 11:48:52 +02:00
Glenn Ruben Bakke b776fe6969 nrf/nrfx_config: Disable RTC2 for nRF9160 targets.
nRF9160 does not have any RTC2. Disable the configuration in
case of NRF9160_XXAA.
2020-07-16 11:44:44 +02:00
Alex Tsamakos f743bd3d25
nrf/boards: Add initial support for Actinius Icarus.
Example make command:

make BOARD=actinius_icarus
2020-07-10 03:48:30 +02:00
Thomas Friebel b6146ca1a1 extmod/nimble: Fix attr NULL ptr dereference in ble_gatt_attr_read_cb.
In case of error, NimBLE calls the read callback with attr = NULL.
2020-07-09 22:41:10 +10:00
iabdalkader c299cc94e3 stm32/pyb_can: Handle timeout arg for FDCAN in pyb_can_send.
Following the documented pyb can_send behavior in pyb.CAN docs.
2020-07-09 00:38:56 +10:00
iabdalkader d07073f4e2 stm32/fdcan: Support maximum timeout of HAL_MAX_DELAY in can_receive. 2020-07-09 00:38:40 +10:00
iabdalkader 63b2eb27d4 stm32/fdcan: Use FDCAN_RXFxS_FxFL instead of hard-coded value. 2020-07-09 00:38:33 +10:00
iabdalkader 8594389fe7 stm32/fdcan: Use the right FIFO to calc element address in can_receive. 2020-07-09 00:37:50 +10:00
Damien George f5dd46b479 unix/variants: Enable VFS and all supported filesystems on dev variant.
So that micropython-dev can be used to test VFS code, and inspect and build
filesystem images that are compatible with bare-metal systems.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-08 23:57:25 +10:00
Martin Fischer 59ed3bdd9f nrf: Enable nrf tick support on all boards by default.
Having time.ticks_ms/us/add/diff is very useful and used by many drivers,
libraries and components.
2020-07-08 23:47:08 +10:00
Martin Fischer 15574cd665 nrf: Add support for time.ticks_xxx functions using RTC1.
This commit adds time.ticks_ms/us support using RTC1 as the timebase.  It
also adds the time.ticks_add/diff helper functions.  This feature can be
enabled using MICROPY_PY_TIME_TICKS.  If disabled the system uses the
legacy sleep methods and does not have any ticks functions.

In addition support for MICROPY_EVENT_POLL_HOOK was added to the
time.sleep_ms(x) function, making this function more power efficient and
allows support for select.poll/asyncio.  To support this, the RTC's CCR0
was used to schedule a ~1msec event to wakeup the CPU.

Some important notes about the RTC timebase:

- Since the granularity of RTC1's ticks are approx 30usec, time.ticks_us is
not perfect, does not have 1us resolution, but is otherwise quite usable.
For tighter measurments the ticker's 1MHz counter should be used.

- time.ticks_ms(x) should *not* be called in an IRQ with higher prio than
the RTC overflow irq (3).  If so it introduces a race condition and
possibly leads to wrong tick calculations.

See #6171 and #6202.
2020-07-08 23:47:02 +10:00
Glenn Ruben Bakke c2317a3a8d nrf/Makefile: Disable ROM text compression when compiling for debug.
When compiling for debug (-O0) the .text segment cannot fit the flash
region when MICROPY_ROM_TEXT_COMPRESSION=1, because the compiler does not
optimise away the large if-else chain used to select the correct compressed
string.

This commit enforces MICROPY_ROM_TEXT_COMPRESSION=0 when compiling for
debug (DEBUG=1).
2020-07-01 22:54:52 +10:00
Glenn Ruben Bakke f22f7b285e nrf/bluetooth/ble_uart: Swap end character on cooked strings.
Changing line ending character of cooked strings makes rshell/pyboard.py
work correctly over Bluetooth socat/pts devices.
2020-07-01 22:51:30 +10:00
Glenn Ruben Bakke 5996bf72f1 nrf/bluetooth/ble_uart: Fix random advertisement name.
The storage space of the advertisement name is not declared static, leading
to a random advertisement name.  This commit fixes the issue by declaring
it static.
2020-07-01 22:50:56 +10:00
Glenn Ruben Bakke ab0c14dba0 nrf/bluetooth/ble_uart: Add mp_hal_stdio_poll function.
This adds support for enabling MICROPY_PY_SYS_STDFILES when running UART
over Bluetooth (NUS).
2020-07-01 22:50:41 +10:00
Glenn Ruben Bakke fc1f22a097 nrf/bluetooth: Handle data length update request.
The Bluetooth link gets disconnected when connecting from a PC after 30-40
seconds.  This commit adds handling of the data length update request.  The
data length parameter pointer is set to NULL in the reply,  letting the
SoftDevice automatically set values and use them in the data length update
procedure.
2020-07-01 22:49:04 +10:00
Glenn Ruben Bakke 9dfb4ae6aa nrf/bluetooth/ble_uart: Fix implicit declaration of function.
mp_keyboard_interrupt() triggers a compiler error because the function is
implicitly declared.  This commit adds "py/runtime.h" to the includes.

Fixes issue #5732.
2020-07-01 22:48:25 +10:00
Jim Mussared 4050281311 unix: Enable uasyncio on dev variant. 2020-07-01 22:44:41 +10:00
Jim Mussared 27abac95d8 unix: Make manifest selection match other ports.
Changes are:
- The default manifest.py is moved to the variants directory (it's in
  "boards" in other ports).
- The coverage variant now uses a custom manifest in its variant directory
  to add frzmpy/frzstr.
- The frzmpy/frzstr tests are moved to variants/coverage/.
2020-07-01 22:42:55 +10:00
Andrew Leech 07f181a216 Revert "tools/pydfu.py: Respect longer timeouts requested by DFU dev..."
This reverts commit 4d6f60d428.

This implementation used the timeout as a maximum amount of time needed for
the operation, when actually the spec and other tools suggest that it's the
minumum delay needed between subsequent USB transfers.
2020-07-01 16:54:03 +10:00
Andrew Leech 494bcad8ab stm32/mboot: Disable polling mode by default and use IRQ mode instead.
Polling mode will cause failures with the mass-erase command due to USB
timeouts, because the USB IRQs are not being serviced.  Swiching from
polling to IRQ mode fixes this because the USB IRQs can be serviced between
page erases.

Note that when the flash is being programmed or erased the MCU is halted
and cannot respond to USB IRQs, because mboot runs from flash, as opposed
to the built-in bootloader which is in system ROM.  But the maximum delay
in responding to an IRQ is the time taken to erase a single page, about
100ms for large pages, and that is short enough that the USB does not
timeout on the host side.

Recent tests have shown that in the current mboot code IRQ mode is pretty
much the same speed as polling mode (within timing error), code size is
slightly reduced in IRQ mode, and IRQ mode idles at about half of the power
consumption as polling mode.
2020-07-01 16:54:03 +10:00
Andrew Leech 95ec0debec stm32/mboot: Remove the use of timeout in DFU_GETSTATUS.
This is treated more like a "delay before continuing" in the spec and
official tools and does not appear to be really needed.  In particular,
downloading firmware is much slower with non-zero timeouts because the host
must pause by the timeout between sending each DFU_GETSTATUS to poll for
download/erase complete.
2020-07-01 16:33:10 +10:00
Damien George 332d83343f py: Rework mp_convert_member_lookup to properly handle built-ins.
This commit fixes lookups of class members to make it so that built-in
functions that are used as methods/functions of a class work correctly.

The mp_convert_member_lookup() function is pretty much completely changed
by this commit, but for the most part it's just reorganised and the
indenting changed.  The functional changes are:

- staticmethod and classmethod checks moved to later in the if-logic,
  because they are less common and so should be checked after the more
  common cases.

- The explicit mp_obj_is_type(member, &mp_type_type) check is removed
  because it's now subsumed by other, more general tests in this function.

- MP_TYPE_FLAG_BINDS_SELF and MP_TYPE_FLAG_BUILTIN_FUN type flags added to
  make the checks in this function much simpler (now they just test this
  bit in type->flags).

- An extra check is made for mp_obj_is_instance_type(type) to fix lookup of
  built-in functions.

Fixes #1326 and #6198.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-30 23:55:32 +10:00
Damien George d06ae1d2b1 py/obj.h: Make existing MP_TYPE_FLAG_xxx macros sequential.
There's no reason to have them non-sequential, this was likely a typo from
commit 9ec1caf42e.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-30 23:55:32 +10:00
Damien George 41b7734c46 zephyr/make-minimal: Disable FAT and LFS2 options to make it build.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-30 22:33:41 +10:00
Damien George f84145bea1 zephyr: Implement machine.Pin.irq() for setting callbacks on pin change.
Supports hard and soft interrupts.  In the current implementation, soft
interrupt callbacks will only be called when the VM is executing, ie they
will not be called during a blocking kernel call like k_msleep.  And the
behaviour of hard interrupt callbacks will depend on the underlying device,
as well as the amount of ISR stack space.

Soft and hard interrupts tested on frdm_k64f and nucleo_f767zi boards.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-30 22:33:41 +10:00
Damien George 9d5edb3559 lib/utils: Protect all of mpirq.c with MICROPY_ENABLE_SCHEDULER.
So it can be unconditionally included in a port's build even if certain
configurations in that port do not use its features, to simplify the
Makefile.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-30 22:31:41 +10:00
spacemanspiff2007 b572aa5721 docs/esp32: Add info about PWM duty cycle range to esp32 quickref.
See related #4581.
2020-06-30 22:28:09 +10:00
victor cb9aafbf8f docs/library: Clarify that the arg to esp.deepsleep is in microseconds. 2020-06-30 22:01:44 +10:00
Damien George 65a7e00078 stm32/mboot: Add DFU logic to respond to DFU_GETSTATE request.
This is required for some DFU programmers, eg ST's DfuSe demo PC app.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-30 21:28:24 +10:00
Andrew Leech 40006813c3 stm32/flash: Update flash_get_sector_info to return -1 on invalid addr.
So the caller can tell when an invalid address is used and can take
appropriate action.
2020-06-30 21:24:28 +10:00
Andrew Leech 8bbaa20227 stm32/mboot: Implement DFU mass erase.
The implementation internally uses sector erase to wipe everything except
the sector(s) that mboot lives in (by erasing starting from
APPLICATION_ADDR).

The erase command can take some time (eg an STM32F765 with 2MB of flash
takes 8 to 10 seconds).  This time is normally enough to make pydfu.py fail
with a timeout.  The DFU standard includes a mechanism for the DFU device
to request a longer timeout as part of the get-status response just before
starting an operation.  This timeout functionality has been implemented
here.
2020-06-30 21:22:21 +10:00
Andrew Leech 4d6f60d428 tools/pydfu.py: Respect longer timeouts requested by DFU device/mboot. 2020-06-30 21:22:00 +10:00
Damien George 048a1d675d stm32/timer: Properly initialise timer deadtime/brk on WB MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-29 17:35:42 +10:00
Andrew Leech e4fcd216e0 stm32/usbd_cdc_interface: Remove full==size-1 limitation on tx ringbuf.
Before this commit the USB VCP TX ring-buffer used the basic implementation
where it can only be filled to a maximum of buffer size-1.  For a 1024 size
buffer this means the largest packet that can be sent is 1023.  Once a
packet of this size is sent the next byte copied in goes to the final byte
in the buffer, so must be sent as a 1 byte packet before the read pointer
can be wrapped around to the beginning.  So in large streaming transfers,
watching the USB sniffer you basically get alternating 1023 byte packets
then 1 byte packets.

This commit changes the ring-buffer implementation to a scheme that doesn't
have the full-size limitation, and the USB VCP driver can now achieve a
constant stream of full-sized packets.  This scheme introduces a
restriction on the size of the buffer: it must be a power of 2, and the
maximum size is half of the size of the index (in this case the index is
16-bit, so the maximum size would be 32767 bytes rounded to 16384 for a
power-of-2).  But this is not a big limitation because the size of the
ring-buffer prior to this commit was restricted to powers of 2 because it
was using a mask-based method to wrap the indices.

For an explanation of the new scheme see
https://www.snellman.net/blog/archive/2016-12-13-ring-buffers/

The RX buffer could likely do with a similar change, though as it's not
read from in chunks like the TX buffer it doesn't present the same issue,
all that's lost is one byte capacity of the buffer.

USB VCP TX throughput is improved by this change, potentially doubling the
speed in certain cases.
2020-06-29 17:21:37 +10:00
Damien George 9f911d822e py/objcomplex: Add mp_obj_get_complex_maybe for use in complex bin-op.
This allows complex binary operations to fail gracefully with unsupported
operation rather than raising an exception, so that special methods work
correctly.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-27 01:03:10 +10:00
Damien George 41fa8b5482 py/emitnative: Implement binary operations for viper uint operands.
uint types in viper mode can now be used for all binary operators except
floor-divide and modulo.

Fixes issue #1847 and issue #6177.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-27 00:24:04 +10:00
Damien George b3b8706d27 py/asm: Add condition codes for signed comparisons.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-27 00:24:04 +10:00
Damien George aa26fe62d8 py/asm: Add funcs/macros to emit machine code for logical-shift-right.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-27 00:24:04 +10:00
Damien George 137df81757 stm32/i2cslave: Pass I2C instance to callbacks to support multi I2Cs.
By passing through the I2C instance to the application callbacks, the
application can implement multiple I2C slave devices on different
peripherals (eg I2C1 and I2C2).

This commit also adds a proper rw argument to i2c_slave_process_addr_match
for F7/H7/WB MCUs, and enables the i2c_slave_process_tx_end callback.
Mboot is also updated for these changes.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-26 23:56:45 +10:00
Damien George 6475cdb7d0 travis: Build mboot for PYBV10 with LFS2 enabled in stm32 job.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-26 21:29:32 +10:00
Damien George 0a8ce0d568 stm32/mboot: Update README to describe WB and littlefs support.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-26 21:26:06 +10:00
Damien George 67fd58bbd2 stm32/mboot: Add support for littlefs.
Mboot now supports FAT, LFS1 and LFS2 filesystems, to load firmware from.
The filesystem needed by the board must be explicitly enabled by the
configuration variables MBOOT_VFS_FAT, MBOOT_VFS_LFS1 and MBOOT_VFS_LFS2.
Boards that previously used FAT implicitly (with MBOOT_FSLOAD enabled) must
now add the following config to mpconfigboard.h:

    #define MBOOT_VFS_FAT (1)

Signed-off-by: Damien George <damien@micropython.org>
2020-06-26 21:17:02 +10:00
Damien George 390f32922d stm32/mboot: Decouple stream, filesystem and top-level loading code.
This commit factors the code for files and streaming to separate source
files (vfs_fat.c and gzstream.c respectively) and introduces an abstract
gzstream interface to make it easier to plug in different filesystems.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-26 21:15:30 +10:00
Damien George 763bd448a4 stm32/mboot: Don't search for firmware on FS, just attempt to open it.
There's no need to do a directory listing to search for the given firmware
filename, it just takes extra time and code size.  Instead this commit
changes it so that the requested firmware file is opened immediately and
will abort if the file couldn't be opened.  This also allows to specify
files in a directory.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-26 21:11:03 +10:00
Damien George 717b5073aa stm32/boards: Enable LFS2 on PYBD_SF3 and PYBD_SF6.
This was missed in commit 120368ba1a

Signed-off-by: Damien George <damien@micropython.org>
2020-06-25 16:32:48 +10:00
Damien George c5af3217d9 stm32/timer: Support TIM1 on WB MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-25 16:32:48 +10:00
Damien George eb9850ef6c stm32/mpconfigport.h: Enable PY_IO_FILEIO when any VFS is enabled.
Previously, if FAT was not enabled but LFS1/2 was then MICROPY_PY_IO_FILEIO
would be disabled and file binary-mode was not supported.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-25 16:32:48 +10:00
Damien George 0c77668d11 extmod/vfs_lfs: Fix littlefs bindings to build in nan-box mode.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-25 16:32:48 +10:00
Damien George 76faeed098 tools/makemanifest.py: Support freezing a subdirectory recursively.
This adds support for freezing an entire directory while keeping the
directory as part of the import path.  For example

    freeze("path/to/library", "module")

will recursively freeze all scripts in "path/to/library/module" and have
them importable as "from module import ...".

Signed-off-by: Damien George <damien@micropython.org>
2020-06-24 12:21:30 +10:00
Damien George 457fdf61c3 py/objtype: Support passing in an OrderedDict to type() as the locals.
An OrderedDict can now be used for the locals when creating a type
explicitly via type(name, bases, locals).

Signed-off-by: Damien George <damien@micropython.org>
2020-06-24 12:05:40 +10:00
Damien George 7dd480ad55 extmod/moductypes: Use mp_obj_is_dict_or_ordereddict to simplify code.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-24 12:05:00 +10:00
Damien George 456a3abe8d py/obj.h: Add public mp_obj_is_dict_or_ordereddict() helper macro.
And use it in py/objdict.c instead of mp_obj_is_dict_type.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-24 12:05:00 +10:00
Damien George b4dc4c5b9a stm32/mboot: Use additional CFLAGS to compile string0.c.
This is the same as a902b69dd5 but applied to
mboot's Makefile.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-23 14:00:16 +10:00
Damien George 81a7293ed6 stm32/mboot: Set VTOR on start up to ensure it has the correct value.
Commit 8675858465 switched to using the CMSIS
provided SystemInit function which sets VTOR to 0x00000000 (previously it
was 0x08000000).  A VTOR of 0x00000000 will be correct on some MCUs but not
on others where the built-in bootloader is remapped to this address, via
__HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH().

To make sure mboot has the correct vector table, this commit explicitly
sets VTOR to the correct value of 0x08000000.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-23 13:56:20 +10:00
Damien George 13ad1a4f06 travis: In stm32 job, build mboot for NUCLEO_WB55.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George 6f40e6e131 stm32/boards: Add build-time option for NUCLEO_WB55 to use mboot.
As an example of how to use mboot on a WB series MCU.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George 705728369d stm32/mboot: Add support for using mboot with WB MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George 8675858465 stm32/mboot: Use CMSIS system source code for SystemInit function.
There's no need to duplicate this functionality in mboot, the code provided
in stm32lib/CMSIS does the same thing and makes it easier to support other
MCU series.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George a8778c8dc8 stm32/mboot: Use flash routines from main stm32 code rather than custom.
The flash functions in ports/stm32/flash.c are almost identical to those in
ports/stm32/mboot/main.c, so remove the duplicated code in mboot and use
instead the main stm32 code.  This also allows supporting other MCU series.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George 736daebfc8 stm32/flash: Add flash_is_valid_addr, and extend sectors for 2MB F7.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George 4c8a68df6f stm32/i2cslave: Add support for WB MCUs.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George afd47d58ac stm32/flash: Make flash C-API reusable, and funcs return an error code.
This commit makes the low-level flash C functions usable by code other than
flashbdev.c (eg by mboot).  Changes in this commit are:
- flash_erase() and flash_write() now return an errno error code, a
  negative value on error.
- flash_erase() now automatically locks the flash, as well as unlocking it.
- flash_write() now automatically unlocks the flash, as well as locking it.
- flashbdev.c is modified for the above changes.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 14:18:15 +10:00
Damien George ce326699d7 stm32/powerctrlboot: Include irq.h to get definitions of IRQ priorities.
irq.h is included by py/mphal.h but it's better to be explicit, eg if mboot
uses powerctrlboot.c.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 13:47:48 +10:00
Damien George 5f3c2f1fa8 stm32/irq: Clean up irq.h so it does not depend on core uPy defines.
The irq.h file now just provides low-level IRQ definitions and priorities.
All Python binding definitions are moved to modmachine.h, with some
renaming of pyb -> machine, and also the machine_idle definition (was
pyb_wfi) is moved to modmachine.c.

The cc3200 and teensy ports are updated to build with these changes.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 13:47:15 +10:00
Damien George ac15be9365 travis: Build qemu-arm with MP_ENDIANNESS_BIG=1 to test bigendian build.
Eventually it would be good to run the full test suite on a big-endian
system, but for now this will help to catch build errors with the
big-endian configuration.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 13:42:24 +10:00
Damien George f1ba2c9d88 qemu-arm/Makefile: Add CFLAGS_EXTRA to CFLAGS.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 13:42:24 +10:00
Damien George 6164c7e666 py/misc.h: Add missing semi-colon in mp_float_union_t for big-endian.
Fixes issue #6161.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-22 13:42:24 +10:00
Jonathan Hogg 3a9d948032 esp32/esp32_rmt: Call rmt_driver_install before rmt_config.
Otherwise the RMT will repeat pulses when using loop(True).  This repeating
is due to a bug in the IDF which will be fixed in an upcoming release, but
for now the accepted workaround is to swap these calls, which should still
work in the fixed version of the IDF.

Fixes issue #6167.
2020-06-19 22:11:14 +10:00
David Lechner 77ed6f69ac tools/uncrustify: Enable more opts to remove space between func and '('.
With only `sp_func_proto_paren = remove` set there are some cases where
uncrustify misses removing a space between the function name and the
opening '('.  This sets all of the related options to `force` as well.
2020-06-19 22:07:32 +10:00
Damien George 026fda605e tools/codeformat.py: Include extmod/{btstack,nimble} in code formatting.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-18 22:20:20 +10:00
Damien George ce02d5e348 stm32/boards/NUCLEO_WB55: Add more CPU pins and aliases to SW1/2/3.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-18 10:48:24 +10:00
Damien George c521c178e9 github: Add FUNDING.yml file pointing to micropython GitHub sponsorship.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-18 00:02:53 +10:00
Damien George cba3e25cb3 travis: Change nrf pca10056 board to build with soft-device enabled.
To test building with SD which enables a lot of additional code.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-17 11:39:52 +10:00
Glenn Ruben Bakke 8d71cc2e7d nrf/bluetooth: Use MP_ERROR_TEXT for all error messages.
This follows up on commit def76fe4d9.

Fixes issue #6152.
2020-06-17 11:33:22 +10:00
Damien George 4b5dd012e0 stm32/rfcore: Leave txpower level as default when initialising rfcore.
And provide a convenient API function to change it (currently unused).

Fixes issue #5985.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-17 00:10:29 +10:00
Damien George 289be6b352 stm32/usb: Add support for 2xVCP on L0, L432 and WB MCUs.
There are a maximum of 8 USB endpoints and each has 2 buffer slots
(in/out).  This commit add support for up to 8 endpoints and adds FIFO
configuration for USB profiles with 2xVCP on MCUs that have device-only USB
peripherals.

Tested on NUCLEO_WB55 in 2xVCP, 2xVCP+MSC and 2xVCP+MSC+HID mode.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-17 00:09:42 +10:00
Damien George da99e0f979 stm32/factoryreset: Provide empty create-FS function when FAT disabled.
Signed-off-by: Damien George <damien@micropython.org>
2020-06-17 00:09:37 +10:00
Jon Rob 1678f41744 esp32/esp32_rmt: Extend RMT to support carrier feature.
The ESP32 RMT peripheral has hardware support for a carrier frequency, and
this commit exposes it to Python with the keyword arguments carrier_freq
and carrier_duty_percent in the constructor.  Example usage:

    r = esp32.RMT(0, pin=Pin(2), clock_div=80, carrier_freq=38000, carrier_duty_percent=50)
2020-06-17 00:03:33 +10:00
Damien George a51eef4471 tests/basics: Add tests for variable annotations. 2020-06-16 23:18:01 +10:00
Damien George f2e267da68 py/compile: Implement PEP 526, syntax for variable annotations.
This addition to the grammar was introduced in Python 3.6.  It allows
annotating the type of a varilable, like:

    x: int = 123
    s: str

The implementation in this commit is quite simple and just ignores the
annotation (the int and str bits above).  The reason to implement this is
to allow Python 3.6+ code that uses this feature to compile under
MicroPython without change, and for users to use type checkers.

In the future viper could use this syntax as a way to give types to
variables, which is currently done in a bit of an ad-hoc way, eg
x = int(123).  And this syntax could potentially be used in the inline
assembler to define labels in an way that's easier to read.
2020-06-16 23:18:01 +10:00
Damien George 131b0de70a py/grammar.h: Consolidate duplicate sub-rules for :test and =test. 2020-06-16 23:18:01 +10:00
Damien George a3c89cf907 tests/cpydiff: Add CPy diff test for assignment expression behaviour. 2020-06-16 22:06:47 +10:00
Damien George e0fe8ea644 tests/basics: Add tests for assignment operator :=. 2020-06-16 22:06:30 +10:00
Damien George 2c5993c59e ports: Disable MICROPY_PY_ASSIGN_EXPR in bare-arm and minimal ports.
To keep these ports as minimal as possible.
2020-06-16 22:06:21 +10:00
Damien George 1783950311 py/compile: Implement PEP 572, assignment expressions with := operator.
The syntax matches CPython and the semantics are equivalent except that,
unlike CPython, MicroPython allows using := to assign to comprehension
iteration variables, because disallowing this would take a lot of code to
check for it.

The new compile-time option MICROPY_PY_ASSIGN_EXPR selects this feature and
is enabled by default, following MICROPY_PY_ASYNC_AWAIT.
2020-06-16 22:02:24 +10:00
Damien George 0fd91e39b1 py/compile: Convert scope test to SCOPE_IS_COMP_LIKE macro.
This macro can be used elsewhere.
2020-06-16 21:42:37 +10:00
David Lechner b4d0d7bf03 tools/uncrustify: Update config for v0.71.0.
This is the result of running...

    uncrustify -c tools/uncrustify.cfg --update-config-with-doc -o tools/uncrustify.cfg

...with some manual fixups to correct places where it changed things it
should not have.

Essentially it just adds new config parameters introduced in v0.71.0
with their default values.

Signed-off-by: David Lechner <david@pybricks.com>
2020-06-14 11:08:05 -05:00
David Lechner ecd7826316 tools/codeformat.py: Remove sizeof fixup.
Formatting for `* sizeof` was fixed in uncrustify v0.71, so we no longer
need the fixups for it.  Also, there was one file where the updated
uncrustify caught a problem that the regex didn't pick up, which is updated
in this commit.

Signed-off-by: David Lechner <david@pybricks.com>
2020-06-14 20:24:18 +10:00
David Lechner bd7c92e17d tools/uncrustify.cfg: Remove deprecated sp_word_brace option.
This option was removed in uncrustify v0.71.

Signed-off-by: David Lechner <david@pybricks.com>
2020-06-14 20:24:03 +10:00
Damien George 5093597542 top: Update contribution and commit guide to include optional sign-off.
MicroPython already requires contributors to implicitly sign-off on a set
of points, which are listed in CODECONVENTIONS.md.

This commit adjusts this wording to allow explicit sign-off using the git
"Signed-off-by:" feature.  There is no reference made to
https://developercertificate.org/ because the project already has its own
version of this.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-12 13:32:22 +10:00
Damien George 2b9900380a stm32/boards/STM32F769DISC: Use macro instead of const for flash size.
So that the flash size can be changed in just one place.  Also remove the
duplicate cache entry.
2020-06-12 10:28:26 +10:00
Maureen Helm 1ae861819d zephyr: Use cmake find_package to locate zephyr.
Updates the zephyr port to use the ZEPHYR_BASE environment variable only to
locate the zephyr cmake package, allowing cmake to cache the variable.
2020-06-12 10:25:16 +10:00
Maureen Helm b1651ff092 zephyr: Increase minimum required cmake version to 3.13.1.
The minimum required cmake version has been 3.13.1 since zephyr 1.14.0.
2020-06-12 10:25:13 +10:00
Maureen Helm 4837b1caa2 zephyr: Convert DT_FLASH_AREA usages to new dts macros.
Converts DT_FLASH_AREA usages in the zephyr port to new device tree macros
introduced in zephyr 2.3.

Tested with littlefs on the reel_board.
2020-06-12 10:25:04 +10:00
Maureen Helm 6aff27ac3c zephyr: Update to new zephyr timeout API.
Updates the zephyr port to use the new timeout api introduced in zephyr
2.3.
2020-06-12 10:24:54 +10:00
Maureen Helm db02cb061d zephyr: Update for refactored zephyr device structures.
Updates the zephyr port to use refactored device structures introduced in
zephyr 2.3.
2020-06-12 10:24:46 +10:00
Maureen Helm 8b061f2d79 zephyr: Fix floating point configuration.
Zephyr renamed CONFIG_FLOAT to CONFIG_FPU to better reflect its semantics
of enabling the hardware floating point unit (FPU) rather than enabling
toolchain-level floating point support (i.e., software floating point for
FPU-less socs).
2020-06-12 10:24:30 +10:00
Maureen Helm 38b4f1569e zephyr: Fix and rename stacks_analyze function in zephyr module.
Zephyr deprecated and then removed its stack_analyze function because it
was unsafe.  Use the new zephyr thread analyzer instead and rename the
MicroPython function to zephyr.thread_analyze() to be more consistent with
the implementation.

Tested on mimxrt1050_evk.

The output now looks like this:

>>> zephyr.thread_analyze()
Thread analyze:
 80004ff4            : unused 400 usage 112 / 512 (21 %)
 rx_workq            : unused 1320 usage 180 / 1500 (12 %)
 tx_workq            : unused 992 usage 208 / 1200 (17 %)
 net_mgmt            : unused 656 usage 112 / 768 (14 %)
 sysworkq            : unused 564 usage 460 / 1024 (44 %)
 idle                : unused 256 usage 64 / 320 (20 %)
 main                : unused 2952 usage 1784 / 4736 (37 %)
2020-06-12 10:24:01 +10:00
Albort Xue 05e5d411b5 mimxrt/boards: Set __heap_size__ to 0 in MIMXRT1011.ld.
Do not use the traditional C heap in order to save memory, because the
traditional C heap is unused in MicroPython.
2020-06-10 22:49:26 +10:00
Nick Crabtree 2934e41df0 docs/esp8266: Add quickref documentation for UART on esp8266.
This patch adds quickref documentation for the change in commit
afd0701bf7.  This commit added the ability to
disable the REPL and hence use UART0 for serial communication on the
esp8266, but was not previously documented anywhere.

The text is largely taken from the commit message, with generic information
on using the UART duplicated from the Wipy quickref document.
2020-06-10 22:46:09 +10:00
Jim Mussared 00c3e2156a tests/run-multitests.py: Allow passing unique env vars to each instance.
For example, to run the BLE multitests entirely with the unix port:

    env MICROPY_MICROPYTHON=../ports/unix/micropython-dev ./run-multitests.py \
        -i micropython,MICROPYBTUSB=01 \
        -i micropython,MICROPYBTUSB=02:02 \
        multi_bluetooth/ble_*.py
2020-06-10 22:41:57 +10:00
Jim Mussared 3f77f2c60c unix/btstack_usb: Allow choosing adaptor via environment variable.
This allows running (for example):

    env MICROPYBTUSB=2-2 ./micropython-dev ../../examples/bluetooth/ble_temperature_central.py
2020-06-10 22:40:02 +10:00
Jim Mussared c6fd6a0d72 examples/bluetooth: Fix event code in ble_temperature_central.py. 2020-06-10 22:39:54 +10:00
jp-96 3705bc418c extmod/modbluetooth: Register default GATT service and fix esp32 init.
This is for the NimBLE bindings, to make sure the default GATT service
appears and that the esp32 initialises NimBLE correctly (it now matches
stm32).
2020-06-10 22:33:29 +10:00
Damien George a4c96fb3b0 extmod/uasyncio: Add asyncio.wait_for_ms function.
Fixes issue #6107.
2020-06-10 22:29:44 +10:00
Damien George f3062b5cbd py/obj.h: Clarify comments about mp_map_t is_fixed and is_ordered.
Long ago, prior to 0ef01d0a75, fixed and
ordered maps were the same setting with the "table_is_fixed_array" member
of mp_map_t.  But these settings are actually independent, and it is
possible to have is_fixed=1, is_ordered=0 (although this can currently
only be done by tools/cc1).  So update the comments to reflect this.
2020-06-10 22:27:10 +10:00
Andrew Leech 95cbe6b65e py/objtype: Use mp_obj_dict_copy() for creating obj.__dict__ attribute.
The resulting dict is now marked as read-only (is_fixed=1) to enforce the
fact that changes to this dict will not be reflected in the class instance.

This commit reduces code size by about 20 bytes, and should be more
efficient because it creates a direct copy of the dict rather than
reinserting all elements.
2020-06-10 22:03:39 +10:00
Andrew Leech 28370c0450 py/objtype: Add __dict__ attribute for class objects.
The behavior mirrors the instance object dict attribute where a copy of the
local attributes are provided (unless the dict is read-only, then that dict
itself is returned, as an optimisation).  MicroPython does not support
modifying this dict because the changes will not be reflected in the class.

The feature is only enabled if MICROPY_CPYTHON_COMPAT is set, the same as
the instance version.
2020-06-10 21:58:13 +10:00
Philipp Ebensberger 29e258611a mimxrt/boards: Integrate support for MIMXRT1020_EVK board. 2020-06-09 19:04:23 +10:00
Albort Xue e0d539f79d mimxrt/boards: Enable LED class for MIMXRT1060_EVK board. 2020-06-09 18:51:08 +10:00
Jim Mussared 8e8dcdd34b esp32: Update IDF v4.0 supported hash to v4.0.1.
The main fix relevant to MicroPython is https://github.com/espressif/esp-idf/issues/4196

Release notes here
https://github.com/espressif/esp-idf/releases/tag/v4.0.1
2020-06-09 16:15:47 +10:00
stijn 51fd6c9777 extmod/ure: Use single function for match/search/sub.
Saves about 500 bytes on unix x64 and enables CPython-conform
usage of passing a re object to these functions.
2020-06-08 09:16:09 +02:00
Damien George bd06c698f0 py/dynruntime.h: Make mp_obj_str_get_str raise if arg not a str/bytes. 2020-06-08 09:05:03 +02:00
Philipp Ebensberger 6ac05af8e1 mimxrt/tusb_config.h: Preliminary fix for TinyUSB HS endpoint overflow.
Sending more than 64 bytes to the USB CDC endpoint in HS mode will lead to
a hard crash.  This commit fixes the issue, although there may be a better
fix from upstream TinyUSB in the future.
2020-06-08 14:39:21 +10:00
David Lechner 1e6d18c915 docs: Fix Sphinx 3.x warnings, and enable warnings-as-errors on build.
This enables warnings as errors and fixes all current errors, namely:

- reference to terms in the glossary must now be explicit (:term:)
- method overloads must not be declared as a separate method or must
  use :noindex:
- 2 cases where `` should have been used instead of `
2020-06-05 21:42:17 +10:00
David Lechner eeca2c3cbe github: Add GitHub action to build docs.
This builds docs, but only on pull requests that change a file in the
docs/ directory.
2020-06-05 21:42:10 +10:00
Damien George 621f40b12c esp32/mpthreadport: Fix calculation of thread stack size.
With this commit the code should work correctly regardless of the size of
StackType_t (it's actually 1 byte in size for the esp32's custom FreeRTOS).

Fixes issue #6072.
2020-06-05 20:55:37 +10:00
Damien George 596fb73927 qemu-arm: Support building in debug mode with DEBUG=1.
Fixes issue #6095.
2020-06-05 20:52:10 +10:00
jxltom 834b482e67 examples/bluetooth: Fix incorrect value of BR/EDR flag in advertising.
According to Supplement to the Bluetooth Core Specification v8 Part A
1.3.1, to support BR/EDR the code should set the fifth bit (Simultaneous LE
and BR/EDR to Same Device Capable (Controller)) and fourth bit
(Simultaneous LE and BR/EDR to Same Device Capable (Host)) of the flag.
2020-06-05 14:24:09 +10:00
Jim Mussared 8b7ae4e099 extmod/modbluetooth: Support bigger characteristic values.
The ring buffer previously used a single unsigned byte field to save the
length, meaning that it would overflow for large characteristic value
responses.

With this commit it now use a 16-bit length instead and has code to
explicitly truncate at UINT16_MAX (although this should be impossible to
achieve in practice).
2020-06-05 14:11:46 +10:00
Jim Mussared 1cad63c0bc extmod/modbluetooth: Ensure status=0 always on success.
This commit makes sure that all discovery complete and read/write status
events set the status to zero on success.

The status value will be implementation-dependent on non-success cases.
2020-06-05 14:11:04 +10:00
Jim Mussared 9708fe8788 docs/library: Update ubluetooth for new events and discover by uuid. 2020-06-05 14:10:13 +10:00
Jim Mussared 9902ce12eb tests/multi_bluetooth: Update to work with new BLE events.
Updates the tests to use non-bitmask events, event renames, as well as some
of the new completion events to improve reliability of the tests.
2020-06-05 14:08:47 +10:00
Jim Mussared c07ea3e4c2 extmod/modbluetooth: Implement read done event.
On btstack there's no status associated with the read result, it comes
through as a separate event.  This allows you to detect read failures or
timeouts.
2020-06-05 14:08:15 +10:00
Jim Mussared 919d640aec extmod/modbluetooth: Allow discovery of svc/char by uuid.
In most situations this is a more efficient way of going straight to the
service and characteristic you need.
2020-06-05 14:08:07 +10:00
Jim Mussared 6a3c89d584 extmod/modbluetooth: Add discover complete events for svc/char/desc.
Without this it's difficult to implement a state machine correctly if the
desired services are not found.
2020-06-05 14:07:52 +10:00
Jim Mussared e6881f0829 extmod/modbluetooth: Make modbluetooth event not a bitfield.
There doesn't appear to be any use for only triggering on specific events,
so it's just easier to number them sequentially.  This makes them smaller
values so they take up only 1 byte in the ringbuf, only 1 byte for the
opcode in the bytecode, and makes room for more events.

Also add a couple of new event types that need to be implemented (to avoid
re-numbering later).

And rename _COMPLETE and _STATUS to _DONE for consistency.

In the future the "trigger" keyword argument can be reinstated by requiring
the user to compute the bitmask, eg:

    ble.irq(handler, 1 << _IRQ_SCAN_RESULT | 1 << _IRQ_SCAN_DONE)
2020-06-05 14:04:20 +10:00
Philipp Ebensberger 02cc4462b7 mimxrt: Add initial impl of machine.LED class, and basic pin support.
This commit implements an LED class with rudimentary parts of a pin C API
to support it.  The LED class does not yet support setting an intensity.

This LED class is put in the machine module for the time being, until a
better place is found.

One LED is supported on TEENSY40 and MIMXRT1010_EVK boards.
2020-06-05 11:47:48 +10:00
Andrew Leech e54626f4c1 docs/reference: Add note about multiple exceptions when heap is locked. 2020-06-02 15:56:34 +10:00
Damien George 8e591d412a minimal: Make build more flexible and work as 64-bit build.
Changes are:
- string0 is no longer built when building for host as the target, because
  it'll be provided by the system libc and may in some cases clash with the
  system one (eg on OSX).
- mp_int_t/mp_uint_t are defined in terms of intptr_t/uintptr_t to support
  both 32-bit and 64-bit builds.
- Configuration values which are the default in py/mpconfig.h are removed
  from mpconfigport.h to make the configuration a bit more minimal, eg as
  a better starting point for new ports.
2020-06-02 15:43:44 +10:00
Damien George b2030e1661 lib/utils/pyexec: Add missing MP_ERROR_TEXT when compiler disabled. 2020-06-02 15:43:44 +10:00
Damien George 203b10703e py/modbuiltins: Fix getattr to work with class raising AttributeError.
Fixes issue #6089.
2020-06-02 15:42:20 +10:00
stinos da71f55e23 stm32/Makefile: Quote libgcc path so spaces are not an issue.
Fixes #3116.
2020-06-02 14:11:08 +10:00
David Spickett a4086a2f13 qemu-arm/README: Update link to toolchain.
New releases have moved from launchpad to developer.arm.com.
2020-06-02 14:09:56 +10:00
Damien George 246f3f640d stm32/boards/xxx_WB55: Enable pyb.ADC and hardware SPI on WB55 boards.
These features are now supported (although machine.ADC is recommended over
pyb.ADC).
2020-06-02 10:48:49 +10:00
Damien George c8985d52d3 stm32/dma: Add support for DMA on STM32WB, with SPI settings provided. 2020-06-02 10:48:49 +10:00
Damien George 0f7b5cceea stm32/machine_adc: Make setting of ADC1_COMMON->CCR clearer on STM32WB. 2020-06-02 10:48:49 +10:00
Damien George 5210fc51ec stm32/adc: Add support to pyb.ADC for STM32WB MCUs. 2020-06-02 10:48:49 +10:00
Damien George 68d053c66e stm32/modmachine: Allow changing AHB and APB bus frequencies on STM32WB.
For now SYSCLK cannot be changed and must remain at 64MHz.
2020-06-02 10:48:49 +10:00
Damien George 9ae50d22c9 stm32/machine_uart: Allow re-init'ing a static UART object.
Just disallow changing the rxbuf which will be some static RAM (can't free
it and soft-reset would lose any dynamically allocated buffer).
2020-06-01 21:41:54 +10:00
Damien George 88971342b1 stm32/machine_uart: Retain attached-to-repl setting when init'ing UART. 2020-06-01 21:41:50 +10:00
Damien George 22806ed5df extmod/vfs: Retain previous working directory if chdir fails.
Fixes issue #6069.
2020-05-29 23:05:01 +10:00
David Lechner 8f642677f7 tools/codeformat.py: Add verbose option to pass to uncrustify and black.
This adds a new command line option `-v` to `tools/codeformat.py` to enable
verbose printing of all files that are scanned.

Normally `uncrustify` and `black` are called with the `-q` option so
setting verbose suppresses the `-q` option and on `black` also enables the
`-v` option which makes it print out all file names matching the filter
similar to how `uncrustify` does by default.
2020-05-29 22:59:56 +10:00
Joel Stanley 5cfc09ffca travis: For powerpc job, build both UART variants.
The powerpc port can be built with two different UART drivers, so build
both in CI.

The default compiler is now powerpc64le-linux-gnu- so it does not need to
be specified on the command line.
2020-05-29 22:56:31 +10:00
Joel Stanley f03d030080 powerpc/uart: Choose which UART to use at build time, not runtime.
Microwatt may have firmware that places data in r3, which was used to
detect microwatt vs powernv.  This breaks the existing probing of the UART
type in this powerpc port.

Instead build only the appropriate UART into the firmware, selected by
passing the option UART=potato or UART=lpc_serial to the Makefile.

A future enhancement would be to parse the device tree and configure
MicroPython based on the settings.
2020-05-29 22:54:55 +10:00
Thorsten von Eicken 50a7ba2348 esp32/modmachine: Fix machine.reset_cause to use IDF's esp_reset_reason.
The code previously called rtc_get_reset_reason which is a "raw" reset
cause.  The ESP-IDF massages that for the proper reset cause available from
esp_reset_reason.

Fixes issue #5134.
2020-05-29 22:27:53 +10:00
cccc 1662a0b06f esp32/machine_sdcard: Add "freq" keyword arg to SDCard constructor.
To allow high speed access.
2020-05-28 12:19:04 +10:00
David Lechner 2d1fef7096 tools/codeformat.py: Use -q option on uncrustify to make output quiet.
This suppresses the Parsing: <file> as language C lines.  This makes
parsing run a bit faster and on CI it makes for less scrolling through logs
(and black already uses the -q option).
2020-05-28 10:08:38 +10:00
David Lechner 093fd80760 py/modsys: Use consistent naming pattern for module-level const objects.
This renames a few identifiers to follow the usual naming convention of
mp_<module>_<name>.  This makes them easier to find, e.g. when grep'ing.
2020-05-28 10:02:14 +10:00
stijn 9523ca92e0 windows: Make appveyor.yml self-contained.
Add configuration which otherwise has to be set via the UI so the file is
more self-contained, and remove configuration which is not needed because
it's the same as the default.  The major change here is that for a while
now Appveyor has been using Visual Studio 2015 by default while we still
want to support 2013.
2020-05-28 09:56:35 +10:00
stijn 97ccde0c43 py/ringbuf: Fix compilation with msvc.
Older versions do not have "inline" so fetch the definition from
mpconfigport.h.
2020-05-28 09:56:18 +10:00
stijn 81db22f693 py/modmath: Work around msvc float bugs in atan2, fmod and modf.
Older implementations deal with infinity/negative zero incorrectly.  This
commit adds generic fixes that can be enabled by any port that needs them,
along with new tests cases.
2020-05-28 09:54:54 +10:00
Damien George a902b69dd5 py/py.mk: Use additional CFLAGS to compile string0.c.
Otherwise functions like memset might get optimised to call themselves (eg
with gcc 10).  And provide CFLAGS_BUILTIN so these options can be changed
by a port if needed.

Fixes issue #6053.
2020-05-27 23:10:23 +10:00
Damien George 4bbba3060d lib/utils: Lock the scheduler when executing hard callback functions.
Otherwise scheduled functions may execute during the hard callback and then
fail if they try to allocate heap memory.
2020-05-27 17:53:31 +10:00
Joel Stanley d6803067c0 travis: Set build name so it appears in the web interfaces.
The env NAME="foo" syntax doesn't appear to set the name in the Travis web
interface.  Instead use the syntax from the docs:

 https://docs.travis-ci.com/user/build-stages/#naming-your-jobs-within-build-stages
2020-05-27 17:06:10 +10:00
Joel Stanley a9d96499b8 travis: Run apt commands once, to slightly speed up the CI. 2020-05-27 17:05:50 +10:00
Joel Stanley b65482ffa8 powerpc: Set better default compiler.
Most developers use a compiler which is called powerpc64le-linux-gnu-gcc.
2020-05-27 17:02:04 +10:00
Joel Stanley 25bc42e754 powerpc: Fix Makefile rule when linking.
The linker script was included in the "$^" inputs, causing the build to
fail:

 LINK build/firmware.elf
 powerpc64le-linux-gnu-ld: error: linker script file 'powerpc.lds' appears multiple times

As a fix the linker script is left as a dependency of the elf, but only the
object files are linked.
2020-05-27 17:00:44 +10:00
Albort Xue b3bc9808f2 mimxrt/boards: Add MIMXRT1060_EVK board. 2020-05-27 16:49:52 +10:00
Olivier Ortigues e32302c1a6 esp8266/esppwm: Fix PWM glitch when setting duty on different channel.
The PWM driver uses a double buffer for the PWM timing array, one in
current use and the other one to update when changing duty parameters.
The issue was that once the duty parameters were changed the updated buffer
was applied immediately without synchronising to the start of the PWM
period.  By moving the buffer toggling/swapping to the interrupt when the
cycle is done there are no more glitches.
2020-05-27 16:15:28 +10:00
Damien George cae77daf00 docs/develop: Fix module/source name in Makefile of native example. 2020-05-16 15:00:46 +10:00
Yu-Ming Chang dd8db974d7 unix/main: Enter REPL when inspect active, even with stdin redirected.
This is how CPython behaves.
2020-05-16 14:13:15 +10:00
Jim Mussared cd9a8c1742 nrf: Add openocd as a supported flasher.
Tested with the Particle Debugger on a Xenon.
2020-05-15 15:06:02 +10:00
Jim Mussared 1f1b78752f travis: Build more boards as part of nrf job.
Specifically:
- pca10040: It was already the default.
- microbit: It uses nRF51, has a Cortex-M0, and has additional libraries.
- pca10056: It has USB CDC.
2020-05-15 15:06:02 +10:00
Jim Mussared e7f8c7d9a3 nrf: Update to work with nrfx v2.0.0, to match TinyUSB.
Commit 6cea369b89 updated the TinyUSB
submodule to a version based on nrfx v2.0.0.  This commit updates the nrf
port to work with the latest TinyUSB and nrfx v2.0.0.
2020-05-15 15:06:02 +10:00
Damien George 9ee5aff334 lib/nrfx: Upgrade to nrfx v2.0.0. 2020-05-15 15:06:02 +10:00
Damien George 8f348778e1 nrf/mphalport: Remove need for "syntax unified" in mp_hal_delay_us.
Because it can confuse older versions of gcc.  Instead use the correct
instruction for Thumb vs Thumb-2 (sub vs subs) so the assembler emits the
2-byte instruction.

Related to commit 1aa9ff9141.
2020-05-15 15:04:49 +10:00
Damien George eb5e9c00f8 nrf/Makefile: Don't use -fno-builtin for Cortex-M0 builds.
So that error string compression is optimised correctly (it needs strcmp to
be optimised away by the compiler).
2020-05-15 13:39:12 +10:00
Damien George 7dffbfd22a extmod/vfs_lfsx: Fix import_stat so it takes into account current dir.
CPython semantics require searching the current directory if the import is
not absolute (when "" is in sys.path).

Fixes issue #6037.
2020-05-15 11:31:32 +10:00
Thomas Roberts 463c0fb2f4 stm32/boards: Add board config for Nucleo-F412ZG development board. 2020-05-15 10:48:48 +10:00
Thomas Roberts d7399679de stm32: Add support for F412 MCUs. 2020-05-15 10:08:30 +10:00
Rafael Römhild 8f3167a962 esp8266/boards: Allow configuring btree/FAT/LFS2 support when building.
Prior to e0905e85a7 it was possible to
disable btree support on build.  This patch allows to configure btree
support on make again and also the two new introduced options for FAT and
LFS2 filesystems.
2020-05-14 22:16:01 +10:00
Damien George 801f7dca78 py/nativeglue.h: Rename "setjmp" entry to "setjmp_" to avoid any clash.
Because some compilers may define setjmp to something.

Fixes issue #6032.
2020-05-14 21:48:05 +10:00
Thomas Friebel 18fb5b4432 extmod/nimble: Make error code mapping default to MP_EIO.
Before this change, any NimBLE error that does not appear in the
ble_hs_err_to_errno_table maps to return code 0, meaning success.  If we
miss adding an error code to the table we end up returning success in case
of failure.

Instead, handle the zero case explicitly and default to MP_EIO.  This
allows removing the now-redundant MP_EIO entries from the mapping.
2020-05-11 22:31:30 +10:00
Hannah Suarez/hcs0 c9611b280f README: Change --help option to -h to match micropython executable.
The behaviour was changed in 83439e38fc
2020-05-11 21:57:38 +10:00
Damien George 3b6c9119eb extmod/modbluetooth: Add support for changing the GAP device name.
This commit allows the user to set/get the GAP device name used by service
0x1800, characteristic 0x2a00.  The usage is:

    BLE.config(gap_name="myname")
    print(BLE.config("gap_name"))

As part of this change the compile-time setting
MICROPY_PY_BLUETOOTH_DEFAULT_NAME is renamed to
MICROPY_PY_BLUETOOTH_DEFAULT_GAP_NAME to emphasise its link to GAP and this
new "gap_name" config value.  And the default value of this for the NimBLE
bindings is changed from "PYBD" to "MPY NIMBLE" to be more generic.
2020-05-11 21:30:41 +10:00
Thorsten von Eicken f385b7bfa8 stm32/README: Reorg DFU flashing instructions with addition for PYBD. 2020-05-11 21:23:41 +10:00
Thorsten von Eicken ab4e197707 esp32/modsocket: Fix getaddrinfo to raise on error.
This commit fixes the behaviour of socket.getaddrinfo on the ESP32 so it
raises an OSError when the name resolution fails instead of returning a []
or a resolution for 0.0.0.0.

Tests are added (generic and ESP32-specific) to verify behaviour consistent
with CPython, modulo the different types of exceptions per MicroPython
documentation.
2020-05-09 16:43:48 +10:00
Damien George adb6733022 tests/run-tests: Skip REPL feature checks when running via pyboard.py. 2020-05-09 16:20:40 +10:00
Damien George 172fc040aa py/parse: Make mp_parse_node_extract_list return size_t instead of int.
Because this function can only return non-negative values, and having the
correct return type gives more information to the caller.
2020-05-09 00:55:44 +10:00
Damien George 035059eaf5 tests/run-multitests.py: Add TRACE banner and move TEST output to end.
To make it easier to understand the output when both -s and -t are used.
2020-05-09 00:06:06 +10:00
Damien George 67fca2b715 esp8266/uart: Move a few functions from iRAM to iROM.
They call functions in iROM so do not need to be in iRAM.
2020-05-08 23:44:57 +10:00
Damien George f2218c2fbd esp8266/esp_mphal: Move most functions in esp_mphal.c from iRAM to iROM.
The ones that are moved out of iRAM should not need to be there, because
either they call functions in iROM (eg mp_hal_stdout_tx_str), or they are
only ever called from a function in iROM and not from an interrupt (eg
ets_esf_free_bufs).

This frees up about 800 bytes of iRAM.
2020-05-08 23:44:57 +10:00
Damien George caa7725642 esp8266/boards: Move py/pairheap.c code from iRAM to iROM.
It doesn't need to be in iRAM.
2020-05-08 23:40:22 +10:00
Damien George e12de1fd9d esp8266: Clean up Pin intr handler by moving all code to machine_pin.c.
The macro MP_FASTCODE is used to explicitly place required functions in
iRAM, instead of needing a separate .c file.
2020-05-08 23:40:22 +10:00
Damien George f792e6c283 py/scheduler: Convert mp_sched_full and mp_sched_num_pending to macros.
So they are guaranteed to be inlined within functions like
mp_sched_schedule which may be located in a special memory region.
2020-05-08 23:20:45 +10:00
robert 0f83ef395c extmod/vfs_lfsx: Fix rename to respect cur dir for new path.
If the new name start with '/', cur_dir is not prepened any more, so that
the current working directory is respected.  And extend the test cases for
rename to cover this functionality.
2020-05-08 21:54:04 +10:00
robert d3ea28d04a extmod/vfs_lfsx: Normalize path name in chdir.
This change scans for '.', '..' and multiple '/' and normalizes the new
path name.  If the resulting path does not exist, an error is raised.
Non-existing interim path elements are ignored if they are removed during
normalization.
2020-05-08 21:52:15 +10:00
robert a5ea4b9f3f extmod/vfs_lfsx: Fix path handling in uos.stat() to consider cur dir.
This fixes the bug, that stat(filename) would not consider the current
working directory.  So if e.g. the cwd is "lib", then stat("main.py") would
return the info for "/main.py" instead of "/lib/main.py".
2020-05-08 21:37:51 +10:00
Damien George 037c83b0ed tests/multi_bluetooth: Fix typo printing wrong IRQ type. 2020-05-08 13:23:45 +10:00
Damien George e2def200bf stm32/boards/PYBD_SF2: Put BTstack library in external QSPI XIP flash.
In the same way the nimble stack is put there.
2020-05-05 20:21:15 +10:00
Maureen Helm 25434e976b zephyr: Use zephyr build system to merge configurations.
The zephyr build system supports merging application-level board
configurations, so there is no need to reproduce this functionality in
MicroPython.

If CONF_FILE is not explicitly set, then the zephyr build system looks for
prj.conf in the application directory.  Therefore we rename the MicroPython
prj_base.conf to prj.conf.

Furthermore, if the zephyr build system finds boards/$(BOARD).conf in the
application directory, it merges that configuration with prj.conf.
Therefore we rename all the MicroPython board .conf files and move them
into a boards/ directory.

The minimal configuration, prj_minimal.conf, is left in the application
directory because it is used as an explicitly set CONF_FILE in
make-minimal.
2020-05-05 00:48:44 +10:00
yangfl 138a28dc07 tests/thread/thread_stacksize1.py: Increase stack size for CPython.
On arm64 with CPython:

  >>> _thread.stack_size(32*1024)
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  ValueError: size not valid: 32768 bytes

So increase the CPython value in the test to 512k so it runs on more
systems (on modern Linux the default stack size is usually 8MB).
2020-05-05 00:43:24 +10:00
Damien George 4ede703687 py/parse: Support constant folding of power operator for integers.
Constant expression like "2 ** 3" will now be folded, and the special form
"X = const(2 ** 3)" will now compile because the argument to the const is
now a constant.

Fixes issue #5865.
2020-05-03 16:23:19 +10:00
Thorsten von Eicken 40e9227733 esp32/partitions: Update comments in files regarding offset. 2020-05-03 15:01:26 +10:00
Thorsten von Eicken 952ff8a8ea esp32: Improve support for OTA updates.
This commit adds several small items to improve the support for OTA
updates on an esp32:

- a partition table for 4MB flash modules that has two OTA partitions ready
  to go to do updates
- a GENERIC_OTA board that uses that partition table and that enables
  automatic roll-back in the bootloader
- a new esp32.Partition.mark_app_valid_cancel_rollback() class-method to
  signal that the boot is successful and should not be rolled back at the
  next reset
- an automated test for doing an OTA update
- documentation updates
2020-05-03 15:00:45 +10:00
Thorsten von Eicken 7d97d241e8 docs/library: Fix docs for machine.WDT to specify millisecond timeout. 2020-05-02 22:55:48 +10:00
Jim Mussared 309c19d39b tests/cpydiff: Add cpydiff test for __all__ used in imported package. 2020-05-02 17:41:04 +10:00
Damien George 73c58150f5 extmod/modbtree: Retain reference to underlying stream so it's not GC'd.
For ports that have a system malloc which is not garbage collected (eg
unix, esp32), the stream object for the DB must be retained separately to
prevent it from being reclaimed by the MicroPython GC (because the
berkeley-db library uses malloc to allocate the DB structure which stores
the only reference to the stream).

Although in some cases the user code will explicitly retain a reference to
the underlying stream because it needs to call close() on it, this is not
always the case, eg in cases where the DB is intended to live forever.

Fixes issue #5940.
2020-05-02 16:08:04 +10:00
Damien George 391927c126 docs/library: Note that machine.Pin.irq's hard arg may not be supported. 2020-04-30 23:50:53 +10:00
Damien George 419d1aa617 esp8266/mpconfigport.h: Add definitions for BEGIN/END_ATOMIC_SECTION.
These are needed to ensure correct operation of the MicroPython scheduler.
2020-04-30 23:47:11 +10:00
Damien George 0bd58a5613 esp8266/machine_pin: Move pin_intr_handler to iRAM, de-support hard IRQ.
GPIO interrupts can occur when the flash ROM cache is in use and so the
GPIO interrupt handler must be in iRAM.  This commit moves the handler to
iRAM, and also moves mp_sched_schedule to iRAM which is called by
pin_intr_handler.

As part of this fix the Pin class can no longer support hard=True in the
Pin.irq() method, because the VM and runtime are too big to put in iRAM.

Fixes #5714.
2020-04-30 23:47:11 +10:00
Damien George 544c308c18 py/scheduler: Add option to wrap mp_sched_schedule in arbitrary attr.
So ports can put it in a special memory section if needed.
2020-04-30 23:47:11 +10:00
Damien George 4371c971e3 travis: Make sure upstream/master exists when computing size-diff check.
Explicitly add the repository as upstream and fetch the master commit.
This makes this bare-arm/minimal job more robust when finding the
fork-point of a PR relative to upstream/master (especially for forks of
this repo).
2020-04-30 23:04:39 +10:00
Damien George 5c8bf12acf all: Fix auto-enable of MICROPY_GCREGS_SETJMP to select GC behaviour.
Only enable it if MICROPY_GCREGS_SETJMP is not already defined, and no
supported architecture is defined.
2020-04-30 16:49:42 +10:00
Jim Mussared 710426024a all: Factor gchelper code to one place and use it for unix & ARM ports.
No functionality change is intended with this commit, it just consolidates
the separate implementations of GC helper code to the lib/utils/ directory
as a general set of helper functions useful for any port.  This reduces
duplication of code, and makes it easier for future ports or embedders to
get the GC implementation correct.

Ports should now link against gchelper_native.c and either gchelper_m0.s or
gchelper_m3.s (currently only Cortex-M is supported but other architectures
can follow), or use the fallback gchelper_generic.c which will work on
x86/x64/ARM.

The gc_helper_get_sp function from gchelper_m3.s is not really GC related
and was only used by cc3200, so it has been moved to that port and renamed
to cortex_m3_get_sp.
2020-04-29 23:45:19 +10:00
Jim Mussared 2e3c42775a unix: Add btstack to the unix submodules list.
But only when bluetooth is enabled, i.e. if building the dev or coverage
variants, and we have libusb available.

Update travis to match, i.e. specify the variant when doing
`make submodules`.
2020-04-29 16:54:12 +10:00
Jim Mussared ebfd9ff2e6 extmod/modbluetooth: Fix sign compare and unused variable warnings. 2020-04-29 16:54:12 +10:00
Jim Mussared c37fd78071 lib/btstack: Update to c8b9823 for USB HCI reset timeout fix. 2020-04-29 16:54:12 +10:00
Jim Mussared af226199ea unix: Enable modbluetooth on the "dev" and "coverage" variants.
And MICROPY_PY_URANDOM_EXTRA_FUNCS is enabled on "dev" so tha the Bluetooth
examples all run.
2020-04-29 16:53:13 +10:00
Jim Mussared 59a7865a7d tests/run-multitests.py: Add shortcuts for local Python instances.
One can now use `-i micropython` and `-i cpython` to add instances using
the `MICROPYTHON` and `CPYTHON3` variables (which can be overridden by env
vars).
2020-04-29 16:45:46 +10:00
Jim Mussared 9b06efb943 tests/multi_bluetooth/ble_gap_advertise: Fix bytes/str compare warning. 2020-04-29 16:45:46 +10:00
Jim Mussared f588138bbe tests/run-multitests.py: Allow filtering out lines from stdout.
And use this new feature to filter out certain lines in the Bluetooth
multitests.
2020-04-29 16:45:46 +10:00
Jim Mussared 7563d58210 unix: Add support for modbluetooth and BLE using btstack.
This commit adds full support to the unix port for Bluetooth using the
common extmod/modbluetooth Python bindings.  This uses the libusb HCI
transport, which supports many common USB BT adaptors.
2020-04-29 16:45:46 +10:00
Jim Mussared c987adb9e9 extmod/btstack: Implement more robust init/deinit sequencing. 2020-04-29 16:45:46 +10:00
Jim Mussared 50e44f477b stm32/main: Peform a clean shutdown of btstack on soft reset.
Not just NimBLE.
2020-04-29 16:45:46 +10:00
Jim Mussared 8119ec0765 extmod/modbluetooth: Don't hold atomic section during mp_sched_schedule.
Because, for example, on unix the atomic section isn't re-entrant, and
mp_sched_schedule() will try to re-acquire the atomic section.
2020-04-29 16:45:40 +10:00
Jim Mussared 0da47ecc93 stm32/Makefile: Rename SRC_LIB to LIB_SRC_C to match other ports. 2020-04-29 16:38:18 +10:00
Jim Mussared cb5994d96e unix/modmachine: Add machine.idle(), implemented using sched_yield.
Also add a definition of MICROPY_EVENT_POLL_HOOK so the unix port can build
against modules that require this.
2020-04-29 16:37:46 +10:00
Damien George 4fa6d939d6 tests/extmod: Add btree test for errors raised by btree DB library.
This test now passes given the previous two commits.
2020-04-27 23:59:09 +10:00
Damien George bd6ca15444 py/modio: Allow uio.IOBase streams to return errno for read/write error.
This allows user code that inherits from uio.IOBase to return an errno
error code from the user readinto/write function, by returning a negative
value.  Eg returning -123 means an errno of 123.  This is already how the
custom ioctl works.
2020-04-27 23:58:46 +10:00
Damien George e08ca78f40 py/stream: Remove mp_stream_errno and use system errno instead.
This change is made for two reasons:

1. A 3rd-party library (eg berkeley-db-1.xx, axtls) may use the system
   provided errno for certain errors, and yet MicroPython stream objects
   that it calls will be using the internal mp_stream_errno.  So if the
   library returns an error it is not known whether the corresponding errno
   code is stored in the system errno or mp_stream_errno.  Using the system
   errno in all cases (eg in the mp_stream_posix_XXX wrappers) fixes this
   ambiguity.

2. For systems that have threading the system-provided errno should always
   be used because the errno value is thread-local.

For systems that do not have an errno, the new lib/embed/__errno.c file is
provided.
2020-04-27 23:58:46 +10:00
Jim Mussared 57fce3bdb2 py/objdict: Fix popitem for ordered dicts.
The popitem method wasn't implemented for ordered dicts and would result in
an invalid state.

Fixes issue #5956.
2020-04-27 23:53:17 +10:00
Jim Mussared 347c8917dc extmod/nimble: Update to work with NimBLE 1.3. 2020-04-27 22:51:10 +10:00
Jim Mussared 0dceab0ddf lib/mynewt-nimble: Update submodule to NimBLE release 1.3.0. 2020-04-27 22:50:42 +10:00
Krsna Mahapatra 0bfd55afbe README: Fix small typo, dfeault -> default. 2020-04-23 11:27:38 +10:00
stijn 84fa3312cf all: Format code to add space after C++-style comment start.
Note: the uncrustify configuration is explicitly set to 'add' instead of
'force' in order not to alter the comments which use extra spaces after //
as a means of indenting text for clarity.
2020-04-23 11:24:25 +10:00
stijn d6243568a0 all: Remove commented-out include statements. 2020-04-23 11:24:15 +10:00
Thorsten von Eicken 1ae7e0e561 esp32: Consolidate check_esp_err functions and add IDF error string.
This commit consolidates a number of check_esp_err functions that check
whether an ESP-IDF return code is OK and raises an exception if not.  The
exception raised is an OSError with the error code as the first argument
(negative if it's ESP-IDF specific) and the ESP-IDF error string as the
second argument.

This commit also fixes esp32.Partition.set_boot to use check_esp_err, and
uses that function for a unit test.
2020-04-23 10:59:07 +10:00
Thorsten von Eicken a177831c46 esp32/modesp32: Add idf_heap_info(capabilities) to esp32 module.
This commit adds an idf_heap_info(capabilities) method to the esp32 module
which returns info about the ESP-IDF heaps.  It's useful to get a bit of a
picture of what's going on when code fails because ESP-IDF can't allocate
memory anymore.  Includes documentation and a test.
2020-04-23 00:02:11 +10:00
Damien George 6a1c7ea815 README: Update Travis CI links to point to travis-ci.com.
MicroPython now build at the .com rather than the .org.
2020-04-22 15:19:13 +10:00
Damien George 6e2871df59 tools/check_code_size.sh: Remove unused script.
It's now replaced by tools/metrics.py.
2020-04-22 14:07:56 +10:00
Damien George 8267f0866c travis: Use tools/metrics.py to compute size diff of minimal ports.
This is to make the Travis CI size check more robust, by not relying on the
saved firmware from a previous build (which may use a different compiler,
environment, etc) but rather compile both master and the PR and diff them.

This size check now checks both bare-arm and minimal x86-32 builds (before
it just checked minimal Cortex-M build).
2020-04-22 14:04:01 +10:00
Damien George 17dc86369f tools/metrics.py: Use OrderedDict when reading build log.
So that the output (eg of the diff command) always has the lines in the
same order.
2020-04-22 14:03:26 +10:00
Damien George 1cc24cd39a tools/metrics.py: Don't build mpy-cross if not needed by any ports.
To save build time.
2020-04-22 14:03:07 +10:00
Damien George a4423570e2 tools/metrics.py: Add option to diff to error if delta above threshold.
Useful for things like CI where the size check is automated.
2020-04-22 14:02:14 +10:00
Damien George 388d419ba3 py/makecompresseddata.py: Make compression deterministic.
Error string compression is not deterministic in certain cases: it depends
on the Python version (whether dicts are ordered by default or not) and
probably also the order files are passed to this script, leading to a
difference in which words are included in the top 128 most common.

The changes in this commit use OrderedDict to keep parsed lines in a known
order, and, when computing how many bytes are saved by a given word, it
uses the word itself to break ties (which would otherwise be "random").
2020-04-20 10:32:49 +10:00
Thomas Friebel 1b1ceb67b2 docs/library: Document that char_data/notify_data are also references. 2020-04-19 00:18:14 +10:00
Andrew Leech 8ee2e1fdbc stm32/mboot: Expose custom DFU USB VID/PID values at makefile level.
In mboot, the ability to override the USB vendor/product id's was added
back in 5688c9ba09.  However, when the main
firmware is turned into a DFU file the default VID/PID are used there.
pydfu.py doesn't care about this but dfu-util does and prevents its use
when the VID/PID don't match.

This commit exposes BOOTLOADER_DFU_USB_VID/PID as make variables, for use
on either command line or mpconfigboard.mk, to set VID/PID in both mboot
and DFU files.
2020-04-18 23:02:00 +10:00
stijn 30840ebc99 all: Enable extra conversion warnings where applicable.
Add -Wdouble-promotion and -Wfloat-conversion for most ports to ban out
implicit floating point conversions, and add extra Travis builds using
MICROPY_FLOAT_IMPL_FLOAT to uncover warnings which weren't found
previously.  For the unix port -Wsign-comparison is added as well but only
there since only clang supports this but gcc doesn't.
2020-04-18 22:42:28 +10:00
stijn f31f9a8b70 py/objint: Do not use fpclassify.
For combinations of certain versions of glibc and gcc the definition of
fpclassify always takes float as argument instead of adapting itself to
float/double/long double as required by the C99 standard.  At the time of
writing this happens for instance for glibc 2.27 with gcc 7.5.0 when
compiled with -Os and glibc 3.0.7 with gcc 9.3.0.  When calling fpclassify
with double as argument, as in objint.c, this results in an implicit
narrowing conversion which is not really correct plus results in a warning
when compiled with -Wfloat-conversion.  So fix this by spelling out the
logic manually.
2020-04-18 22:42:24 +10:00
stijn 70affd9ba2 all: Fix implicit floating point to integer conversions.
These are found when building with -Wfloat-conversion.
2020-04-18 22:42:24 +10:00
stijn bcf01d1686 all: Fix implicit conversion from double to float.
These are found when building with -Wfloat-conversion.
2020-04-18 22:42:24 +10:00
stijn dc4d119d3d py/objarray: Fix sign mismatch in comparison.
Found when compiling with clang and -Wsign-compare.
2020-04-18 22:42:19 +10:00
stijn 7fb9edf436 tests/float: Fix cmath_fun_special for MICROPY_FLOAT_IMPL_FLOAT.
When the unix and windows ports use MICROPY_FLOAT_IMPL_FLOAT instead of
MICROPY_FLOAT_IMPL_DOUBLE, the test output has for example
complex(-0.15052, 0.34109) instead of the expected
complex(-0.15051, 0.34109).

Use one decimal place less for the output printing to fix this.
2020-04-18 22:36:49 +10:00
stijn 0ba68f8a1d all: Fix implicit floating point promotion.
Initially some of these were found building the unix coverage variant on
MacOS because that build uses clang and has -Wdouble-promotion enabled, and
clang performs more vigorous promotion checks than gcc.  Additionally the
codebase has been compiled with clang and msvc (the latter with warning
level 3), and with MICROPY_FLOAT_IMPL_FLOAT to find the rest of the
conversions.

Fixes are implemented either as explicit casts, or by using the correct
type, or by using one of the utility functions to handle floating point
casting; these have been moved from nativeglue.c to the public API.
2020-04-18 22:36:14 +10:00
stijn b909e8b2dd Revert "all: Fix implicit casts of float/double, and signed comparison."
This reverts commit a2110bd3fc.  There's
nothing inherently wrong with it, but upcoming commits will apply similar
fixes in a slightly different way.
2020-04-18 22:36:06 +10:00
stijn 4677315a01 travis: Finish jobs early after test failure.
For jobs which run tests multiple times terminate after the first run fails
otherwise the next test run overwrites the previous results, making
--print-failures useless.
2020-04-18 22:35:56 +10:00
stijn 91a6ddc78a travis: Decrease build duration by starting OSX build early.
Looking at the recent build history the time it takes just to complete the
OSX build is already 12 minutes so make it start early, which brings down
the total build time from about 20 minutes to 14 minutes.
2020-04-18 22:35:44 +10:00
Martin Fischer 28833690bb stm32/mboot/README: Clarify that mboot can access FAT formatted FS only. 2020-04-16 16:28:07 +10:00
Martin Fischer 7942d0b688 stm32/storage: Fix start address of second, internal block device. 2020-04-16 16:25:20 +10:00
David Lechner 6943fb60fe mpy-cross/main: Print uncaught nlr jump to stderr.
This is to be consistent with the same change in the unix port,
4ab8bee82f.
2020-04-16 16:22:25 +10:00
David Lechner 803e5eadea mpy-cross/main: Fix stderr_print_strn parameter type.
Change mp_uint_t to size_t to match the mp_print_strn_t function prototype.
This fixes a compiler warning when mp_uint_t and size_t are not the same
size.
2020-04-16 16:18:13 +10:00
Damien George f534b99765 esp32: Update to ESP IDF v3.3.2. 2020-04-14 23:30:03 +10:00
Damien George 2725a79192 py: Always give noop defines when MICROPY_ROM_TEXT_COMPRESSION disabled.
This commit provides a typedef for mp_rom_error_text_t, and a macro define
for MP_COMPRESSED_ROM_TEXT, when MICROPY_ROM_TEXT_COMPRESSION is disabled.
This simplifies the configuration (it no longer has a special case for
MICROPY_ENABLE_DYNRUNTIME) and makes it work for other cases that don't use
compression (eg examples/embedding).  This commit also ensures
MICROPY_ROM_TEXT_COMPRESSION is defined during qstr processing.
2020-04-14 22:13:11 +10:00
Damien George 5f0661b4fe extmod/uasyncio: Change cannot to can't in error message, and test exp.
Follow up to 8e048d2548 which missed these.
2020-04-14 21:51:25 +10:00
Romain Goyet bd63c26dd5 py/scope: Add assert to check that low numbered qstrs do fit in uint8_t. 2020-04-13 22:27:27 +10:00
Damien George 7654907e1e py/makecompresseddata.py: Don't prefix str with mark if not compressed. 2020-04-13 22:21:57 +10:00
Damien George 8e048d2548 all: Clean up error strings to use lowercase and change cannot to can't.
Now that error string compression is supported it's more important to have
consistent error string formatting (eg all lowercase English words,
consistent contractions).  This commit cleans up some of the strings to
make them more consistent.
2020-04-13 22:19:37 +10:00
Damien George db137e70dc extmod/uasyncio: Add Loop.new_event_loop method.
This commit adds Loop.new_event_loop() which is used to reset the singleton
event loop.  This functionality is put here instead of in Loop.close() to
make it possible to write code that is compatible with CPython.
2020-04-13 22:16:52 +10:00
David Lechner 1bbc15dd15 unix/Makefile: Fix regression using install on non-GNU systems.
This was fixed previously in 31fc81d3b8 but
regressed in 4af79e7694.

Fixes #5885.
2020-04-13 22:11:36 +10:00
Jim Mussared 8470cd0be9 py/scheduler: Add assert that scheduler is locked when unlocking.
And add a test that shows how this can happen when multiple threads are
accessing the scheduler, which fails if atomic sections are not used.
2020-04-13 21:55:47 +10:00
Jim Mussared 243805d776 py/scheduler: Fix race in checking scheduler pending state.
Because the atomic section starts after checking whether the scheduler
state is pending, it's possible it can become a different state by the time
the atomic section starts.

This is especially likely on ports where MICROPY_BEGIN_ATOMIC_SECTION is
implemented with a mutex (i.e. it might block), but the race exists
regardless, i.e. if a context switch occurs between those two lines.
2020-04-13 21:55:47 +10:00
Jim Mussared c2cfbcc8d4 unix: Implement MICROPY_BEGIN/END_ATOMIC_SECTION protection macros.
This macro is used to implement global serialisation, typically by
disabling IRQs.  On the unix port, if threading is enabled, use the
existing thread mutex (that protects the thread list structure) for this
purpose.  Other places in the code (eg the scheduler) assume this macro
will provide serialisation.
2020-04-13 21:44:09 +10:00
Jim Mussared 45cf76465c unix: Fix behaviour of COPT/NDEBUG for unix variants.
Based on eg 1e6fd9f2b4, it's understood that
the intention for unix builds is that regular builds disable assert, but
the coverage build should set -O0 and enable asserts.

It looks like this didn't work (even before variants were introduced, eg at
v1.11) -- coverage always built with -Os and -DNDEBUG.

This commit makes it possible for variants to have finer-grained control
over COPT flags, and enables assert() and -O0 on coverage builds.

Other variants already match the defaults so they have been updated.
2020-04-13 21:20:32 +10:00
stijn f66c989516 tests/run-tests: Make diff tool user configurable. 2020-04-13 16:43:01 +10:00
Thorsten von Eicken e880c8dfaa travis: Split esp32 ESP-IDF v3 and v4 builds to separate jobs.
To make it easier to see what is happening when there is a failure.  This
commit also fixes the ESP-IDF v4 build to use the correct GCC 8.2.0.
2020-04-13 16:06:58 +10:00
Peter Hinch 7409467361 docs/library: Note that uasyncio.wait_for() can raise exception. 2020-04-09 22:11:13 +10:00
Damien George d6f80963df esp32/espneopixel: Use integer arithmetic to compute timing values. 2020-04-09 16:23:34 +10:00
Damien George e292296d52 py/objexcept: Remove optional TimeoutError exception.
TimeoutError was added back in 077812b2ab for
the cc3200 port. In f522849a4d the cc3200
port enabled use of it in the socket module aliased to socket.timeout.  So
it was never added to the builtins.  Then it was replaced by
OSError(ETIMEDOUT) in 047af9b10b.

The esp32 port enables this exception, since the very beginning of that
port, but it could never be accessed because it's not in builtins.

It's being removed: 1) to not encourage its use; 2) because there are a lot
of other OSError subclasses which are not defined at all, and having
TimeoutError is a bit inconsistent.

Note that ports can add anything to the builtins via MICROPY_PORT_BUILTINS.
And they can also define their own exceptions using the
MP_DEFINE_EXCEPTION() macro.
2020-04-09 16:09:38 +10:00
Damien George 4914731e58 py/parse: Remove unnecessary check in const folding for ** operator.
In this part of the code there is no way to get the ** operator, so no need
to check for it.

This commit also adds tests for this, and other related, invalid const
operations.
2020-04-09 16:02:39 +10:00
Damien George a5f2ae10fe tests/extmod: Update littlefs test output to match new library version.
The amount of free space on the VfsLfs2 filesystem after creating a large
file is reduced by 2 blocks in this test.
2020-04-09 15:59:28 +10:00
Damien George 7a07e71915 lib/littlefs: Update littlefs2 to v2.2.0.
At commit a049f1318eecbe502549f9d74a41951985fb956f
2020-04-09 15:59:28 +10:00
stijn bd5633778f travis: Make OSX build work again by not installing pkgconfig.
Recent builds are failing with the following error:

    Error: pkg-config 0.29.2 is already installed

Assuming this will be the case form now on, we don't have to install
pkgconfig anymore.
2020-04-07 13:59:34 +10:00
Damien George c5a21a94f8 extmod/modbluetooth: Provide FLAG_WRITE_NO_RESPONSE for characteristics.
This flag is supported and needs to be set if characteristics are write-
without-response.
2020-04-07 13:46:56 +10:00
Damien George 899e89d4c6 extmod/btstack: Pass through SCAN_RSP events.
The latest version of BTstack has a bug fixed so that it correctly
configures scan parameters if they are set right after activating the
stack.  This means that BLE.gap_scan() will correctly set the scanning to
passive and so SCAN_RSP events are not passed through, so we don't need to
explicitly filter them in our bindings.
2020-04-07 13:46:56 +10:00
Damien George fa285be9d7 lib/btstack: Update to latest master btstack commit. 2020-04-07 13:46:56 +10:00
robert-hh 8680a74595 drivers/display/ssd1306.py: Change the SET_COM_PIN_CFG setting.
Making it more specific to use 0x02 for display with an aspect ratio > 2
(resolutions 96x16 and 128x32) and 0x12 for all other sizes as recommended
by @mcauser.  Tested with a 64x32 display which did not work before.
2020-04-07 13:42:37 +10:00
Jim Mussared 073b9a5eb8 ports: Enable error text compression for various ports, but not all.
Enabled on: bare-arm, minimal, unix coverage/dev/minimal, stm32, esp32,
esp8266, cc3200, teensy, qemu-arm, nrf.  Not enabled on others to be able
to test the code when the feature is disabled (the default case).

Code size change for this commit:

   bare-arm:  -600 -0.906%
minimal x86:  -308 -0.208%
   unix x64:    +0 +0.000%
unix nanbox:    +0 +0.000%
      stm32: -3368 -0.869% PYBV10
     cc3200: -1024 -0.558%
    esp8266: -2512 -0.368% GENERIC
      esp32: -2876 -0.205% GENERIC[incl -3168(data)]
        nrf: -1708 -1.173% pca10040
       samd:    +0 +0.000% ADAFRUIT_ITSYBITSY_M4_EXPRESS
2020-04-05 15:02:06 +10:00
Jim Mussared def76fe4d9 all: Use MP_ERROR_TEXT for all error messages. 2020-04-05 15:02:06 +10:00
Jim Mussared 85858e72df py/objexcept: Allow compression of exception message text.
The decompression of error-strings is only done if the string is accessed
via printing or via er.args.  Tests are added for this feature to ensure
the decompression works.
2020-04-05 15:02:06 +10:00
Jim Mussared 92c83bd16b windows: Update genhdr.targets to match makeqstrdefs.py args. 2020-04-05 14:29:49 +10:00
Jim Mussared 154b4eb354 py: Implement "common word" compression scheme for error messages.
The idea here is that there's a moderate amount of ROM used up by exception
text.  Obviously we try to keep the messages short, and the code can enable
terse errors, but it still adds up.  Listed below is the total string data
size for various ports:

    bare-arm 2860
    minimal 2876
    stm32 8926  (PYBV11)
    cc3200 3751
    esp32 5721

This commit implements compression of these strings.  It takes advantage of
the fact that these strings are all 7-bit ascii and extracts the top 128
frequently used words from the messages and stores them packed (dropping
their null-terminator), then uses (0x80 | index) inside strings to refer to
these common words.  Spaces are automatically added around words, saving
more bytes.  This happens transparently in the build process, mirroring the
steps that are used to generate the QSTR data.  The MP_COMPRESSED_ROM_TEXT
macro wraps any literal string that should compressed, and it's
automatically decompressed in mp_decompress_rom_string.

There are many schemes that could be used for the compression, and some are
included in py/makecompresseddata.py for reference (space, Huffman, ngram,
common word).  Results showed that the common-word compression gets better
results.  This is before counting the increased cost of the Huffman
decoder.  This might be slightly counter-intuitive, but this data is
extremely repetitive at a word-level, and the byte-level entropy coder
can't quite exploit that as efficiently.  Ideally one would combine both
approaches, but for now the common-word approach is the one that is used.

For additional comparison, the size of the raw data compressed with gzip
and zlib is calculated, as a sort of proxy for a lower entropy bound.  With
this scheme we come within 15% on stm32, and 30% on bare-arm (i.e. we use
x% more bytes than the data compressed with gzip -- not counting the code
overhead of a decoder, and how this would be hypothetically implemented).

The feature is disabled by default and can be enabled by setting
MICROPY_ROM_TEXT_COMPRESSION at the Makefile-level.
2020-04-05 14:20:57 +10:00
Jim Mussared 1921224272 extmod/modubinascii: Make code private and module self-contained.
This commit makes all functions and function wrappers in modubinascii.c
STATIC and conditional on the MICROPY_PY_UBINASCII setting, which will
exclude the file from qstr/ compressed-string searching when ubinascii is
not enabled.  The now-unused modubinascii.h header file is also removed.

The cc3200 port is updated accordingly to use this module in its entirety
instead of providing its own top-level definition of ubinascii.

This was originally like this because the cc3200 port has its own ubinascii
module which referenced these methods.  The plan appeared to be that the
API might diverge (e.g. hardware crc), but this should be done similar to
I2C/SPI via a port-specific handler, rather than the port having its own
definition of the module.  Having a centralised module definition also
enforces consistency of the API among ports.
2020-04-05 14:13:53 +10:00
Jim Mussared c34e7b9d4c py/dynruntime.mk: Set MICROPY_ENABLE_DYNRUNTIME instead of per module.
So this setting could be used by other source files if needed.
2020-04-05 14:13:02 +10:00
Jim Mussared 994c1dd57a stm32/Makefile: Add missing ordering dependency on generated headers. 2020-04-05 14:12:59 +10:00
Jim Mussared a9a745e4b4 py: Use preprocessor to detect error reporting level (terse/detailed).
Instead of compiler-level if-logic.  This is necessary to know what error
strings are included in the build at the preprocessor stage, so that string
compression can be implemented.
2020-04-05 14:11:51 +10:00
Damien George 312c699491 esp32: Change from FAT to littlefs v2 as default filesystem.
This commit changes the default filesystem type for esp32 to littlefs v2.
This port already enables both VfsFat and VfsLfs2, so either can be used
for the filesystem, and existing systems that use FAT will still work.
2020-04-04 17:03:30 +11:00
Damien George ad2b3185da travis: Build GENERIC_1M board as part of esp8266 job. 2020-04-04 16:37:51 +11:00
Damien George 497ca99eb2 esp8266/makeimg.py: Print out info about RAM segments when building fw. 2020-04-04 16:30:39 +11:00
Damien George e0905e85a7 esp8266: Change from FAT to littlefs v2 as default filesystem.
This commit changes the esp8266 boards to use littlefs v2 as the
filesystem, rather than FAT.  Since the esp8266 doesn't expose the
filesystem to the PC over USB there's no strong reason to keep it as FAT.
Littlefs is smaller in code size, is more efficient in use of flash to
store data, is resilient over power failure, and using it saves about 4k of
heap RAM, which can now be used for other things.

This is a backwards incompatible change because all existing esp8266 boards
will need to update their filesystem after installing new firmware (eg
backup old files, install firmware, restore files to new filesystem).

As part of this commit the memory layout of the default board (GENERIC) has
changed.  It now allocates all 1M of memory-mapped flash to the firmware,
so the filesystem area starts at the 2M point.  This is done to allow more
frozen bytecode to be stored in the 1M of memory-mapped flash.  This
requires an esp8266 module with 2M or more of flash to work, so a new board
called GENERIC_1M is added which has the old memory-mapping (but still
changed to use littlefs for the filesystem).

In summary there are now 3 esp8266 board definitions:
- GENERIC_512K: for 512k modules, doesn't have a filesystem.
- GENERIC_1M: for 1M modules, 572k for firmware+frozen code, 396k for
  filesystem (littlefs).
- GENERIC: for 2M (or greater) modules, 968k for firmware+frozen code,
  1M+ for filesystem (littlefs), FAT driver also included in firmware for
  use on, eg, external SD cards.
2020-04-04 16:30:36 +11:00
Damien George df156b18e5 docs,tests: Add docs and test for uasyncio custom exc handler methods. 2020-04-04 10:47:48 +11:00
Kevin Köck 15f41c2dbf extmod/uasyncio: Add global exception handling methods.
This commit adds support for global exception handling in uasyncio
according to the CPython error handling:
https://docs.python.org/3/library/asyncio-eventloop.html#error-handling-api

This allows a program to receive exceptions from detached tasks and log
them to an appropriate location, instead of them being printed to the REPL.

The implementation preallocates a context dictionary so in case of an
exception there shouldn't be any RAM allocation.

The approach here is compatible with CPython except that in CPython the
exception handler is called once the task that threw an uncaught exception
is freed, whereas in MicroPython the exception handler is called
immediately when the exception is thrown.
2020-04-04 10:37:00 +11:00
Jim Mussared e97bb58f0e esp32/README.md: Fix typo in venv instructions. 2020-04-02 22:52:48 +11:00
Damien George f97b5395ed extmod/uasyncio: Add StreamReader/StreamWriter as aliases of Stream cls.
To be compatible with CPython.  Fixes issue #5847.
2020-04-02 00:51:00 +11:00
Kevin Köck aca19c25d2 extmod/uasyncio: Add error message to Lock.release's RuntimeError.
Otherwise it can be hard to understand what the error is if a blank
RuntimeError is raised.
2020-04-02 00:40:23 +11:00
Damien George b389bc0afa extmod/uasyncio: Implement Loop.stop() to stop the event loop. 2020-04-02 00:14:18 +11:00
Damien George 711dd392d3 extmod/uasyncio: Don't create a Loop instance in get_event_loop().
The event loop is (for now) just a singleton so make it so that Loop
instances are not needed.
2020-04-01 23:56:31 +11:00
Damien George 8fff0b0acd unix/mpthreadport: Ensure enough thread stack to detect overflow.
Following up to 5e6cee07ab, some systems (eg
FreeBSD 12.0 64-bit) will crash if the stack-overflow margin is too small.
It seems the margin of 8192 bytes (or thereabouts) is always needed.  This
commit adds this much margin if the requested stack size is too small.

Fixes issue #5824.
2020-03-31 09:35:46 +11:00
David Lechner 581f9135a4 tests/run-tests: Add commands to print and clean *.exp,out files.
This adds a couple of commands to the run-tests script to print the diffs
of failed tests and also to clean up the .exp and .out files after failed
tests.  (And a spelling error is fixed while we are touching nearby code.)

Travis is also updated to use these new commands, including using it for
more builds.
2020-03-30 13:25:58 +11:00
David Lechner 6110cd3078 tests/float: Add new lexer test to test parsing of float without prefix.
Since automatically formatting tests with black, we have lost one line of
code coverage.  This adds an explicit test to ensure we are testing the
case that is no longer covered implicitly.
2020-03-30 13:23:05 +11:00
David Lechner 3dc324d3f1 tests: Format all Python code with black, except tests in basics subdir.
This adds the Python files in the tests/ directory to be formatted with
./tools/codeformat.py.  The basics/ subdirectory is excluded for now so we
aren't changing too much at once.

In a few places `# fmt: off`/`# fmt: on` was used where the code had
special formatting for readability or where the test was actually testing
the specific formatting.
2020-03-30 13:21:58 +11:00
David Lechner 488613bca6 tests/micropython/heapalloc_fail_set.py: Remove extra trailing comma.
Unlike tuples, sets do not need trailing comma when there is only one item.
2020-03-30 13:10:24 +11:00
David Lechner 2461349b27 travis: Build full unix coverage build on osx job.
This should help catch more compile errors with the clang compiler.
2020-03-30 12:05:22 +11:00
David Lechner a2110bd3fc all: Fix implicit casts of float/double, and signed comparison.
These were found by buiding the unix coverage variant on macOS (so clang
compiler).  Mostly, these are fixing implicit cast of float/double to
mp_float_t which is one of those two and one mp_int_t to size_t fix for
good measure.
2020-03-30 12:04:21 +11:00
Lars Kellogg-Stedman 3a0f64fc7a tools/pyboard.py: Add -d as an alias for --device. 2020-03-30 11:37:32 +11:00
Lars Kellogg-Stedman 1cf994c48b tools/pyboard.py: Support setting device/baudrate from shell env vars.
Allow defaults for --device and --baudrate to be set in the environment
using PYBOARD_DEVICE and PYBOARD_BAUDRATE.
2020-03-30 11:37:32 +11:00
David Lechner 688323307a tests/basics/dict_pop.py: Remove extra comma in call and fix grammar. 2020-03-28 23:41:08 +11:00
Damien George 1a3e386c67 all: Remove spaces inside and around parenthesis.
Using new options enabled in the uncrustify configuration.
2020-03-28 23:36:44 +11:00
Damien George b56caaf104 travis: Build NUCLEO_L073RZ instead of B_L072Z_LRWAN1 for stm32 job.
The NUCLEO_L073RZ build is slightly bigger and this MCU has only 192k flash
so this helps to catch flash overflow.
2020-03-28 13:56:16 +11:00
Damien George 83461e37d4 stm32/boards: Disable pend_throw, uheapq, utimeq on small-flash boards.
These are mainly used by the previous version of uasyncio which is now
replaced by a newer version, with built-in C module _uasyncio.  Saves about
1300 bytes of flash.
2020-03-28 13:55:59 +11:00
Damien George 09154f585f stm32/mpconfigport.h: Make most extended modules configurable by board. 2020-03-28 13:46:35 +11:00
David Lechner 6c77d5c7cd travis: Use grep with --text on qemu-arm output.
If the .out file contains non-text characters, grep won't show the output
unless we ask nicely.
2020-03-28 13:29:54 +11:00
David Lechner 0608fbff29 travis: Use custom PPA to get pre-built uncrustify.
Use PPA so that we don't have to rebuild uncrustify from source, speeding
up the job.  This also requires not running this test on arm64.
2020-03-28 11:40:47 +11:00
David Lechner 9418611c8a unix: Implement PEP 475 to retry syscalls failing with EINTR.
https://www.python.org/dev/peps/pep-0475/

This implements something similar to PEP 475 on the unix port, and for the
VfsPosix class.

There are a few differences from the CPython implementation:
- Since we call mp_handle_pending() between any ENITR's, additional
  functions could be called if MICROPY_ENABLE_SCHEDULER is enabled, not
  just signal handlers.
- CPython only handles signal on the main thread, so other threads will
  raise InterruptedError instead of retrying.  On MicroPython,
  mp_handle_pending() will currently raise exceptions on any thread.

A new macro MP_HAL_RETRY_SYSCALL is introduced to reduce duplicated code
and ensure that all instances behave the same.  This will also allow other
ports that use POSIX-like system calls (and use, eg, VfsPosix) to provide
their own implementation if needed.
2020-03-27 14:40:46 +11:00
David Lechner 5e6cee07ab unix/mpthreadport: Fix crash when thread stack size <= 8k.
The stack size adjustment for detecting stack overflow in threads was not
taking into account that the requested stack size could be <= 8k, in which
case the subtraction would overflow.  This is fixed in this commit by
ensuring that the adjustment can't be more than the available size.

This fixes the test tests/thread/thread_stacksize1.py which sometimes
crashes with a segmentation fault because of an uncaught NLR jump, which is
a "maximum recursion depth exceeded" exception.

Suggested-by: @dpgeorge
2020-03-27 13:59:18 +11:00
Damien George dbba6b05dc stm32/mpconfigport.h: Remove unused root pointer for BTstack bindings.
This was a cut-and-paste error from the NimBLE bindings.
2020-03-27 00:30:37 +11:00
Damien George ad004db662 esp32: Enable and freeze uasyncio. 2020-03-26 01:25:46 +11:00
Damien George 1d4d688b3b esp8266: Enable and freeze uasyncio.
Only included in GENERIC build.
2020-03-26 01:25:46 +11:00
Damien George 35e2dd0979 stm32: Enable and freeze uasyncio. 2020-03-26 01:25:45 +11:00
Damien George 3b68f36175 extmod/uasyncio: Add manifest.py for freezing uasyncio Py files. 2020-03-26 01:25:45 +11:00
Damien George c99322f8d8 docs/library: Add initial docs for uasyncio module. 2020-03-26 01:25:45 +11:00
Damien George 91dd3948e8 unix: Enable uasyncio C helper module on coverage build. 2020-03-26 01:25:45 +11:00
Damien George bc009fdd62 extmod/uasyncio: Add optional implementation of core uasyncio in C.
Implements Task and TaskQueue classes in C, using a pairing-heap data
structure.  Using this reduces RAM use of each Task, and improves overall
performance of the uasyncio scheduler.
2020-03-26 01:25:45 +11:00
Damien George 081d067662 tests/net_inet: Add uasyncio internet tests. 2020-03-26 01:25:45 +11:00
Damien George 38904b8937 tests/multi_net: Add uasyncio test for TCP server and client.
Includes a test where the (non uasyncio) client does a RST on the
connection, as a simple TCP server/client test where both sides are using
uasyncio, and a test for TCP stream close then write.
2020-03-26 01:25:45 +11:00
Damien George 18fa65e474 tests: Make default MICROPYPATH include extmod to find uasyncio. 2020-03-26 01:25:45 +11:00
Damien George 3667effff1 travis: Exclude some uasyncio tests on OSX. 2020-03-26 01:25:45 +11:00
Damien George 5d09a40df9 tests/run-tests: Skip uasyncio if no async, and skip one test on native. 2020-03-26 01:25:45 +11:00
Damien George c4935f3049 tests/extmod: Add uasyncio tests.
All .exp files are included because they require CPython 3.8 which may not
always be available.
2020-03-26 01:25:45 +11:00
Damien George 63b9944382 extmod/uasyncio: Add new implementation of uasyncio module.
This commit adds a completely new implementation of the uasyncio module.
The aim of this version (compared to the original one in micropython-lib)
is to be more compatible with CPython's asyncio module, so that one can
more easily write code that runs under both MicroPython and CPython (and
reuse CPython asyncio libraries, follow CPython asyncio tutorials, etc).
Async code is not easy to write and any knowledge users already have from
CPython asyncio should transfer to uasyncio without effort, and vice versa.

The implementation here attempts to provide good compatibility with
CPython's asyncio while still being "micro" enough to run where MicroPython
runs. This follows the general philosophy of MicroPython itself, to make it
feel like Python.

The main change is to use a Task object for each coroutine.  This allows
more flexibility to queue tasks in various places, eg the main run loop,
tasks waiting on events, locks or other tasks.  It no longer requires
pre-allocating a fixed queue size for the main run loop.

A pairing heap is used to queue Tasks.

It's currently implemented in pure Python, separated into components with
lazy importing for optional components.  In the future parts of this
implementation can be moved to C to improve speed and reduce memory usage.
But the aim is to maintain a pure-Python version as a reference version.
2020-03-26 01:25:45 +11:00
Damien George f05ae416ff stm32/softtimer: Initialise pairing-heap node before pushing to heap. 2020-03-26 01:21:04 +11:00
Damien George f9741d18f6 unix/coverage: Init all pairheap test nodes before using them. 2020-03-26 01:21:04 +11:00
Damien George 6c7e78de72 py/pairheap: Add helper function to initialise a new node. 2020-03-26 01:21:04 +11:00
Damien George c47a3ddf4a py/pairheap: Properly unlink node on pop and delete.
This fixes a bug in the pairing-heap implementation when nodes are deleted
with mp_pairheap_delete and then reinserted later on.
2020-03-26 01:21:04 +11:00
Damien George 98ab7643a7 travis: Print errors out for OSX job. 2020-03-26 01:21:04 +11:00
Damien George ab00f4c44e qemu-arm: Set default board as mps2-an385 to get more flash for tests.
And use Ubuntu bionic for qemu-arm Travic CI job.
2020-03-26 01:21:04 +11:00
Damien George f8fc78691d py/mpconfig.h: Enable MICROPY_MODULE_GETATTR by default.
To enable lazy loading of submodules (among other things), which is very
useful for MicroPython libraries that want to have optional subcomponents.

Disabled explicitly on minimal ports.
2020-03-26 01:21:04 +11:00
Zoltán Vörös c5cc64175b ports: Add lib/libm/roundf.c to bare-metal Makefile's.
This function is not used by the core but having it as part of the build
allows it to be used by user C modules, or board extensions.  The linker
won't include it in the final firmware if it remains unused.
2020-03-25 01:22:00 +11:00
Damien George bf4fb16250 esp32/modsocket: Handle poll of a closed socket.
This gets tests/extmod/uselect_poll_basic.py working on the esp32.
2020-03-25 01:17:12 +11:00
Andreas Motl fbfea3b440 drivers/onewire: Fix undefined variable errors.
On CPython, and with pylint, the variables MATCH_ROM and SEARCH_ROM are
undefined.  This code works in MicroPython because these variables are
constants and the MicroPython parser/compiler optimises them out.  But it
is not valid Python because they are technically undefined within the scope
they are used.

This commit makes the code valid Python code.  The const part is removed
completely because these constants are part of the public API and so cannot
be moved to the global scope (where they could still use the MicroPython
const optimisation).
2020-03-25 01:09:14 +11:00
David Lechner 2f7d2bb3e2 py/stream.h: Include sys/types.h to get size_t and off_t for POSIX API. 2020-03-25 01:00:52 +11:00
David Lechner 58d9a4815d extmod/vfs_posix_file: Include unistd.h to get STD{IN,OUT,ERR}_FILENO. 2020-03-25 00:59:39 +11:00
David Lechner d0edaf88a3 windows/windows_mphal: Fix missing semicolon. 2020-03-25 00:59:34 +11:00
David Lechner 3b07736b6d unix,windows: Use STDIN_FILENO, STDOUT_FILENO macros where appropriate.
This replaces 0 and 1 with STDIN_FILENO and STDOUT_FILENO to make the
intention of the code clearer.
2020-03-25 00:59:05 +11:00
David Lechner 100012bec6 windows: Remove custom definition of MP_PLAT_PRINT_STRN.
This removes the port-specific definition of MP_PLAT_PRINT_STRN on the
windows port, so that the default mp_hal_stdout_tx_strn_cooked() is always
used.  This fixes releasing the GIL during the call to write() (this was
missed in bc3499f010).

Also, mp_hal_dupterm_tx_strn() was defined but never used anywhere so it is
safe to delete it.
2020-03-25 00:56:38 +11:00
David Lechner b1066a9f96 unix: Remove custom definition of MP_PLAT_PRINT_STRN.
This removes the port-specific definition of MP_PLAT_PRINT_STRN on the unix
port.  Since fee7e5617f this is no longer a
single function call so we are not really optimising anything over using
the default definition of MP_PLAT_PRINT_STRN which calls
mp_hal_stdout_tx_strn_cooked().
2020-03-25 00:54:18 +11:00
Damien George 9fa32169e9 esp8266/modnetwork: Add support for wlan.ifconfig('dhcp').
Fixes issue #5780.
2020-03-25 00:43:04 +11:00
Damien George feb2577585 all: Remove spaces between nested paren and inside function arg paren.
Using new options enabled in the uncrustify configuration.
2020-03-25 00:39:46 +11:00
stijn f62cc41fac windows/msvc: Fix warnings regarding function declarations.
Fix missing mkdir and gettimeofday declarations, then silence msvc-specific
compiler warning C4996: 'The POSIX name for this item is deprecated'.
2020-03-25 00:38:11 +11:00
stijn 1b3e0e10b9 tools/codeformat.py: Include all msvc C code in auto-format. 2020-03-25 00:36:42 +11:00
Maureen Helm 76a5b3a97a zephyr: Update machine.Pin class to use new zephyr gpio api.
Zephyr v2.2 reworked its gpio api to support linux device tree bindings and
pin logical levels.  This commit updates the zephyr port's machine.Pin
class to replace the deprecated gpio api calls with the new supported gpio
api.  This resolves several build warnings.

Tested on frdm_k64f and mimxrt1050_evk boards.
2020-03-25 00:29:42 +11:00
Damien George 40255aff23 stm32/mboot: Remove unnecessary test for led being 1 in led_state.
The "led" argument is always a pointer to the GPIO port, or'd with the pin
that the LED is on, so testing that it is "1" is unnecessary.  The type of
"led" is also changed to uint32_t so it can properly hold a 32-bit pointer.
2020-03-25 00:10:32 +11:00
Andrew Leech 9dd470b768 stm32/mboot: Update LED0 state from systick handler.
Updating the LED0 state from systick handler ensures LED0 is always
consistent with its flash rate regardless of other processing going on in
either interrupts or main.  This improves the visible stability of the
bootloader, rather than LED0 flashing somewhat randomly at times.

This commit also changes the LED0 flash rate depending on the current state
of DFU, giving slightly more visual feedback on what the device is doing.
2020-03-25 00:08:32 +11:00
Andrew Leech 38ccb4c643 tools/pydfu.py: Display any error strings from device/mboot. 2020-03-22 15:24:57 +11:00
Andrew Leech f7130a99b6 stm32/mboot: Protect against invalid address flash writes.
And provide a DFU error message for invalid erases and writes.
2020-03-22 15:23:49 +11:00
Andrew Leech b41d08cf15 stm32/mboot: Update dfu state/status flags to better match standard. 2020-03-22 14:11:16 +11:00
Andrew Leech 03b1ed80e7 stm32/mboot: Allow overriding led_init and led_state in board folder.
Allows for custom functions/logic to display mboot state.
2020-03-22 13:48:45 +11:00
Andrew Leech 2966d83a65 tools/pydfu.py: Add args for VID/PID & exit with cleaner error handling. 2020-03-22 13:33:04 +11:00
Jim Mussared 9715905b18 esp32/README.md: Update build instructions for newer toolchain.
Also fix Espressif links to the specific version they apply to.
2020-03-22 13:26:03 +11:00
Jim Mussared 0cd13081df esp8266/README.md: Add docker build instructions. 2020-03-22 13:26:03 +11:00
Damien George 8d34344dce esp8266/modmachine: Implement machine.soft_reset().
Fixes issue #5764.
2020-03-20 13:40:01 +11:00
Damien George 19ea30bdd5 tests/run-multitests.py: Print test summary and do exit(1) on failure. 2020-03-18 21:33:40 +11:00
Damien George 2cdf1d25f5 unix: Remove custom file implementation to use extmod's VFS POSIX one.
The implementation in extmod/vfs_posix_file.c is now equivalent to that in
ports/unix/file.c, so remove the latter and use the former instead.
2020-03-18 21:01:07 +11:00
Damien George 68b1bc2042 extmod/vfs_posix_file: Lock GIL when writing and allow stdio flush.
Also support MP_STREAM_GET_FILENO ioctl.  The stdio flush change was done
previously for the unix port in 3e0b46b9af.
These changes make this POSIX file implementation equivalent to the unix
file implementation.
2020-03-18 21:01:07 +11:00
Damien George ad9a0ec8ab all: Convert exceptions to use mp_raise_XXX helpers in remaining places. 2020-03-18 17:26:19 +11:00
Damien George 8f0778b209 extmod/modlwip: Properly handle non-blocking and timeout on UDP recv.
Fixes UDP non-blocking recv so it returns EAGAIN instead of ETIMEDOUT.
Timeout waiting for incoming data is also improved by replacing 100ms delay
with poll_sockets(), as is done in other parts of this module.

Fixes issue #5759.
2020-03-18 10:51:32 +11:00
Damien George 00267aae0b extmod/modlwip: Fix polling of UDP socket so it doesn't return HUP.
STATE_NEW will return HUP when polled so put active UDP sockets into a new
state which is different to STATE_NEW.

Fixes issue #5758.
2020-03-18 10:49:27 +11:00
Damien George eae495a714 stm32/main: Fix bug mounting 3rd SD partition.
Fixes issue #5753.
2020-03-12 12:34:31 +11:00
Thomas Friebel baf8aa286a examples/bluetooth: Replace "connectable" parameter with "adv_type".
Follow up to dd0bc26e65 which changed the
parameter list of the IRQ_SCAN_RESULT event.  Adapt
ble_temperature_central.py accordingly.
2020-03-12 10:58:08 +11:00
Maureen Helm 110a610f70 zephyr: Execute main.py file if it exists.
Adds support in the zephyr port to execute main.py if the file system is
enabled and the file exists. Existing support for executing a main.py
frozen module is preserved, since pyexec_file_if_exists() works just
like pyexec_frozen_module() if there's no vfs.
2020-03-11 08:30:42 -05:00
Maureen Helm 78c7e4a859 zephyr: Enable usb mass storage class on mimxrt1050_evk.
Enables the zephyr usb device stack and mass storage class on the
mimxrt1050_evk board. The mass storage class is backed by the sdhc disk
access driver, so it's now possible to browse and modify the contents of
the SD card from a USB host (your PC). This is in preparation to support
writing a main.py script to the SD card, and then executing it after the
next reset.
2020-03-11 07:46:41 -05:00
Maureen Helm 5feb54afbb zephyr: Mount a file system during init.
Adds support in the zephyr port to mount a file system if a block device
(sdhc disk access or flash area) is available. The mount point is either
"/sd" or "/flash" depending on the type of block device.

Tested with an sdhc disk access block device and fatfs on the
mimxrt1050_evk board.

Tested with a flash area block device and littlefs on the reel_board.
2020-03-11 07:46:41 -05:00
Damien George f552451cba travis: For unix tests use Makefile target instead of explicit commands. 2020-03-11 20:20:18 +11:00
Damien George ea1ea909d7 tests/run-tests: Consider all tests as native when emit=native is used.
So that they are skipped when running on a target that doesn't support the
native emitter, eg a nanbox build.
2020-03-11 20:20:18 +11:00
Damien George 359213fbe1 unix/Makefile: Detect and pass thru mpy-cross flags when running tests. 2020-03-11 20:20:18 +11:00
Andrew Leech 86bfabec11 py/modmicropython: Add heap_locked function to test state of heap.
This commit adds micropython.heap_locked() which returns the current
lock-depth of the heap, and can be used by Python code to check if the heap
is locked or not.  This new function is configured via
MICROPY_PY_MICROPYTHON_HEAP_LOCKED and is disabled by default.

This commit also changes the return value of micropython.heap_unlock() so
it returns the current lock-depth as well.
2020-03-11 16:54:16 +11:00
Jim Mussared 7eea0d8b6c mimxrt: Add MIMXRT1010 board. 2020-03-11 15:36:27 +11:00
Jim Mussared f46782dde9 mimxrt: Add new, minimal port to NXP i.MX RT series CPUs.
This is an extremely minimal port to the NXP i.MX RT, in the style of the
SAMD port  It's largely based on the TinyUSB mimxrt implementation, using
the NXP SDK.  It currently supports the Teensy 4.0 board with a REPL over
the USB-VCP interface.

This commit also adds the NXP SDK submodule (also from TinyUSB) to
lib/nxp_driver.

Note: if you already have the tinyusb submodule initialized recursively you
will need to run the following as the tinyusb sub-submodules have been
rearranged (upstream):

    git submodule deinit lib/tinyusb
    rm -rf .git/modules/lib/tinyusb
    git submodule update --init lib/tinyusb
2020-03-11 15:34:13 +11:00
Jim Mussared 211032a5c9 samd: Fix to build with latest tinyusb. 2020-03-11 15:34:10 +11:00
Jim Mussared 6cea369b89 lib/tinyusb: Update to a6b916ba for i.MX support. 2020-03-11 15:32:55 +11:00
Andrew Leech ed93778e00 py/objstringio: Expose tell() on StringIO and BytesIO objects.
To match file objects.

Fixes issue #5581.
2020-03-11 14:43:03 +11:00
David Lechner 8a4ce6b79a tools/codeformat.py: Eliminate need for sizeof fixup.
This eliminates the need for the sizeof regex fixup by rearranging things a
bit.  All other bitfields already use the parentheses around expressions
with sizeof, so one case is fixed by following this convention.

VM_MAX_STATE_ON_STACK is the only remaining problem and it can be worked
around by changing the order of the operands.
2020-03-11 14:34:40 +11:00
Tom Collins fccf17521a py/objstr: Remove duplicate % in error string.
The double-% was added in 11de8399fe (Jun
2014) when such errors were formatted with printf.  But then
55830dd9bf (Dec 2018) changed
mp_obj_new_exception_msg() to not format the message, as discussed
in #3004.  So such error strings are no longer formatted and a % is just
that.
2020-03-11 14:31:29 +11:00
Damien George ed848553b4 extmod/vfs: Factor out vfs mount-and-chdir helper from stm32. 2020-03-11 14:24:26 +11:00
Damien George 554c01fc25 tools/metrics.py: Use check_call instead of run to error out on error. 2020-03-11 14:23:39 +11:00
Damien George 7bf62562ce extmod/nimble: When getting BLE MAC try public address if random fails.
This is needed for BLE.config('mac') to work on esp32.
2020-03-11 14:02:13 +11:00
Damien George dd0bc26e65 extmod/modbluetooth: Change scan result's "connectable" to "adv_type".
This commit changes the BLE _IRQ_SCAN_RESULT data from:

    addr_type, addr, connectable, rssi, adv_data

to:

    addr_type, addr, adv_type, rssi, adv_data

This allows _IRQ_SCAN_RESULT to handle all scan result types (not just
connectable and non-connectable passive scans), and to distinguish between
them using adv_type which is an integer taking values 0x00-0x04 per the BT
specification.

This is a breaking change to the API, albeit a very minor one: the existing
connectable value was a boolean and True now becomes 0x00, False becomes
0x02.

Documentation is updated and a test added.

Fixes #5738.
2020-03-11 14:00:44 +11:00
Thomas Friebel bd746a4630 esp32: Deinitialize Bluetooth on soft reset.
This fixes a crash, caused by NimBLE continuing to call the Python BLE
interrupt handler after soft reboot.
2020-03-11 13:02:00 +11:00
Thomas Friebel 41a9f1dec8 extmod/modbluetooth: Unify error handling in remaining places.
Most error handling is done via `bluetooth_handle_errno()` already.
Replace the remaining few manual checks with calls to that function.
2020-03-11 13:01:35 +11:00
Jim Mussared 1937fb22ab extmod/nimble: Clarify active state and check for active in all methods.
This commit ensures that the BLE stack is active before allowing operations
that may otherwise crash if it's not active.  It also clarifies the state
better (adding the "stopping" state) and renames mp_bluetooth_is_enabled to
the more self-explanatory mp_bluetooth_is_active.
2020-03-11 13:01:35 +11:00
Damien George a017576706 esp8266/machine_pin: Disable ets_loop_iter during hard IRQ handler.
Otherwise ets_loop_iter may be reentered.  Related to issue #5714.
2020-03-10 16:48:34 +11:00
Damien George 4fda7a5b44 tests/multi_bluetooth: Add initial tests for bluetooth BLE. 2020-03-10 02:22:34 +11:00
Damien George bd50651567 travis: Run multi_net tests as part of coverage job. 2020-03-10 02:22:34 +11:00
Damien George 8f44c0dd16 tests/multi_net: Add initial set of multi-instance tests for network. 2020-03-10 02:22:34 +11:00
Damien George df9a949891 tests/run-multitests.py: Add new test runner for multiple Py instances.
This commit adds a test runner and initial test scripts which run multiple
Python/MicroPython instances (eg executables, target boards) in parallel.
This is useful for testing, eg, network and Bluetooth functionality.

Each test file has a set of functions called instanceX(), where X ranges
from 0 up to the maximum number of instances that are needed, N-1.  Then
run-multitests.py will execute this script on N separate instances (eg
micropython executables, or attached boards via pyboard.py) at the same
time, synchronising their start in the right order, possibly passing IP
address (or other address like bluetooth MAC) from the "server" instance to
the "client" instances so they can connect to each other.  It then runs
them to completion, collects the output, and then tests against what
CPython gives (or what's in a provided .py.exp file).

The tests will be run using the standard unix executable for all instances
by default, eg:

    $ ./run-multitests.py multi_net/*.py

Or they can be run with a board and unix executable via:

    $ ./run-multitests.py --instance pyb:/dev/ttyACM0 --instance exec:micropython multi_net/*.py
2020-03-10 02:22:34 +11:00
Damien George ecee6f2877 travis: Build stm32 PYBD_SF6 with BTstack as bluetooth stack. 2020-03-10 01:53:42 +11:00
Damien George e965363b6b stm32: Refactor Bluetooth HCI RX to be independent of transport layer.
Now all HCI specific code (eg UART vs WB55 internal messaging) is confined
to modbluetooth_hci.c.
2020-03-10 01:53:42 +11:00
Damien George d7259f6b1c extmod/btstack: Implement notifications/indications for GATT clients.
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George 018ce122ca extmod/btstack: Implement scan and gatt client, connect and disconnect.
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George 372e5a280e extmod/btstack: Implement gatts_db for btstack.
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George 86c26db3ff extmod/btstack: Implement service registration.
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George 0674917bc5 extmod/btstack: Implement advertising.
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George 51f8591097 stm32/boards/PYBD: Allow building with BTstack (via make command line).
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George 0e95815bfb stm32: Add bindings for BTstack implementation.
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George fbefcef1df extmod/btstack: Add empty modbluetooth implementation.
Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George d35fefe30a lib: Add BlueKitchen BTstack submodule. 2020-03-10 01:53:42 +11:00
Damien George 0ac06a510a extmod/modbluetooth: Extract out gatts_db functionality from nimble.
For use by other stacks, if they need it.

Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George 894c550c86 stm32: Refactor bluetooth stack/hci/driver bindings.
This makes a cleaner separation between the: driver, HCI UART and BT stack.
Also updated the naming to be more consistent (mp_bluetooth_hci_*).

Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-10 01:53:42 +11:00
Damien George c44d52f33e extmod/modbluetooth_nimble: Move nimble specific code, factor nimble.mk.
Move extmod/modbluetooth_nimble.* to extmod/nimble.  And move common
Makefile lines to extmod/nimble/nimble.mk (which was previously only used
by stm32).  This allows (upcoming) btstack to follow a similar structure.

Work done in collaboration with Jim Mussared aka @jimmo.
2020-03-06 12:35:20 +11:00
Damien George 44aa5b2200 stm32/modnetwork: Remove redundant call to nimble_poll in lwip poll.
The bluetooth stack has its own dedicated polling function, see
mod_bluetooth_nimble_poll_wrapper().
2020-03-06 12:35:20 +11:00
MikeTeachman 8db5d2d1f1 tools/makemanifest.py: Fix build on Windows by adding .exe to mpy-cross.
When using a manifest on Windows the reference to mpy-cross compiler was
missing the .exe file extension, so add it when appropriate.

Also allow the default path to mpy-cross to be overridden by the (optional)
MICROPY_MPYCROSS environment variable, to allow full flexibility on any OS.
2020-03-05 10:26:31 +11:00
Damien George 3e0b46b9af unix/file: Don't raise OSError(EINVAL) on sys.stdin/out/err.flush().
sys.stdout.flush() is needed on CPython to flush the output, and the change
in this commit makes such an expression also work on MicroPython (although
MicroPython doesn't actual need to do any flushing).
2020-03-04 12:39:55 +11:00
Damien George 9c07c973c1 examples/natmod: Add .gitignore to ignore generated example .mpy files. 2020-03-03 12:54:17 +11:00
Damien George 1993c8cf9a py/builtinevex: Support passing in a bytearray/buffer to eval/exec.
CPython allows this and it's a simple generalisation of the existing code
which just supported str/bytes.

Fixes issue #5704.
2020-02-28 12:45:36 +11:00
Damien George 54a54f5872 CODECONVENTIONS.md: Update to reflect use of new tools/codeformat.py. 2020-02-28 12:35:19 +11:00
Damien George f6375ac3eb travis: Add CI job to check code formatting.
The CI job will fail if there is any code which does not conform to the
style encoded by tools/codeformat.py.  And it will list any changes
required.

uncrustify is built from source because Ubuntu bionic has uncrustify-0.66.1
which is from 2017/11/22 and is missing many options needed here.
2020-02-28 10:34:17 +11:00
Damien George 69661f3343 all: Reformat C and Python source code with tools/codeformat.py.
This is run with uncrustify 0.70.1, and black 19.10b0.
2020-02-28 10:33:03 +11:00
Damien George 3f39d18c2b all: Add *FORMAT-OFF* in various places.
This string is recognised by uncrustify, to disable formatting in the
region marked by these comments.  This is necessary in the qstrdef*.h files
to prevent modification of the strings within the Q(...).  In other places
it is used to prevent excessive reformatting that would make the code less
readable.
2020-02-28 10:31:07 +11:00
Damien George b86075ef1f py/parse: Add parenthesis around calculated bit-width in struct.
To improve interaction with uncrustify formatter.
2020-02-28 10:30:52 +11:00
Damien George 3c58d9a1a5 examples/bluetooth/ble_temperature_central.py: Shorten comment.
So the line length is less than 100 characters.
2020-02-28 10:30:49 +11:00
Damien George a0441fc15d examples/accellog.py: Shift long comments to their own line.
To improve interaction with black formatter.
2020-02-28 10:30:37 +11:00
Damien George 17aeb43e18 py: Un-nest configuration #if/#endif's for selection of complex code.
Because un-nested #if's are simpler to handle with formatting tools.
2020-02-28 10:30:34 +11:00
Damien George 7768a8c38d py/malloc: Put { on separate line for funcs that have selective sigs.
To ensure there are balanced {}'s in the file, and to help with formatting.
2020-02-28 10:30:29 +11:00
Damien George 73670ef281 unix/unix_mphal: Adjust #if in mp_hal_stdin_rx_chr to improve format. 2020-02-28 10:30:28 +11:00
Damien George a642241a12 py/builtinimport: Adjust if-block order in find_file to clean up #if's. 2020-02-28 10:30:20 +11:00
Damien George 2b50afaee4 py/bc0.h: Shift comment to start of line to improve format consistency. 2020-02-28 10:29:32 +11:00
Damien George a1b18b3ba7 py: Removing dangling "else" to improve code format consistency. 2020-02-28 10:29:27 +11:00
Damien George 4b23e98fb0 tools/codeformat.py: Add formatter using uncrustify for C, black for Py.
This commit adds a tool, codeformat.py, which will reformat C and Python
code to fit a certain style.  By default the tool will reformat (almost)
all the original (ie not 3rd-party) .c, .h and .py files in this
repository.  Passing filenames on the command-line to codeformat.py will
reformat only those.  Reformatting is done in-place.

uncrustify is used for C reformatting, which is available for many
platforms and can be easily built from source, see
https://github.com/uncrustify/uncrustify.  The configuration for uncrustify
is also added in this commit and values are chosen to best match the
existing code style.  A small post-processing stage on .c and .h files is
done by codeformat.py (after running uncrustify) to fix up some minor
items:
- space inserted after * when used as multiplication with sizeof
- #if/ifdef/ifndef/elif/else/endif are dedented by one level when they are
  configuring if-blocks and case-blocks.

For Python code, the formatter used is black, which can be pip-installed;
see https://github.com/psf/black.  The defaults are used, except for line-
length which is set at 99 characters to match the "about 100" line-length
limit used in C code.

The formatting tools used and their configuration were chosen to strike a
balance between keeping existing style and not changing too many lines of
code, and enforcing a relatively strict style (especially for Python code).
This should help to keep the code consistent across everything, and reduce
cognitive load when writing new code to match the style.
2020-02-28 10:14:28 +11:00
hahmadi b169904254 stm32/mpconfigport.h: Add option to have custom help text.
Define MICROPY_PY_BUILTINS_HELP_TEXT in <yourboard>/mpconfigboard.h for a
custom help text.
2020-02-21 15:02:19 +11:00
Jim Mussared 54db464a1b tests/basics/array1.py: Add equality testing for array. 2020-02-21 14:25:03 +11:00
Jim Mussared 3ccce89b83 py/objarray: Turn on MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE for memoryview.
And add corresponding tests.

Fixes #5674 (comparison of memoryview against bytes).
2020-02-21 14:24:07 +11:00
stijn 2d800c77a0 travis: Add OSX build to CI.
Add a standard unix port build in an OSX environment using clang.  Should
help in catching build failures due to platform differences early on.
2020-02-21 14:20:52 +11:00
Jim Mussared f8449dd092 extmod/modframebuf: Allow blit source to be a subclass of FrameBuffer. 2020-02-21 13:32:48 +11:00
Damien George f6d99bc795 py/dynruntime.h: Add implementation of mp_obj_cast_to_native_base. 2020-02-21 13:32:48 +11:00
Damien George 9344e876bb py/objtype: Allow mp_instance_cast_to_native_base to take native obj.
And rename it to mp_obj_cast_to_native_base() to indicate this.  This
allows users of this function to easily support native and native-subclass
objects in the same way (by just passing the object through this function).
2020-02-21 13:20:12 +11:00
Damien George d3b2c6e44c py/objtuple: Remove code that handles tuple-subclass equality test.
Since commit 3aab54bf43 this piece of code is
no longer needed because the top-level function mp_obj_equal_not_equal()
now handles the case of user types, and will never call tuple's binary_op
function with MP_BINARY_OP_EQUAL and a non-tuple on the RHS.
2020-02-20 10:48:03 +11:00
Damien George 819380c964 tests/basics: Add test for tuple compare with class derived from tuple.
Only the "==" operator was tested by the test suite in for such arguments.
Other comparison operators like "<" take a different path in the code so
need to be tested separately.
2020-02-20 10:48:03 +11:00
Damien George a636837987 tools/makemanifest.py: Support freezing with empty list of mpy files.
Fixes issue #5655.
2020-02-20 10:41:50 +11:00
Damien George 410757f4f4 unix/mphalport.h: Fix build when MICROPY_USE_READLINE=0.
If the built-in input() is enabled (which it is by default) then it needs
some form of readline, so supply it with one when MICROPY_USE_READLINE=0.

Fixes issue #5658.
2020-02-20 00:45:58 +11:00
Jim Mussared a9ce8dfdaa esp32: Move to IDF 4.0 release version. 2020-02-20 00:34:31 +11:00
David Lechner 4adcaa4423 unix/mpthreadport: Fix Mac build by using SIGUSR1 if SIGRTMIN not avail.
Some platforms, like Apple, don't define SIGRTMIN, so fall back to SIGUSR1
in such a case.

Fixes #5659.
2020-02-20 00:30:08 +11:00
Damien George 1fccda049f py/objexcept: Rename mp_obj_new_exception_msg_varg2 to ..._vlist.
Follow up to recent commit ad7213d3c3, the
name "varg2" is misleading, vlist describes better that the argument is a
va_list.  This name also matches CircuitPython, which already has such
helper functions.
2020-02-18 21:00:42 +11:00
Jim Mussared cddb90e8b0 extmod/modbluetooth_nimble: Fix wrong offset used for descriptor flags. 2020-02-18 16:37:38 +11:00
Jim Mussared 66ac2e1fc0 extmod/modbluetooth.h: Fix typo in comment about registering services. 2020-02-18 16:36:37 +11:00
Andrew Leech 3fe83e4318 stm32/sdram: Fix compile issue from unused sdram startup test flag. 2020-02-18 14:22:03 +11:00
Thomas Friebel f4726735cf extmod/modbluetooth: Implement config getter for BLE rxbuf size.
Knowing the buffer size can be important, to ensure that valid data will be
received.
2020-02-18 13:37:50 +11:00
David Lechner 3bd2ae1a36 unix/mpthreadport: Use SIGRTMIN+5 instead of SIGUSR1 for thread-GC.
This changes the signal used to trigger garbage collection from SIGUSR1 to
SIGRTMIN + 5.  SIGUSR1 is quite common compared to SIGRTMIN (measured by
google search results) and is more likely to conflict with libraries that
may use the same signal.

POSIX specifies that there are at least 8 real-time signal so 5 was chosen
as a "random" number to further avoid potential conflict with libraries
that may use SIGRTMIN or SIGRTMAX.

Also, if we ever have a `usignal` module, it would be nice to leave SIGUSR1
and SIGUSR2 free for user programs.
2020-02-18 13:32:42 +11:00
Damien George ce39c958ef py: Factor out definition of mp_float_union_t to one location. 2020-02-18 13:04:36 +11:00
Damien George ac8383a95d nrf: Use MICROPY_HW_ENABLE_RNG instead of MICROPY_PY_RANDOM_HW_RNG.
The "random" module no longer uses the hardware RNG (the extmod version of
this module has a pseudo-random number generator), so the config option
MICROPY_PY_RANDOM_HW_RNG is no longer meaningful.  This commit replaces it
with MICROPY_HW_ENABLE_RNG, which controls whether the hardware RNG is
included in the build.
2020-02-18 12:43:16 +11:00
Damien George 6ad3bb1e12 nrf: Remove custom "random" module and use extmod version instead.
Hardware RNG code is moved to drivers/rng.[ch].
2020-02-18 12:43:16 +11:00
cccc 4f3e5ea934 nrf/drivers/bluetooth: Fix variable initialisation error with older gcc.
Without this change, arm-none-eabi-gcc version 4.9.3 (at least) would give
a "missing braces around initializer" error.
2020-02-16 23:46:27 +11:00
David Lechner 4af79e7694 unix/Makefile: Allow to install all variants of the executable.
The install target is current broken when PROG is used to override the
default executable name.  This fixes it by removing the redundant TARGET
variable and uses PROG directly instead.

The install and uninstall targets are also moved to the common unix
Makefile so that all variants can be installed in the same way.
2020-02-16 23:37:40 +11:00
David Lechner c5f4268c99 unix/variants/standard: Fix role of PREFIX when used to install.
Currently it is not possible to override PREFIX when installing micropython
using the makefile.  It is common practice to be able to run something like
this:

    $ make install PREFIX=/usr DESTDIR=/tmp/staging

This fixes such usage.
2020-02-16 23:35:52 +11:00
Peter Hinch d2f22ea953 drivers/nrf24l01: Change pipe addrs in test to match Arduino addrs.
These addresses were initially chosen to match the nRF24 Arduino library
examples but they are byte-reversed.  So change them to be on-air
compatible with the Arduino library.

Also, the data sheet for the nRF24 says that RX data pipes 1-5 must share
the same top 32-bits, and must differ only in the LSbyte.  The addresses
used here (while correct because they are on TX pipe and RX pipe 0) are
misleading in this sense, because it looks like they were chosen to share
the top 32-bits per the datasheet.
2020-02-16 23:26:34 +11:00
Damien George baf11f237b unix/Makefile: Remove old variant targets that are no longer needed.
To eliminate confusion about what targets to use when building.
2020-02-16 00:15:57 +11:00
Thorsten von Eicken be92aacba3 docs/develop: Detail how to add symbols to mp_fun_table for native mods. 2020-02-16 00:04:25 +11:00
David Lechner f020eac6a8 py/obj.h: Remove TODO idea comment about truncated mp_map_t.
It was suggested to move this to a GitHub issue rather than keep it in the
code, which isn't really sustainable for all ideas.
2020-02-13 13:14:17 +11:00
Damien George ad7213d3c3 py: Add mp_raise_msg_varg helper and use it where appropriate.
This commit adds mp_raise_msg_varg(type, fmt, ...) as a helper for
nlr_raise(mp_obj_new_exception_msg_varg(type, fmt, ...)).  It makes the
C-level API for raising exceptions more consistent, and reduces code size
on most ports:

   bare-arm:   +28 +0.042%
minimal x86:  +100 +0.067%
   unix x64:   -56 -0.011%
unix nanbox:  -300 -0.068%
      stm32:  -204 -0.054% PYBV10
     cc3200:    +0 +0.000%
    esp8266:   -64 -0.010% GENERIC
      esp32:  -104 -0.007% GENERIC
        nrf:  -136 -0.094% pca10040
       samd:    +0 +0.000% ADAFRUIT_ITSYBITSY_M4_EXPRESS
2020-02-13 11:52:40 +11:00
Damien George 97eca38c4f py: Add mp_raise_type helper macro and use it where appropriate.
This provides a more consistent C-level API to raise exceptions, ie moving
away from nlr_raise towards mp_raise_XXX.  It also reduces code size by a
small amount on some ports.
2020-02-13 11:03:37 +11:00
Damien George 7679e3be96 py/objmodule.h: Remove obsolete mp_builtin_module_weak_links_map decl.
It was made obsolete in d2384efa80
2020-02-11 15:43:13 +11:00
Damien George 5a755ac30a esp32/modsocket: Convert EADDRINUSE error code from lwip return value. 2020-02-11 13:59:09 +11:00
stijn 5f91933e54 windows: Improve default search path.
The default value for MICROPYPATH used in unix/main.c is
"~/.micropython/lib:/usr/lib/micropython" which has 2 problems when used in
the Windows port:
- it has a ':' as path separator but the port uses ';' so the entire string
  is effectively discarded since it gets interpreted as a single path which
  doesn't exist
- /usr/lib/micropython is not a valid path in a standard Windows
  environment

Override the value with a suitable default.
2020-02-11 13:34:35 +11:00
stijn 8b6e6008c7 unix/main: Use OS-dependent path separator when searching path. 2020-02-11 13:33:56 +11:00
Damien George 580fd636c0 nrf/drivers: Use mp_raise_msg where appropriate, and shorten exc msgs.
If the exception doesn't need printf-style formatting then calling
mp_raise_msg is more efficient.  Also shorten exception messages to match
style in core and other ports.
2020-02-11 11:45:14 +11:00
Damien George 6a3ca96fe5 tests/basics: Add test for equality between tuple and namedtuple. 2020-02-11 11:06:17 +11:00
Damien George 27465e6b24 tests/basics: Add tests for equality between bool and int/float/complex.
False/True should be implicitly converted to 0/1 when compared with numeric
types.
2020-02-11 11:06:17 +11:00
Damien George 9ec1caf42e py: Expand type equality flags to 3 separate ones, fix bool/namedtuple.
Both bool and namedtuple will check against other types for equality; int,
float and complex for bool, and tuple for namedtuple.  So to make them work
after the recent commit 3aab54bf43 they would
need MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST set.  But that makes all bool and
namedtuple equality checks less efficient because mp_obj_equal_not_equal()
could no longer short-cut x==x, and would need to try __ne__.  To improve
this, this commit splits the MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST flags into 3
separate flags to give types more fine-grained control over how their
equality behaves.  These new flags are then used to fix bool and namedtuple
equality.

Fixes issue #5615 and #5620.
2020-02-11 11:06:00 +11:00
Yonatan Goldschmidt 0852acfc74 tests/run-tests: Auto-skip extmod/ticks_diff, extmod/time_ms_us tests. 2020-02-11 10:56:49 +11:00
Peter Hinch 88cbfd791a docs/library: Fix framebuf monochrome 1-bit modes, swapping HLSB/HMSB.
This fix can be demonstrated by the following:

    b = bytearray(32)
    f = framebuf.FrameBuffer(b, 32, 8, framebuf.MONO_HLSB)
    f.pixel(0, 0, 1)
    print('MONO_HLSB', hex(b[0]))

    b = bytearray(32)
    f = framebuf.FrameBuffer(b, 32, 8, framebuf.MONO_HMSB)
    f.pixel(0, 0, 1)
    print('MONO_HMSB', hex(b[0]))

Outcome:

    MONO_HLSB 0x80
    MONO_HMSB 0x1
2020-02-10 23:04:15 +11:00
Damien George ce40abcf21 stm32/usbd_cdc_interface: Remove "interrupt_char != -1" check.
It's not needed.  The C integer implicit promotion rules mean that the
uint8_t of the incoming character is promoted to a (signed) int, matching
the type of interrupt_char.  Thus the uint8_t incoming character can never
be equal to -1 (the value of interrupt_char that indicate that interruption
is disabled).
2020-02-07 16:08:37 +11:00
Damien George 046ae80bdf unix, windows: Use mp_keyboard_interrupt instead of custom code.
The mp_keyboard_interrupt() function does exactly what is needed here, and
using it gets ctrl-C working when MICROPY_ENABLE_SCHEDULER is enabled on
these ports (and MICROPY_ASYNC_KBD_INTR is disabled).
2020-02-07 16:08:33 +11:00
Damien George abe2caf6df py/scheduler: Move clearing of kbd traceback to mp_keyboard_interrupt.
This is a more logical place to clear the KeyboardInterrupt traceback,
right before it is set as a pending exception.  The clearing is also
optimised from a function call to a simple store of NULL.
2020-02-07 16:08:31 +11:00
Damien George f4641b2378 esp32/uart: Use core-provided mp_keyboard_interrupt, placed in IRAM. 2020-02-07 16:08:31 +11:00
Damien George 8d0421c3cf esp8266: Put mp_keyboard_interrupt in IRAM.
It was originally in IRAM due to the linker script specification, but
since the function moved from lib/utils/interrupt_char.c to py/scheduler.c
it needs to be put back in IRAM.
2020-02-07 16:08:31 +11:00
Damien George 8fb5c8fdd5 py/scheduler: Allow a port to specify attrs for mp_keyboard_interrupt.
Functions like mp_keyboard_interrupt() may need to be called from an IRQ
handler and may need to be in a special memory section, so provide a
generic wrapping macro for a port to do this.  The macro name is chosen to
be MICROPY_WRAP_<function name in uppercase> so that (in the future with
more wrappers) each function could potentially be handled separately.
2020-02-07 16:08:29 +11:00
Damien George eaf30c516a tests/unix: Add coverage tests for kbd-intr and scheduler. 2020-02-07 16:08:29 +11:00
Damien George 9efb36bfa6 py/scheduler: Move mp_keyboard_interrupt from lib/utils to py core.
This function is tightly coupled to the state and behaviour of the
scheduler, and is a core part of the runtime: to schedule a pending
exception.  So move it there.
2020-02-07 16:08:26 +11:00
Damien George 5a91cd9ff3 lib/utils/pyexec: Handle pending exceptions after disabling kbd intrs.
Pending exceptions would otherwise be handled later on where there may not
be an NLR handler in place.

A similar fix is also made to the unix port's REPL handler.

Fixes issues #4921 and #5488.
2020-02-07 16:08:26 +11:00
Damien George 98a3911c43 py/scheduler: Add "raise_exc" argument to mp_handle_pending.
Previous behaviour is when this argument is set to "true", in which case
the function will raise any pending exception.  Setting it to "false" will
cancel any pending exception.
2020-02-07 16:08:20 +11:00
Maureen Helm 7a5752a748 zephyr: Enable littlefs.
Enables the littlefs (v1 and v2) filesystems in the zephyr port.

Example usage with the internal flash on the reel_board or the
rv32m1_vega_ri5cy board:

import os
from zephyr import FlashArea
bdev = FlashArea(FlashArea.STORAGE, 4096)
os.VfsLfs2.mkfs(bdev)
os.mount(bdev, '/flash')
with open('/flash/hello.txt','w') as f:
    f.write('Hello world')
print(open('/flash/hello.txt').read())

Things get a little trickier with the frdm_k64f due to the micropython
application spilling into the default flash storage partition defined
for this board. The zephyr build system doesn't enforce the flash
partitioning when mcuboot is not enabled (which it is not for
micropython). For now we can demonstrate that the littlefs filesystem
works on frdm_k64f by constructing the FlashArea block device on the
mcuboot scratch partition instead of the storage partition. Do this by
replacing the FlashArea.STORAGE constant above with the value 4.
2020-02-07 11:24:06 +11:00
Maureen Helm 86a66960f9 zephyr: Implement block device protocol via zephyr flash map api.
Introduces a new zephyr.FlashArea class that uses the zephyr flash map
api to implement the uos.AbstractBlockDev protocol. The flash driver is
enabled on the frdm_k64f board, reel_board, and rv32m1_vega_ri5cy board.

The standard and extended block device protocols are both supported,
therefore this class can be used with file systems like littlefs which
require the extended interface.
2020-02-07 11:24:06 +11:00
Maureen Helm 2d7ec8e704 zephyr: Enable fatfs.
Enables the fatfs filesystem in the zephyr port.

Example usage with an SD card on the mimxrt1050_evk board:

import zephyr, os
bdev = zephyr.DiskAccess('SDHC')
os.VfsFat.mkfs(bdev)
os.mount(bdev, '/sd')
with open('/sd/hello.txt','w') as f:
    f.write('Hello world')
print(open('/sd/hello.txt').read())
2020-02-07 11:24:06 +11:00
Maureen Helm a0440b01ea zephyr: Enable virtual file system and uos module.
Enables the virtual file system and uos module in the zephyr port.
No concrete file system implementations are enabled yet.
2020-02-07 11:24:06 +11:00
Maureen Helm cc19cf2549 zephyr: Implement block device protocol via zephyr disk access api.
Introduces a new zephyr.DiskAccess class that uses the zephyr disk
access api to implement the uos.AbstractBlockDev protocol. This can be
used with any type of zephyr disk access driver, which currently
includes SDHC, RAM, and FLASH implementations. The SDHC driver is
enabled on the mimxrt1050_evk board.

Only the standard block device protocol (without the offset parameter)
can be supported with the zephyr disk access api, therefore this class
cannot be used with file systems like littlefs which require the
extended interface. In the future it may be possible to implement the
extended interface in a new class using the zephyr flash api.
2020-02-07 11:24:06 +11:00
Petr Viktorin dbed8f576d tests/basics: Move test for "return" outside function to own file.
Because its behaviour is conditional on MICROPY_CPYTHON_COMPAT.
2020-02-06 00:42:34 +11:00
Petr Viktorin e6c9800645 py/compile: Allow 'return' outside function in minimal builds.
A 'return' statement on module/class level is not correct Python, but
nothing terribly bad happens when it's allowed.  So remove the check unless
MICROPY_CPYTHON_COMPAT is on.

This is similar to MicroPython's treatment of 'import *' in functions
(except 'return' has unsurprising behavior if it's allowed).
2020-02-06 00:41:55 +11:00
Damien George d6a1e45caa stm32/usbd_conf: Allow boards to configure USB HS ULPI NXT/DIR pins. 2020-02-04 23:15:55 +11:00
Damien George 69b415f745 tests: Move CPy diff test to real test now that subclass equality works.
Testing for equality of subclassed strings now works, thanks to commit
3aab54bf43
2020-02-04 18:25:34 +11:00
Andrew Leech ff9a61b5a8 stm32/sdram: Expose the result of sdram startup test in stm32_main.
This means boards can choose to only use it for gc heap if the test passes.
2020-02-04 18:18:41 +11:00
odewdney b51a2c266a lib/utils: Change default value of pyexec_mode_kind to 0 to put in bss.
By simply reordering the enums for pyexec_mode_kind_t it eliminates a data
variable which costs ROM to initialise it.  And the minimal build now has
nothing in the data section.

It seems the compiler is smart enough so that the generated code for
if-logic which tests these enum values is unchanged.
2020-02-04 18:10:26 +11:00
Jim Mussared 0645478475 esp32/Makefile: Reorder includes to build with latest toolchain.
Tested on:
- IDF3.3.1 (old toolchain)
- IDF4.0-beta1 (old toolchain)
- IDF4.0-beta1 (new toolchain from install.sh / export.sh)
2020-02-04 18:06:14 +11:00
David Lechner 74106757ac tests/cpydiff: Add os module environ differences. 2020-02-04 17:54:31 +11:00
David Lechner 4a97f7aaf3 tests/cmdline: Add test for MICROPYINSPECT environment variable.
When this variable is set to non-empty string it triggers the REPL after a
command/module/file finishes running.

The Python file without the file extension is because the cmdline: parser
in run-test splits on spaces, so we can't use the -c option since
`import os` can't be written without a space.
2020-02-04 17:54:31 +11:00
David Lechner f1b6e6bb15 unix/modos: Implement putenv and unsetenv to complement getenv.
CPython also has os.environ, which should be used instead of os.getenv()
due to caching in the os.environ mapping.  But for MicroPython it makes
sense to only implement the basic underlying methods, ie getenv/putenv/
unsetenv.
2020-02-04 17:54:31 +11:00
David Lechner 83439e38fc unix/main: Add command-line -h option for printing help text.
This adds a -h option to print the usage help text and adds a new, shorter
error message that is printed when invalid arguments are given.  This
behaviour follows CPython (and other tools) more closely.
2020-02-04 17:54:31 +11:00
David Lechner 5a63bc5a44 unix/main: Add #if guard around -v option usage and document -i/-m opts.
This commit modifies the usage() function to only print the -v option help
text when MICROPY_DEBUG_PRINTERS is enabled.  The -v option requires this
build option to be enabled for it to have any effect.

The usage text is also modified to show the -i and -m options, and also
show that running a command, module or file are mutually exclusive.
2020-02-04 17:53:35 +11:00
David Lechner c8d2f7838f docs/unix: Add a new new quickref page for the UNIX port.
This adds a new quickstart page for the UNIX port that documents the
command line options and environment variables.
2020-02-04 17:53:06 +11:00
David Lechner 7c24f55285 tests/cmdline/repl_inspect: Add new test for -i option.
This adds a new test to verify that the inspect (-i) command line option
works.
2020-02-04 17:53:06 +11:00
David Lechner 122baa6787 unix/main: Add support for MICROPYINSPECT environment variable.
This adds support for a MICROPYINSPECT environment variable that works
exactly like PYTHONINSPECT; per CPython docs:

    If this is set to a non-empty string it is equivalent to specifying the
    -i option.

    This variable can also be modified by Python code using os.environ to
    force inspect mode on program termination.
2020-02-04 17:52:58 +11:00
Maureen Helm bc3ce86a5a zephyr: Remove reference to syscall_macros_h_target.
Zephyr removed the build target syscall_macros_h_target in commit
f4adf107f31674eb20881531900ff092cc40c07f.  Removes reference from
MicroPython to fix build errors in the zephyr port.

This change is not compatible with zephyr v2.1 or earlier.  It will be
compatible with Zephyr v2.2 when released.
2020-02-04 17:10:24 +11:00
Maureen Helm a7663b862e zephyr: Replace deprecated time conversion macro.
The SYS_CLOCK_HW_CYCLES_TO_NS macro was deprecated in zephyr commit
8892406c1de21bd5de5877f39099e3663a5f3af1.  This commit updates MicroPython
to use the new k_cyc_to_ns_floor64 api and fix build warnings in the zephyr
port.

This change is compatible with Zephyr v2.1 and later.
2020-02-04 17:09:59 +11:00
Maureen Helm c25e12d0dd zephyr: Update include paths for Zephyr v2.0.
Zephyr restructured its includes in v2.0 and removed compatibility shims
after two releases in commit 1342dadc365ee22199e51779185899ddf7478686.
Updates include paths in MicroPython accordingly to fix build errors in
the zephyr port.

These changes are compatible with Zephyr v2.0 and later.
2020-02-04 17:09:19 +11:00
Jesse Andrews c4ea4c1810 docs/esp8266: In TCP tutorial, add HTTP response code and content-type.
Show how to send an HTTP response code and content-type.  Without the
response code Safari/iOS will fail.  Without the content-type Lynx/Links
will fail.
2020-02-03 23:50:09 +11:00
David Lechner 4ab8bee82f unix/main: Print usage and NLR errors to stderr instead of stdout.
When stdout is redirected it is useful to have errors printed to stderr
instead of being redirected.

mp_stderr_print() can't be used in these two instances since the
MicroPython runtime is not running so we use fprintf(stderr) instead.
2020-02-01 22:44:08 +11:00
caochaowu 61f64c78a6 nrf/boards/common.ld: Add ENTRY(Reset_Handler) in linker script.
It's not strictly needed but can be helpful when using a debugger.
2020-02-01 00:09:44 +11:00
Michael Buesch 1604606238 tools/pyboard.py: Change shebang to use python3.
This script still works with Python 2 but Python 3 is recommended.
2020-02-01 00:06:26 +11:00
Michael Buesch 1cadb12d1c tools/pyboard.py: Use slice del instead of list.clear() for Py2 compat.
Python 2 does not have list.clear().
2020-02-01 00:05:29 +11:00
Michael Buesch 83afd48ad9 tools/pyboard.py: Add option --no-follow to detach after sending script.
This option makes pyboard.py exit as soon as the script/command is
successfully sent to the device, ie it does not wait for any output.  This
can help to avoid hangs if the board is being rebooted with --comman (for
example).

Example usage:

    $ python3 ./tools/pyboard.py --device /dev/ttyUSB0 --no-follow \
        --command 'import machine; machine.reset()'
2020-02-01 00:03:37 +11:00
David Lechner 3e1bbeabaf py/modthread: Fix spelling error in comment. 2020-01-31 23:57:25 +11:00
Damien George e3ff52863b esp8266/modules/ntptime.py: Add comment about configuring NTP host.
The ability to change the host is a frequently requested feature, so
explicitly document how it can be achieved using the existing code.

See issues #2121, #4385, #4622, #5122, #5536.
2020-01-31 23:54:11 +11:00
Damien George af88e70414 stm32/powerctrl: Reenable PLL3 on H7 MCUs when waking from stop mode.
So that USB can work.
2020-01-31 23:25:18 +11:00
Damien George 2c8c2b935e stm32/powerctrl: Improve support for changing system freq on H7 MCUs.
This commit improves pllvalues.py to generate PLL values for H7 MCUs that
are valid (VCO in and out are in range) and extend for the entire range of
SYSCLK values up to 400MHz (up to 480MHz is currently unsupported).
2020-01-31 23:25:18 +11:00
Damien George 03b73ce329 stm32/stm32_it: Don't call __HAL_USB_HS_EXTI_CLEAR_FLAG on H7 MCUs.
It doesn't exist on these MCUs.
2020-01-31 23:25:18 +11:00
Damien George 257b17ec10 stm32/sdio: Add support for H7 MCUs.
The cyw43 driver on stm32 will now work with H7 MCUs.
2020-01-31 23:25:18 +11:00
Damien George d494e47855 drivers/cyw43: Return early from cyw43_wifi_set_up if wifi_on fails. 2020-01-31 20:46:35 +11:00
Damien George 5de55e8fb4 drivers/cyw43: Include stdio.h in files that use printf. 2020-01-31 20:46:10 +11:00
Damien George 31ba06ce84 stm32/boards/stm32f746_af.csv: Add ADC alt functions to correct pins. 2020-01-30 16:31:11 +11:00
Damien George 68db7e01d8 stm32/powerctrl: Enable overdrive on F7 when waking from stop mode.
Because if the SYSCLK is set to 180MHz or higher it will require this to be
on already.
2020-01-30 16:30:03 +11:00
Damien George 29b84ea798 stm32/powerctrl: Disable HSI if not needed to save a bit of power. 2020-01-30 16:29:45 +11:00
Nicko van Someren c96a2f636b tests/basics: Expand test cases for equality of subclasses. 2020-01-30 14:53:07 +11:00
Nicko van Someren 3aab54bf43 py: Support non-boolean results for equality and inequality tests.
This commit implements a more complete replication of CPython's behaviour
for equality and inequality testing of objects.  This addresses the issues
discussed in #5382 and a few other inconsistencies.  Improvements over the
old code include:

- Support for returning non-boolean results from comparisons (as used by
  numpy and others).
- Support for non-reflexive equality tests.
- Preferential use of __ne__ methods and MP_BINARY_OP_NOT_EQUAL binary
  operators for inequality tests, when available.
- Fallback to op2 == op1 or op2 != op1 when op1 does not implement the
  (in)equality operators.

The scheme here makes use of a new flag, MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST,
in the flags word of mp_obj_type_t to indicate if various shortcuts can or
cannot be used when performing equality and inequality tests.  Currently
four built-in classes have the flag set: float and complex are
non-reflexive (since nan != nan) while bytearray and frozenszet instances
can equal other builtin class instances (bytes and set respectively).  The
flag is also set for any new class defined by the user.

This commit also includes a more comprehensive set of tests for the
behaviour of (in)equality operators implemented in special methods.
2020-01-30 14:53:07 +11:00
Damien George c3450effd4 py/objtype: Make mp_obj_type_t.flags constants public, moved to obj.h. 2020-01-30 14:53:07 +11:00
Damien George 96a4435be1 stm32/boards/STM32F769DISC: Add config to use external SPI as filesys.
This board now has the following 3 build configurations:
- mboot + external QSPI in XIP mode + internal filesystem
- mboot + external QSPI with filesystem (the default)
- no mboot + external QSPI with filesystem
2020-01-30 14:40:38 +11:00
Damien George 7bb2bf965e stm32/Makefile: Allow a board's .mk file to add things to CFLAGS. 2020-01-30 14:39:46 +11:00
Andrew Leech 30501d3f54 drivers, stm32: Support SPI/QSPI flash chips over 16MB.
With a SPI flash that has more than 16MB, 32-bit addressing is required
rather than the standard 24-bit.  This commit adds support for 32-bit
addressing so that the SPI flash commands (read/write/erase) are selected
automatically depending on the size of the address being used at each
operation.
2020-01-30 13:18:38 +11:00
David Lechner b72cb0ca1b py/mpthread.h: Use strong type for mp_thread_set_state() argument.
This modifies the signature of mp_thread_set_state() to use
mp_state_thread_t* instead of void*.  This matches the return type of
mp_thread_get_state(), which returns the same value.

`struct _mp_state_thread_t;` had to be moved before
`#include <mpthreadport.h>` since the stm32 port uses it in its
mpthreadport.h file.
2020-01-29 17:10:32 +11:00
Damien George a542c6d7e0 stm32/powerctrl: For F7, allow PLLM!=HSE when setting PLLSAI to 48MHz.
PLLM is shared among all PLL blocks on F7 MCUs, and this calculation to
configure PLLSAI to have 48MHz on the P output previously assumed that PLLM
is equal to HSE (eg PLLM=25 for HSE=25MHz).  This commit relaxes this
assumption to allow other values of PLLM.
2020-01-29 16:49:13 +11:00
Jim Mussared c3095b37e9 py/nativeglue: Fix typo about where the native fun table enum is. 2020-01-27 13:22:19 +11:00
Jim Mussared 888ddb81dd py/emitnative: Stop after finding an unwind target.
The loop searches backwards for a target, but doesn't stop after finding
the first result, meaning that it'll always end up at the outermost
exception handler.
2020-01-27 13:22:03 +11:00
Jim Mussared 0de304e7da py/emitnative: Use NULL for pending exception (not None).
This previously made the native emitter incompatible with the bytecode
emitter, and mp_resume (and subsequently mp_obj_generator_resume) expects
the bytecode emitter behavior (i.e. throw==NULL).
2020-01-27 13:21:49 +11:00
Jim Mussared 1f4b607116 tests: Add tests for generator throw and yield-from with exc handlers.
This commit adds a generator test for throwing into a nested exception, and
one when using yield-from with a pending exception cleanup.  Both these
tests currently fail on the native emitter, and are simplified versions of
native test failures from uasyncio in #5332.
2020-01-27 13:16:06 +11:00
David Lechner d89ed3e62b unix/unix_mphal: Add compile check for incompatible GIL+ASYNC_KBD_INTR.
It is not safe to enable MICROPY_ASYNC_KBD_INTR and MICROPY_PY_THREAD_GIL
at the same time.  This will trigger a compiler error to ensure that it
is not possible to make this mistake.
2020-01-26 23:31:27 +11:00
David Lechner bc3499f010 windows/windows_mphal: Release GIL during system calls.
This releases the GIL during syscalls that could block.
2020-01-26 23:27:40 +11:00
David Lechner 62537a18e3 py: Release GIL during syscalls in reader and writer code.
This releases the GIL during POSIX system calls that could block.
2020-01-26 23:26:31 +11:00
David Lechner 35f66d38b8 extmod/vfs_posix: Release GIL during system calls.
This releases the GIL during syscalls that could block.
2020-01-26 23:26:14 +11:00
David Lechner fee7e5617f unix: Release GIL during all system calls.
Addition of GIL EXIT/ENTER pairs are:

- modos: release the GIL during system calls.  CPython does this as well.

- moduselect: release the GIL during the poll() syscall.  This call can be
  blocking, so it is important to allow other threads to run at this time.

- modusocket: release the GIL during system calls.  Many of these calls can
  be blocking, so it is important to allow other threads to run.

- unix_mphal: release the GIL during the read and write syscalls in
  mp_hal_stdin_rx_chr and mp_hal_stdout_tx_strn.  If we don't do this
  threads are blocked when the REPL or the builtin input function are used.

- file, main, mpconfigport.h: release GIL during syscalls in built-in
  functions that could block.
2020-01-26 23:21:29 +11:00
Damien George 96716b46e1 unix/Makefile: Reserve CFLAGS_EXTRA/LDFLAGS_EXTRA for external use.
When CFLAGS_EXTRA/LDFLAGS_EXTRA (or anything) is set on the command line of
a make invocation then it will completely override any setting or appending
of these variables in the makefile(s).  This means builds like the coverage
variant will have their mpconfigvariant.mk settings overridden.  Fix this
by using CFLAGS/LDFLAGS exclusively in the makefile(s), reserving the
CFLAGS_EXTRA/LDFLAGS_EXTRA variables for external command-line use only.
2020-01-24 11:51:21 +11:00
Yonatan Goldschmidt cb4472df42 tests: Add boolean-as-integer formatting tests for fixed regression.
As suggested by @dpgeorge in #5538.
2020-01-24 10:57:17 +11:00
Yonatan Goldschmidt 35e664d779 tests/unix: Add coverage tests for mp_obj_is_type() and variants. 2020-01-24 10:57:17 +11:00
Yonatan Goldschmidt d9433d3e94 py/obj.h: Add and use mp_obj_is_bool() helper.
Commit d96cfd13e3 introduced a regression in
testing for bool objects, that such objects were in some cases no longer
recognised and bools, eg when using mp_obj_is_type(o, &mp_type_bool), or
mp_obj_is_integer(o).

This commit fixes that problem by adding mp_obj_is_bool(o).  Builds with
MICROPY_OBJ_IMMEDIATE_OBJS enabled check if the object is any of the const
True or False objects.  Builds without it use the old method of ->type
checking, which compiles to smaller code (compared with the former
mentioned method).

Fixes #5538.
2020-01-24 10:53:45 +11:00
Damien George 27f41e624c tests/unix: Add coverage test for mp_obj_new_exception_args.
Because it's no longer called anywhere in the code.
2020-01-23 13:37:25 +11:00
Damien George e2c1226da4 py/objexcept: Optimise mp_obj_new_exception[_arg1/_args] functions.
This reduces code size by 10-70 bytes on all ports (except cc3200 which has
no change).
2020-01-23 13:37:25 +11:00
Damien George edc7a8bf1d py/objgenerator: Use mp_obj_new_exception_arg1 to make StopIteration. 2020-01-23 13:37:25 +11:00
David Lechner edbb73a411 py/qstr: Don't include or init qstr_mutex when GIL is enabled.
When threads and the GIL are enabled, then the qstr mutex is not needed.
The qstr_mutex field is never used in this case because of:

    #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
    #define QSTR_ENTER() mp_thread_mutex_lock(&MP_STATE_VM(qstr_mutex), 1)
    #define QSTR_EXIT() mp_thread_mutex_unlock(&MP_STATE_VM(qstr_mutex))
    #else
    #define QSTR_ENTER()
    #define QSTR_EXIT()
    #endif

So, we can completely remove qstr_mutex everywhere when MICROPY_PY_THREAD
&& !MICROPY_PY_THREAD_GIL.
2020-01-23 13:29:11 +11:00
David Lechner ccc18f047d py/gc: Don't include or init gc_mutex when GIL is enabled.
When threads and the GIL are enabled, then the GC mutex is not needed.  The
gc_mutex field is never used in this case because of:

    #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
    #define GC_ENTER() mp_thread_mutex_lock(&MP_STATE_MEM(gc_mutex), 1)
    #define GC_EXIT() mp_thread_mutex_unlock(&MP_STATE_MEM(gc_mutex))
    #else
    #define GC_ENTER()
    #define GC_EXIT()
    #endif

So, we can completely remove gc_mutex everywhere when MICROPY_PY_THREAD
&& !MICROPY_PY_THREAD_GIL.
2020-01-23 13:28:42 +11:00
c0rejump 6db5cede06 tools/pydfu.py: Clean up syntax, update comments and docstrings.
Some parts of code have been aligned to increase readability.  In general
'' instead of "" were used wherever possible to keep the same convention
for entire file.  Import inspect line has been moved to the top according
to hints reported by pep8 tools.  A few extra spaces were removed, a few
missing spaces were added.  Comments have been updated, mostly in
"read_dfu_file" function.  Some other comments have been capitalized and/or
slightly updated.  A few docstrings were fixed as well.  No real code
changes intended.
2020-01-23 13:23:12 +11:00
Damien George a11e306227 tools: Add metrics.py script to build and compute port sizes/metrics. 2020-01-23 12:48:52 +11:00
Damien George dccace6f3f tests/unix: Add coverage tests for pairheap data structure. 2020-01-22 17:31:18 +11:00
Damien George cfddc6a8c7 tests/extmod: Add basic machine.Timer test. 2020-01-22 17:31:18 +11:00
Damien George f70373c7b2 stm32/softtimer: Change linear linked list to a pairing heap. 2020-01-22 17:31:18 +11:00
Damien George fe203bb3e2 py/pairheap: Add generic implementation of pairing heap data structure. 2020-01-22 17:31:18 +11:00
stijn 599371b133 windows: Support word-based move/delete key sequences for REPL.
Translate common Ctrl-Left/Right/Delete/Backspace to the EMACS-style
sequences (i.e. Alt key based) for forward-word, backward-word, forwad-kill
and backward-kill.  Requires MICROPY_REPL_EMACS_WORDS_MOVE to be defined so
the readline implementation interprets these.
2020-01-22 16:54:19 +11:00
adzierzanowski a55c17dc69 esp32/modnetwork: Add max_clients kw-arg to WLAN.config for AP setting.
This allows the user to configure the maximum number of clients that are
connected to the access point.  Resolves #5125.
2020-01-22 16:43:25 +11:00
Peter Hinch 59746ac14a docs/library/uos.rst: Improve block devices section, and ioctl ret vals. 2020-01-22 16:37:31 +11:00
Thorsten von Eicken 5c5f93c1b8 tests: Make run-tests help and README be more descriptive of behaviour. 2020-01-22 16:35:24 +11:00
Jim Mussared 3032ae1155 esp32: Enable NimBLE support on all builds (IDF 3.3 and 4.0).
This commit updates the IDFv3 version to v3.3.1, and enables the
"ubluetooth" module by default on IDFv3 builds.
2020-01-15 00:24:43 +11:00
JensDiemer c14ff6194c esp8266/modules: Fix AttributeError in _boot.py if flash not formatted.
Prior to this commit, if the flash filesystem was not formatted then it
would error: "AttributeError: 'FlashBdev' object has no attribute 'mount'".
That is due to it not being able to detect the filesystem on the block
device and just trying to mount the block device directly.

This commit fixes the issue by just catching all exceptions.  Also it's not
needed to try the mount if `flashbdev.bdev` is None.
2020-01-14 23:53:49 +11:00
Memiks 4ab4bf3ec6 ports: Modify mp_hal_pin_write macro so it can be used as a function.
Even though it doesn't return anything it could still be used like a
function.  Addresses issue #5501.
2020-01-14 23:48:42 +11:00
Damien George 3448e69c2d tests/unix: Add coverage test for new mp_obj_int_get_uint_checked func. 2020-01-14 23:45:56 +11:00
Yonatan Goldschmidt 176ab99180 py/objint: Add mp_obj_int_get_uint_checked() helper.
Can be used where mp_obj_int_get_checked() will overflow due to the
sign-bit solely.  This returns an mp_uint_t, so it also verifies the given
integer is not negative.

Currently implemented only for mpz configurations.
2020-01-14 23:35:22 +11:00
Yonatan Goldschmidt 1c849d63a8 py/mpconfig.h: Define BITS_PER_BYTE only if not already defined.
It's a common macro that is possibly defined in headers of systems/SDKs
MicroPython is embedded into.
2020-01-12 20:57:01 +02:00
Damien George 40057600b8 py/obj: Optimise mp_obj_get_type for immediate objs with repr A and C.
This function is called often and with immediate objects enabled it has
more cases, so optimise it for speed.  With this optimisation the runtime
is now slightly faster with immediate objects enabled than with them
disabled.
2020-01-13 01:01:45 +11:00
Damien George d96cfd13e3 py/obj: Add MICROPY_OBJ_IMMEDIATE_OBJS option to reduce code size.
This option (enabled by default for object representation A, B, C) makes
None/False/True objects immediate objects, ie they are no longer a concrete
object in ROM but are rather just values, eg None=0x6 for representation A.

Doing this saves a considerable amount of code size, due to these objects
being widely used:

   bare-arm:  -392 -0.591%
minimal x86:  -252 -0.170% [incl +52(data)]
   unix x64:  -624 -0.125% [incl -128(data)]
unix nanbox:    +0 +0.000%
      stm32: -1940 -0.510% PYBV10
     cc3200: -1216 -0.659%
    esp8266:  -404 -0.062% GENERIC
      esp32:  -732 -0.064% GENERIC[incl +48(data)]
        nrf:  -988 -0.675% pca10040
       samd:  -564 -0.556% ADAFRUIT_ITSYBITSY_M4_EXPRESS

Thanks go to @Jongy aka Yonatan Goldschmidt for the idea.
2020-01-13 01:01:45 +11:00
Damien George 6f0c83f6e1 py/obj.h: Redefine qstr object encoding to add immediate obj encoding.
This commit adjusts the definition of qstr encoding in all object
representations by taking a single bit from the qstr space and using it to
distinguish between qstrs and a new kind of literal object: immediate
objects.  In other words, the qstr space is divided in two pieces, one half
for qstrs and the other half for immediate objects.

There is still enough room for qstr values (29 bits in representation A on
a 32-bit architecture, and 19 bits in representation C) and the new
immediate objects can be used for things like None, False and True.
2020-01-13 01:01:45 +11:00
Damien George ecdb30ea64 py/nativeglue: Use mp_const_X instead of &mp_const_X_obj. 2020-01-12 13:51:09 +11:00
Jason Neal 7ef2f65114 docs/library: Add / to indicate positional-only args in library docs.
Removes the confusion of positional-only arguments which have defaults that
look like keyword arguments.
2020-01-12 13:44:59 +11:00
Thorsten von Eicken 6632dd3981 esp32/modmachine: Add implementation of machine.soft_reset(). 2020-01-12 13:38:45 +11:00
Thorsten von Eicken 1caede927a docs/library/machine: Document machine.soft_reset() function. 2020-01-12 13:38:27 +11:00
David Lechner 339d0816c5 py/runtime: Move MICROPY_PORT_INIT_FUNC near the end of mp_init().
This moves the MICROPY_PORT_INIT_FUNC hook to the end of mp_init(), just
before MP_THREAD_GIL_ENTER(), so that everything (in particular the GIL
mutex) is intialized before the hook is called.  MICROPY_PORT_DEINIT_FUNC
is also moved to be symmetric (but there is no functional change there).

If a port needs to perform initialisation earlier than
MICROPY_PORT_INIT_FUNC then it can do it before calling mp_init().
2020-01-12 13:27:04 +11:00
Yonatan Goldschmidt 853aaa06f2 lib/mp-readline: Add word-based move/delete EMACS key sequences.
This commit adds backward-word, backward-kill-word, forward-word,
forward-kill-word sequences for the REPL, with bindings to Alt+F, Alt+B,
Alt+D and Alt+Backspace respectively.  It is disabled by default and can be
enabled via MICROPY_REPL_EMACS_WORDS_MOVE.

Further enabling MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE adds extra bindings
for these new sequences: Ctrl+Right, Ctrl+Left and Ctrl+W.

The features are enabled on unix micropython-coverage and micropython-dev.
2020-01-12 13:09:27 +11:00
Yonatan Goldschmidt dce590c29d lib/mp-readline: Add an assert() to catch buffer overflows.
During readline development, this function may receive bad `pos` values.
It's easier to understand the assert() failing error than to have a "stack
smashing detected" message.
2020-01-12 13:09:23 +11:00
Yonatan Goldschmidt df5c3bd976 py/unicode: Add unichar_isalnum(). 2020-01-12 13:03:57 +11:00
Thorsten von Eicken bc5c993adf docs/README: Add short paragraph about using readthedocs.
This adds a short paragraph on how to hook readthedocs.org up.  The main
goal is to make people aware of the option, to help with contributing to
the documentation.
2020-01-12 11:45:55 +11:00
Jim Mussared 977b532c8f unix: Rename unix binaries to micropython-variant (not _variant).
For consistency with mpy-cross, and other unix tools in general.
2020-01-12 10:37:40 +11:00
Jim Mussared 7319d546b7 travis: Update travis to specify which unix variant to build. 2020-01-12 10:37:33 +11:00
Jim Mussared 2357338e93 unix: Add placeholder DEV variant with settrace enabled.
This will eventually become the "full featured" unix binary with more
features enabled, specifically useful for development and testing.
2020-01-12 10:37:23 +11:00
Jim Mussared bd2fff6687 unix: Add build variants, analogous to boards on bare-metal.
Invoking "make" will still build the standard "micropython" executable, but
other variants are now build using, eg, "make VARIANT=minimal".  This
follows how bare-metal ports specify a particular board, and allows running
any make target (eg clean, test) with any variant.

Convenience targets (eg "make coverage") are provided to retain the old
behaviour, at least for now.

See issue #3043.
2020-01-12 10:34:23 +11:00
Jim Mussared 7d2ccd027f py/mkenv.mk: Move usage of 32-bit flags to py.mk.
This allows ports/variants to configure MICROPY_FORCE_32BIT after including
mkenv.mk, but before py.mk.
2020-01-12 10:34:10 +11:00
Damien George bfbd94401d py: Make mp_obj_get_type() return a const ptr to mp_obj_type_t.
Most types are in rodata/ROM, and mp_obj_base_t.type is a constant pointer,
so enforce this const-ness throughout the code base.  If a type ever needs
to be modified (eg a user type) then a simple cast can be used.
2020-01-09 11:25:26 +11:00
Damien George e3187b052f stm32/boards/PYBD: Change RTC asynch prediv from 1 to 4.
This change has the following effects:
- Reduces the resolution of the RTC sub-second counter from 30.52us to
  122.07us.
- Allows RTC.calibration() to now support positive values (as well as
  negative values).
- Reduces VBAT current consumption in standby mode by a small amount.

For general purpose use 122us resolution of the sub-second counter is
good enough, and the benefits of full range calibration and minor reduction
in VBAT consumption are worth the change.
2020-01-07 23:59:29 +11:00
stijn 54a2584de1 tests/unix: Make unix time test pass on more platforms.
As the mktime documentation for CPython states: "The earliest date for
which it can generate a time is platform-dependent".  In particular on
Windows this depends on the timezone so e.g. for UTC+2 the earliest is 2
hours past midnight January 1970.  So change the reference to the earliest
possible, for UTC+14.
2020-01-06 23:28:42 +11:00
Damien George 4d528bbaa8 tests/cpydiff: Add CPy diff-test for using dict.keys() as a set.
See issue #5493.
2020-01-06 23:26:00 +11:00
Damien George 99b8c1a937 esp32/Makefile: Assign result of $call to dummy var for older make.
Make version 4.1 and lower does not allow $call as the main expression on a
line, so assign the result of the $call to a dummy variable.

Fixes issue #5426.
2020-01-06 23:03:22 +11:00
Jason Neal 5ef3b6b2d9 docs/library/machine.UART.rst: Detail timeout behaviour of read methods.
Also document existence of "invert" argument to constructor.
2020-01-06 22:50:58 +11:00
Jason Neal 99ed431d28 docs/library/machine.I2C.rst: Use positional-only arguments syntax.
Addresses issue #5196.
2020-01-06 22:25:35 +11:00
David Lechner 1bc9fc8082 tests/run-tests: Handle 'CRASH' return by float.py feature test.
It is possile for `run_feature_check(pyb, args, base_path, 'float.py')` to
return `b'CRASH'`.  This causes an unhandled exception in `int()`.

This commit fixes the problem by first testing for `b'CRASH'` before trying
to convert the return value to an integer.
2020-01-06 22:22:27 +11:00
Jason Neal aec88ddf03 docs: More consistent capitalization and use of articles in headings.
See issue #3188.
2020-01-06 22:17:29 +11:00
Jason Neal de78a9e317 tools/gen-cpydiff.py: Adjust subsections to sentence case. 2020-01-06 22:16:18 +11:00
Nicko van Someren 10709846f3 py/objslice: Inline fetching of slice paramters in str_subscr().
To reduce code size.
2019-12-29 00:06:02 +11:00
Nicko van Someren 4c93955b7b py/objslice: Add support for indices() method on slice objects.
Instances of the slice class are passed to __getitem__() on objects when
the user indexes them with a slice.  In practice the majority of the time
(other than passing it on untouched) is to work out what the slice means in
the context of an array dimension of a particular length.  Since Python 2.3
there has been a method on the slice class, indices(), that takes a
dimension length and returns the real start, stop and step, accounting for
missing or negative values in the slice spec.  This commit implements such
a indices() method on the slice class.

It is configurable at compile-time via MICROPY_PY_BUILTINS_SLICE_INDICES,
disabled by default, enabled on unix, stm32 and esp32 ports.

This commit also adds new tests for slice indices and for slicing unicode
strings.
2019-12-28 23:55:15 +11:00
Tim Gates 007a704d82 nrf/examples: Fix typo in mountsd.py, wireing -> wiring. 2019-12-28 12:07:30 +11:00
Damien George 269c9a08b6 unix/modos: Add uos.rename and uos.rmdir.
The existing uos.remove cannot be used to remove directories, instead
uos.rmdir is needed.  And also provide uos.rename to get a good set of
filesystem functionality without requiring additional Python-level os
functions (eg using ffi).
2019-12-28 11:54:49 +11:00
Andrew Leech 1b844e908c unix/modtime: Add utime.mktime function, to complement utime.localtime.
This also adds it to the windows port.
2019-12-28 11:11:54 +11:00
Damien George b23bd6433c py: Clean up commented-out code and comments about exception hierarchy.
In CPython, EnvironmentError and IOError are now aliases of OSError so no
need to have them listed in the code.  OverflowError inherits from
ArithmeticError because it's intended to be raised "when the result of an
arithmetic operation is too large to be represented" (per CPython docs),
and MicroPython aims to match the CPython exception hierarchy.
2019-12-28 01:01:36 +11:00
Yonatan Goldschmidt b2e4a57289 nrf/main: Remove unnecessary repl_info(0) call.
It's statically initialized to 0.
2019-12-28 00:08:31 +11:00
Yonatan Goldschmidt 61d2b40ad5 lib/utils/pyexec: Introduce MICROPY_REPL_INFO, wrap debug prints in it.
For the 3 ports that already make use of this feature (stm32, nrf and
teensy) this doesn't make any difference, it just allows to disable it from
now on.

For other ports that use pyexec, this decreases code size because the debug
printing code is dead (it can't be enabled) but the compiler can't deduce
that, so code is still emitted.
2019-12-28 00:05:39 +11:00
Yonatan Goldschmidt aca8873bb8 extmod/modbluetooth: Fix func prototype, empty args should be (void).
This fixes a -Wstrict-prototypes error.
2019-12-27 23:57:46 +11:00
David Lechner e79424d672 ports: Allow overriding CROSS_COMPILE in a custom makefile.
Many ports already allow overriding CROSS_COMPILE.  This modifies the
remaining ports to allow it as well.
2019-12-27 23:53:16 +11:00
Damien George d56bc6e03d py/obj.h: Use 32-bit shift in MP_OBJ_NEW_QSTR calc for obj-repr D.
The qst value is always small enough to fit in 31-bits (even less) and
using a 32-bit shift rather than a 64-bit shift reduces code size by about
300 bytes.
2019-12-27 23:33:34 +11:00
Damien George 4c0176d13f py/objstr: Don't use inline GET_STR_DATA_LEN for object-repr D.
Changing to use the helper function mp_obj_str_get_data_no_check() reduces
code size of nan-boxing builds by about 1000 bytes.
2019-12-27 23:15:52 +11:00
Damien George e83ab7374b travis: Add stm32 build in nanbox mode. 2019-12-27 22:54:53 +11:00
Damien George 93509ac8c7 stm32: Add configuration to build in nanbox mode.
Most stm32 boards can now be built in nan-boxing mode via:

    $ make NANBOX=1

Note that if float is enabled then it will be forced to double-precision.
Also, native emitters will be disabled.
2019-12-27 22:54:53 +11:00
Damien George d980d51807 stm32: Fix to build in nanbox mode. 2019-12-27 22:54:53 +11:00
Damien George e83fc3260e drivers/cyw43: Fix to build in nanbox mode. 2019-12-27 22:54:53 +11:00
Damien George 6f872f81d6 extmod: Fix modbluetooth and modwebrepl to build in nanbox mode. 2019-12-27 22:54:53 +11:00
Damien George 1f499ad2fe py/objobject: Fix __setattr__/__delattr__ to build in nanbox mode. 2019-12-27 22:54:53 +11:00
Damien George d97b40bdaa py: Introduce MP_ROM_FALSE/MP_ROM_TRUE for ROM to refer to bool objects.
This helps to prevent mistakes, and allows easily changing the ROM value of
False/True if needed.
2019-12-27 22:54:20 +11:00
Damien George 09376f0e47 py: Introduce MP_ROM_NONE macro for ROM to refer to None object.
This helps to prevent mistakes, and allows easily changing the ROM value of
None if needed.
2019-12-27 22:51:17 +11:00
Damien George f5eec903fa py/objsingleton: Use mp_generic_unary_op for singleton objects.
So these types more closely match NoneType, eg they can be hashed, like in
CPython.
2019-12-27 12:53:36 +11:00
Damien George de8c04317b tests/micropython: Add test for yield-from while heap is locked. 2019-12-27 12:34:22 +11:00
Damien George aacd618939 py/runtime: Don't allocate iter buf for user-defined types.
A user-defined type that defines __iter__ doesn't need any memory to be
pre-allocated for its iterator (because it can't use such memory).  So
optimise for this case by not allocating the iter-buf.
2019-12-27 12:34:22 +11:00
Damien George 11b4524b39 travis: Add new job to build and test unix coverage in 32-bit mode. 2019-12-27 12:30:51 +11:00
Damien George 99a04b8060 tests/extmod: Split out VfsFat finaliser tests to separate test file.
It tests independent functionality and may need to be skipped for a given
port.
2019-12-27 12:30:51 +11:00
Damien George 865827ed8e tests/run-tests: Add "--mpy-cross-flags" arg to specify mpy-cross flags. 2019-12-27 12:30:51 +11:00
Damien George ab75210e33 py/asmx86: Remove unused 5th argument facility.
In commit 71a3d6ec3b mp_setup_code_state was
changed from a 5-arg function to a 4-arg function, and at that point 5-arg
calls in native code were no longer needed.  See also commit
4f9842ad80.
2019-12-27 12:30:51 +11:00
Damien George b97fb683d0 py/asmx86: Fix stack to be 16-byte aligned for entry and sub-call. 2019-12-27 12:30:51 +11:00
Damien George ed2be79b49 extmod/uzlib: Explicitly cast ptr-diff-expr to unsigned.
The struct member "dest" should never be less than "destStart", so their
difference is never negative.  Cast as such to make the comparison
explicitly unsigned, ensuring the compiler produces the correct comparison
instruction, and avoiding any compiler warnings.
2019-12-23 00:07:03 +11:00
Damien George 300eb65ae7 py/nlrx86: Silence possible warnings about unused nlr argument. 2019-12-23 00:07:03 +11:00
Yonatan Goldschmidt 42e45bd694 py/objobject: Add object.__delattr__ function.
Similar to object.__setattr__.
2019-12-21 00:14:22 +11:00
Yonatan Goldschmidt 07ccb5588c py/objobject: Add object.__setattr__ function.
Allows assigning attributes on class instances that implement their own
__setattr__.  Both object.__setattr__ and super(A, b).__setattr__ will work
with this commit.
2019-12-21 00:12:08 +11:00
Jim Mussared 90f286465b stm32/mbedtls: Resize mbedtls output buffer from 16 down to 4 kiB.
To reduce the size of the SSL context on the heap.  See issue #5303.
2019-12-21 00:02:24 +11:00
Damien George 5e431188db py/obj.h: Remove comments about additional mp_buffer_info_t entries.
These entries are unlikely to be needed, so remove them to clean up the
struct definition.
2019-12-20 23:36:17 +11:00
Damien George 035180ca01 py: Remove commented-out debug printf's from emitbc and objlist.
Any debugging prints should use a macro like DEBUG_printf.
2019-12-20 23:34:46 +11:00
1812 changed files with 51388 additions and 19986 deletions

1
.github/FUNDING.yml vendored 100644
View File

@ -0,0 +1 @@
github: micropython

18
.github/workflows/docs.yml vendored 100644
View File

@ -0,0 +1,18 @@
name: Build docs
on:
pull_request:
paths:
- docs/**
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v1
- name: Install Python packages
run: pip install Sphinx
- name: Build docs
run: make -C docs/ html

3
.gitignore vendored
View File

@ -27,8 +27,7 @@ build-*/
# Test failure outputs
######################
tests/*.exp
tests/*.out
tests/results/*
# Python cache files
######################

6
.gitmodules vendored
View File

@ -30,3 +30,9 @@
[submodule "lib/mynewt-nimble"]
path = lib/mynewt-nimble
url = https://github.com/apache/mynewt-nimble.git
[submodule "lib/btstack"]
path = lib/btstack
url = https://github.com/bluekitchen/btstack.git
[submodule "lib/nxp_driver"]
path = lib/nxp_driver
url = https://github.com/hathach/nxp_driver.git

View File

@ -18,49 +18,117 @@ stages:
- name: test
# define the jobs for the stages
# order of the jobs has longest running first to optimise total time
# approx order of the jobs has longest running first to optimise total time
jobs:
include:
# check code formatting
- stage: test
os: linux
dist: bionic
name: "code formatting"
before_install:
- sudo apt-add-repository --yes --update ppa:pybricks/ppa
install:
- sudo apt-get install uncrustify python3-pip
- uncrustify --version
- pip3 install --user setuptools
- pip3 install --user black
- black --version
script:
- tools/codeformat.py
- git diff --exit-code
# zephyr port
- stage: test
name: "zephyr port build"
services:
- docker
before_install:
- docker pull zephyrprojectrtos/ci:v0.11.8
- >
docker run --name zephyr-ci -d -it
-v "$(pwd)":/micropython
-e ZEPHYR_SDK_INSTALL_DIR=/opt/sdk/zephyr-sdk-0.11.3
-e ZEPHYR_TOOLCHAIN_VARIANT=zephyr
-w /micropython/ports/zephyr
zephyrprojectrtos/ci:v0.11.8
- docker ps -a
install:
- docker exec zephyr-ci west init --mr v2.4.0 /zephyrproject
- docker exec -w /zephyrproject zephyr-ci west update
- docker exec -w /zephyrproject zephyr-ci west zephyr-export
script:
- docker exec zephyr-ci bash -c "make clean; ./make-minimal ${MAKEOPTS}"
- docker exec zephyr-ci bash -c "make clean; ./make-minimal ${MAKEOPTS} BOARD=frdm_k64f"
- docker exec zephyr-ci bash -c "make clean; make ${MAKEOPTS}"
- docker exec zephyr-ci bash -c "make clean; make ${MAKEOPTS} BOARD=frdm_k64f"
- docker exec zephyr-ci bash -c "make clean; make ${MAKEOPTS} BOARD=mimxrt1050_evk"
- docker exec zephyr-ci bash -c "make clean; make ${MAKEOPTS} BOARD=reel_board"
# unix port on OSX (first in list because the build VM takes a long time to start)
- stage: test
os: osx
osx_image: xcode11.3
name: "unix port build with clang on OSX"
env:
- PKG_CONFIG_PATH=/usr/local/opt/libffi/lib/pkgconfig
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/unix submodules
- make ${MAKEOPTS} -C ports/unix deplibs
- make ${MAKEOPTS} -C ports/unix
# OSX has poor time resolution and the following tests do not have the correct output
- (cd tests && ./run-tests --exclude 'uasyncio_(basic|heaplock|lock|wait_task)')
# check for additional compiler errors/warnings
- make ${MAKEOPTS} -C ports/unix VARIANT=coverage submodules
- make ${MAKEOPTS} -C ports/unix VARIANT=coverage
after_failure:
- tests/run-tests --print-failures
# stm32 port
- stage: test
env: NAME="stm32 port build"
name: "stm32 port build"
install:
# need newer gcc version for Cortex-M7 support
- sudo add-apt-repository -y ppa:team-gcc-arm-embedded/ppa
- sudo apt-get update -qq || true
- sudo apt-get install gcc-arm-embedded
- sudo apt-get install libnewlib-arm-none-eabi
- sudo apt-get install gcc-arm-embedded libnewlib-arm-none-eabi
- arm-none-eabi-gcc --version
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/stm32 submodules
- git submodule update --init lib/btstack
- make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_F091RC
- make ${MAKEOPTS} -C ports/stm32 BOARD=PYBV11 MICROPY_PY_WIZNET5K=5200 MICROPY_PY_CC3K=1
- make ${MAKEOPTS} -C ports/stm32 BOARD=PYBV11 MICROPY_PY_WIZNET5K=5200 MICROPY_PY_CC3K=1 USER_C_MODULES=../../examples/usercmodule CFLAGS_EXTRA="-DMODULE_CEXAMPLE_ENABLED=1 -DMODULE_CPPEXAMPLE_ENABLED=1"
- make ${MAKEOPTS} -C ports/stm32 BOARD=PYBD_SF2
- make ${MAKEOPTS} -C ports/stm32 BOARD=PYBD_SF6 NANBOX=1 MICROPY_BLUETOOTH_NIMBLE=0 MICROPY_BLUETOOTH_BTSTACK=1
- make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_H743ZI CFLAGS_EXTRA='-DMICROPY_PY_THREAD=1'
- make ${MAKEOPTS} -C ports/stm32 BOARD=B_L072Z_LRWAN1
- make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_L073RZ
- make ${MAKEOPTS} -C ports/stm32 BOARD=STM32L476DISC
- make ${MAKEOPTS} -C ports/stm32 BOARD=NUCLEO_WB55
- make ${MAKEOPTS} -C ports/stm32/mboot BOARD=PYBV10 CFLAGS_EXTRA='-DMBOOT_FSLOAD=1 -DMBOOT_VFS_LFS2=1'
- make ${MAKEOPTS} -C ports/stm32/mboot BOARD=PYBD_SF6
- make ${MAKEOPTS} -C ports/stm32/mboot BOARD=NUCLEO_WB55
# qemu-arm port
- stage: test
env: NAME="qemu-arm port build and tests"
dist: bionic # needed for more recent version of qemu-system-arm with mps2-an385 target
name: "qemu-arm port build and tests"
install:
- sudo apt-get install gcc-arm-none-eabi
- sudo apt-get install libnewlib-arm-none-eabi
- sudo apt-get install qemu-system
- sudo apt-get install gcc-arm-none-eabi libnewlib-arm-none-eabi qemu-system
- arm-none-eabi-gcc --version
- qemu-system-arm --version
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/qemu-arm CFLAGS_EXTRA=-DMP_ENDIANNESS_BIG=1
- make ${MAKEOPTS} -C ports/qemu-arm clean
- make ${MAKEOPTS} -C ports/qemu-arm -f Makefile.test test
after_failure:
- grep "FAIL" ports/qemu-arm/build/console.out
- grep --text "FAIL" ports/qemu-arm/build/console.out
# unix coverage
- stage: test
env: NAME="unix coverage build and tests"
name: "unix coverage build and tests"
install:
- sudo apt-get install python3-pip
- sudo pip install cpp-coveralls
@ -70,17 +138,12 @@ jobs:
- python3 --version
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/unix submodules
- make ${MAKEOPTS} -C ports/unix deplibs
- make ${MAKEOPTS} -C ports/unix coverage
- make ${MAKEOPTS} -C ports/unix VARIANT=coverage submodules
- make ${MAKEOPTS} -C ports/unix VARIANT=coverage deplibs
- make ${MAKEOPTS} -C ports/unix VARIANT=coverage
# run the main test suite
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests)
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests -d thread)
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests --emit native)
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests --via-mpy -d basics float micropython)
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests --via-mpy --emit native -d basics float micropython)
# test when input script comes from stdin
- cat tests/basics/0prelim.py | ports/unix/micropython_coverage | grep -q 'abc'
- make -C ports/unix VARIANT=coverage test_full
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython-coverage ./run-multitests.py multi_net/*.py) || travis_terminate 1
# test building native mpy modules
- make -C examples/natmod/features1 ARCH=x64
- make -C examples/natmod/features2 ARCH=x64
@ -91,16 +154,48 @@ jobs:
- make -C examples/natmod/ure ARCH=x64
- make -C examples/natmod/uzlib ARCH=x64
# test importing .mpy generated by mpy_ld.py
- MICROPYPATH=examples/natmod/features2 ./ports/unix/micropython_coverage -m features2
- MICROPYPATH=examples/natmod/features2 ./ports/unix/micropython-coverage -m features2
- (cd tests && ./run-natmodtests.py extmod/{btree*,framebuf*,uheapq*,ure*,uzlib*}.py)
# run coveralls coverage analysis (try to, even if some builds/tests failed)
- (cd ports/unix && coveralls --root ../.. --build-root . --gcov $(which gcov) --gcov-options '\-o build-coverage/' --include py --include extmod)
after_failure:
- (cd tests && for exp in *.exp; do testbase=$(basename $exp .exp); echo -e "\nFAILURE $testbase"; diff -u $testbase.exp $testbase.out; done)
- tests/run-tests --print-failures
# unix coverage 32-bit
- stage: test
name: "unix coverage 32-bit build and tests"
install:
- sudo apt-get install gcc-multilib g++-multilib libffi-dev:i386
- sudo apt-get install python3-pip
- sudo pip3 install setuptools
- sudo pip3 install pyelftools
- gcc --version
- python3 --version
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/unix MICROPY_FORCE_32BIT=1 VARIANT=coverage submodules
- make ${MAKEOPTS} -C ports/unix MICROPY_FORCE_32BIT=1 VARIANT=coverage deplibs
- make ${MAKEOPTS} -C ports/unix MICROPY_FORCE_32BIT=1 VARIANT=coverage
# run the main test suite
- make -C ports/unix MICROPY_FORCE_32BIT=1 VARIANT=coverage test_full || travis_terminate 1
# test building native mpy modules
- make -C examples/natmod/features1 ARCH=x86
- make -C examples/natmod/features2 ARCH=x86
- make -C examples/natmod/btree ARCH=x86
- make -C examples/natmod/framebuf ARCH=x86
- make -C examples/natmod/uheapq ARCH=x86
- make -C examples/natmod/urandom ARCH=x86
- make -C examples/natmod/ure ARCH=x86
- make -C examples/natmod/uzlib ARCH=x86
# test importing .mpy generated by mpy_ld.py
- MICROPYPATH=examples/natmod/features2 ./ports/unix/micropython-coverage -m features2
- (cd tests && ./run-natmodtests.py --arch x86 extmod/{btree*,framebuf*,uheapq*,ure*,uzlib*}.py)
after_failure:
- tests/run-tests --print-failures
# standard unix port
- stage: test
env: NAME="unix port build and tests"
name: "unix port build and tests"
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/unix submodules
@ -108,79 +203,100 @@ jobs:
- make ${MAKEOPTS} -C ports/unix
- make ${MAKEOPTS} -C ports/unix test
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython ./run-perfbench.py 1000 1000)
after_failure:
- tests/run-tests --print-failures
# unix nanbox (and using Python 2 to check it can run the build scripts)
# unix nanbox/float (and using Python 2 to check it can run the build scripts)
- stage: test
env: NAME="unix nanbox port build and tests"
name: "unix nanbox/float port build and tests"
install:
- sudo apt-get install gcc-multilib libffi-dev:i386
script:
- make ${MAKEOPTS} -C mpy-cross PYTHON=python2
- make ${MAKEOPTS} -C ports/unix submodules
- make ${MAKEOPTS} -C ports/unix PYTHON=python2 deplibs
- make ${MAKEOPTS} -C ports/unix PYTHON=python2 nanbox
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython_nanbox ./run-tests)
- make ${MAKEOPTS} -C ports/unix VARIANT=nanbox submodules
- make ${MAKEOPTS} -C ports/unix PYTHON=python2 VARIANT=nanbox deplibs
- make ${MAKEOPTS} -C ports/unix PYTHON=python2 VARIANT=nanbox
- make ${MAKEOPTS} -C ports/unix PYTHON=python2 VARIANT=nanbox test_full || travis_terminate 1
- make ${MAKEOPTS} -C ports/unix clean
- make ${MAKEOPTS} -C ports/unix CFLAGS_EXTRA="-DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT"
- make ${MAKEOPTS} -C ports/unix test
after_failure:
- tests/run-tests --print-failures
# unix stackless
# unix stackless/float with clang
- stage: test
env: NAME="unix stackless port build and tests with clang"
name: "unix stackless/float port build and tests with clang"
install:
- sudo apt-get install clang
script:
- make ${MAKEOPTS} -C mpy-cross CC=clang
- make ${MAKEOPTS} -C ports/unix submodules
- make ${MAKEOPTS} -C ports/unix CC=clang CFLAGS_EXTRA="-DMICROPY_STACKLESS=1 -DMICROPY_STACKLESS_STRICT=1"
- make ${MAKEOPTS} -C ports/unix CC=clang test || travis_terminate 1
- make ${MAKEOPTS} -C ports/unix clean
- make ${MAKEOPTS} -C ports/unix CC=clang CFLAGS_EXTRA="-DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT"
- make ${MAKEOPTS} -C ports/unix CC=clang test
after_failure:
- tests/run-tests --print-failures
# unix with sys.settrace
- stage: test
env: NAME="unix port with sys.settrace build and tests"
name: "unix port with sys.settrace build and tests"
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/unix MICROPY_PY_BTREE=0 MICROPY_PY_FFI=0 MICROPY_PY_USSL=0 CFLAGS_EXTRA="-DMICROPY_PY_SYS_SETTRACE=1" test
- make ${MAKEOPTS} -C ports/unix MICROPY_PY_BTREE=0 MICROPY_PY_FFI=0 MICROPY_PY_USSL=0 CFLAGS_EXTRA="-DMICROPY_PY_SYS_SETTRACE=1" test || travis_terminate 1
- make ${MAKEOPTS} -C ports/unix clean
- make ${MAKEOPTS} -C ports/unix MICROPY_PY_BTREE=0 MICROPY_PY_FFI=0 MICROPY_PY_USSL=0 CFLAGS_EXTRA="-DMICROPY_STACKLESS=1 -DMICROPY_STACKLESS_STRICT=1 -DMICROPY_PY_SYS_SETTRACE=1" test
after_failure:
- (cd tests && for exp in *.exp; do testbase=$(basename $exp .exp); echo -e "\nFAILURE $testbase"; diff -u $testbase.exp $testbase.out; done)
- tests/run-tests --print-failures
# minimal unix port with tests
- stage: test
env: NAME="minimal unix port build and tests"
name: "minimal unix port build and tests"
script:
- make ${MAKEOPTS} -C ports/unix minimal
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython_minimal ./run-tests -e exception_chain -e self_type_check -e subclass_native_init -d basics)
- make ${MAKEOPTS} -C ports/unix VARIANT=minimal
- (cd tests && MICROPY_CPYTHON3=python3 MICROPY_MICROPYTHON=../ports/unix/micropython-minimal ./run-tests -e exception_chain -e self_type_check -e subclass_native_init -d basics)
after_failure:
- tests/run-tests --print-failures
# windows port via mingw
- stage: test
env: NAME="windows port build via mingw"
name: "windows port build via mingw"
install:
- sudo apt-get install gcc-mingw-w64
script:
- make ${MAKEOPTS} -C mpy-cross
- make ${MAKEOPTS} -C ports/windows CROSS_COMPILE=i686-w64-mingw32-
# esp32 port
# esp32 w/ESP-IDFv3 port
- stage: test
env: NAME="esp32 port build"
name: "esp32 ESP-IDFv3 port build"
install:
- sudo apt-get install python3-pip
- sudo pip3 install 'pyparsing<2.4'
- wget https://dl.espressif.com/dl/xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz
- zcat xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz | tar x
- curl -L https://dl.espressif.com/dl/xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz | tar zxf -
- export PATH=$(pwd)/xtensa-esp32-elf/bin:$PATH
- git clone https://github.com/espressif/esp-idf.git
- export IDF_PATH=$(pwd)/esp-idf
script:
- make ${MAKEOPTS} -C mpy-cross
# IDF v3 build
- git -C esp-idf checkout $(grep "ESPIDF_SUPHASH_V3 :=" ports/esp32/Makefile | cut -d " " -f 3)
- git -C esp-idf submodule update --init components/json/cJSON components/esp32/lib components/esptool_py/esptool components/expat/expat components/lwip/lwip components/mbedtls/mbedtls components/micro-ecc/micro-ecc components/nghttp/nghttp2
- git -C esp-idf submodule update --init components/json/cJSON components/esp32/lib components/esptool_py/esptool components/expat/expat components/lwip/lwip components/mbedtls/mbedtls components/micro-ecc/micro-ecc components/nghttp/nghttp2 components/nimble components/bt
- make ${MAKEOPTS} -C ports/esp32 submodules
- make ${MAKEOPTS} -C ports/esp32
# clean
- git -C esp-idf clean -f -f -d components/json/cJSON components/esp32/lib components/expat/expat components/micro-ecc/micro-ecc components/nghttp/nghttp2
- make ${MAKEOPTS} -C ports/esp32 clean
# IDF v4 build
# esp32 w/ESP-IDFv4 port
- stage: test
name: "esp32 ESP-IDFv4 port build"
install:
- sudo apt-get install python3-pip
- sudo pip3 install 'pyparsing<2.4'
- curl -L https://dl.espressif.com/dl/xtensa-esp32-elf-gcc8_2_0-esp-2019r2-linux-amd64.tar.gz | tar zxf -
- export PATH=$(pwd)/xtensa-esp32-elf/bin:$PATH
- git clone https://github.com/espressif/esp-idf.git
- export IDF_PATH=$(pwd)/esp-idf
script:
- make ${MAKEOPTS} -C mpy-cross
- git -C esp-idf checkout $(grep "ESPIDF_SUPHASH_V4 :=" ports/esp32/Makefile | cut -d " " -f 3)
- git -C esp-idf submodule update --init components/bt/controller/lib components/bt/host/nimble/nimble components/esp_wifi/lib_esp32 components/esptool_py/esptool components/lwip/lwip components/mbedtls/mbedtls
- make ${MAKEOPTS} -C ports/esp32 submodules
@ -188,7 +304,7 @@ jobs:
# esp8266 port
- stage: test
env: NAME="esp8266 port build"
name: "esp8266 port build"
install:
- wget https://github.com/jepler/esp-open-sdk/releases/download/2018-06-10/xtensa-lx106-elf-standalone.tar.gz
- zcat xtensa-lx106-elf-standalone.tar.gz | tar x
@ -198,68 +314,83 @@ jobs:
- make ${MAKEOPTS} -C ports/esp8266 submodules
- make ${MAKEOPTS} -C ports/esp8266
- make ${MAKEOPTS} -C ports/esp8266 BOARD=GENERIC_512K
- make ${MAKEOPTS} -C ports/esp8266 BOARD=GENERIC_1M
# nrf port
- stage: test
env: NAME="nrf port build"
name: "nrf port build"
install:
- sudo apt-get install gcc-arm-none-eabi
# need newer gcc version for Cortex-M33 support
- sudo add-apt-repository -y ppa:team-gcc-arm-embedded/ppa
- sudo apt-get update -qq || true
- sudo apt-get install gcc-arm-embedded
- sudo apt-get install libnewlib-arm-none-eabi
- arm-none-eabi-gcc --version
script:
- ports/nrf/drivers/bluetooth/download_ble_stack.sh s140_nrf52_6_1_1
- make ${MAKEOPTS} -C ports/nrf submodules
- make ${MAKEOPTS} -C ports/nrf
- make ${MAKEOPTS} -C ports/nrf BOARD=pca10040
- make ${MAKEOPTS} -C ports/nrf BOARD=microbit
- make ${MAKEOPTS} -C ports/nrf BOARD=pca10056 SD=s140
- make ${MAKEOPTS} -C ports/nrf BOARD=pca10090
# bare-arm and minimal ports
# bare-arm and minimal ports, with size-diff check
- stage: test
env: NAME="bare-arm and minimal ports build"
name: "bare-arm and minimal ports build and size-diff check"
install:
- sudo apt-get install gcc-arm-none-eabi
- sudo apt-get install libnewlib-arm-none-eabi
- sudo apt-get install gcc-multilib libffi-dev:i386 gcc-arm-none-eabi libnewlib-arm-none-eabi
- gcc --version
- arm-none-eabi-gcc --version
script:
- make ${MAKEOPTS} -C ports/bare-arm
- make ${MAKEOPTS} -C ports/minimal CROSS=1 build/firmware.bin
- ls -l ports/minimal/build/firmware.bin
- tools/check_code_size.sh
- mkdir -p ${HOME}/persist
# Save new firmware for reference, but only if building a main branch, not a pull request
- 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then cp ports/minimal/build/firmware.bin ${HOME}/persist/; fi'
# starts off at either the ref/pull/N/merge FETCH_HEAD, or the current branch HEAD
- git checkout -b pull_request # save the current location
- git remote add upstream https://github.com/micropython/micropython.git
- git fetch --depth=100 upstream
# build reference, save to size0
# ignore any errors with this build, in case master is failing
- git checkout `git merge-base --fork-point upstream/master pull_request`
- git show -s
- tools/metrics.py clean bm
- tools/metrics.py build bm | tee ~/size0 || true
# build PR/branch, save to size1
- git checkout pull_request
- git log upstream/master..HEAD
- tools/metrics.py clean bm
- tools/metrics.py build bm | tee ~/size1 || travis_terminate 1
# compute diff of the code sizes
- tools/metrics.py diff --error-threshold 0 ~/size0 ~/size1
# cc3200 port
- stage: test
env: NAME="cc3200 port build"
name: "cc3200 port build"
install:
- sudo apt-get install gcc-arm-none-eabi
- sudo apt-get install libnewlib-arm-none-eabi
- sudo apt-get install gcc-arm-none-eabi libnewlib-arm-none-eabi
script:
- make ${MAKEOPTS} -C ports/cc3200 BTARGET=application BTYPE=release
- make ${MAKEOPTS} -C ports/cc3200 BTARGET=bootloader BTYPE=release
# samd port
- stage: test
env: NAME="samd port build"
name: "samd port build"
install:
- sudo apt-get install gcc-arm-none-eabi
- sudo apt-get install libnewlib-arm-none-eabi
- sudo apt-get install gcc-arm-none-eabi libnewlib-arm-none-eabi
script:
- make ${MAKEOPTS} -C ports/samd submodules
- make ${MAKEOPTS} -C ports/samd
# teensy port
- stage: test
env: NAME="teensy port build"
name: "teensy port build"
install:
- sudo apt-get install gcc-arm-none-eabi
- sudo apt-get install libnewlib-arm-none-eabi
- sudo apt-get install gcc-arm-none-eabi libnewlib-arm-none-eabi
script:
- make ${MAKEOPTS} -C ports/teensy
# powerpc port
- stage: test
env: NAME="powerpc port build"
name: "powerpc port build"
install:
- sudo apt-get install gcc-powerpc64le-linux-gnu
- sudo apt-get install libc6-dev-ppc64el-cross
- sudo apt-get install gcc-powerpc64le-linux-gnu libc6-dev-ppc64el-cross
script:
- make ${MAKEOPTS} -C ports/powerpc CROSS_COMPILE=powerpc64le-linux-gnu-
- make ${MAKEOPTS} -C ports/powerpc UART=potato
- make ${MAKEOPTS} -C ports/powerpc UART=lpc_serial

View File

@ -11,7 +11,7 @@ It's also ok to drop file extensions.
Besides prefix, first line of a commit message should describe a
change clearly and to the point, and be a grammatical sentence with
final full stop. First line should fit within 78 characters. Examples
final full stop. First line should fit within 72 characters. Examples
of good first line of commit messages:
py/objstr: Add splitlines() method.
@ -19,16 +19,20 @@ of good first line of commit messages:
docs/machine: Fix typo in reset() description.
ports: Switch to use lib/foo instead of duplicated code.
After the first line, add an empty line and in following lines describe
a change in a detail, if needed. Any change beyond 5 lines would likely
require such detailed description.
After the first line add an empty line and in the following lines describe
the change in a detail, if needed, with lines fitting within 75 characters
(with an exception for long items like URLs which cannot be broken). Any
change beyond 5 lines would likely require such detailed description.
To get good practical examples of good commits and their messages, browse
the `git log` of the project.
MicroPython doesn't require explicit sign-off for patches ("Signed-off-by"
lines and similar). Instead, the commit message, and your name and email
address on it construes your sign-off of the following:
When committing you are encouraged to sign-off your commit by adding
"Signed-off-by" lines and similar, eg using "git commit -s". If you don't
explicitly sign-off in this way then the commit message, which includes your
name and email address in the "Author" line, implies your sign-off. In either
case, of explicit or implicit sign-off, you are certifying and signing off
against the following:
* That you wrote the change yourself, or took it from a project with
a compatible license (in the latter case the commit message, and possibly
@ -42,19 +46,35 @@ address on it construes your sign-off of the following:
copyright for your changes (for smaller changes, the commit message
conveys your copyright; if you make significant changes to a particular
source module, you're welcome to add your name to the file header).
* Your signature for all of the above, which is the 'Author' line in
the commit message, and which should include your full real name and
* Your contribution including commit message will be publicly and
indefinitely available for anyone to access, including redistribution
under the terms of the project's license.
* Your signature for all of the above, which is the "Signed-off-by" line
or the "Author" line in the commit message, includes your full real name and
a valid and active email address by which you can be contacted in the
foreseeable future.
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.
Python code conventions
=======================
Python code follows [PEP 8](http://legacy.python.org/dev/peps/pep-0008/).
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.
Naming conventions:
- Module names are short and all lowercase; eg pyb, stm.
- Class names are CamelCase, with abreviations all uppercase; eg I2C, not
- Class names are CamelCase, with abbreviations all uppercase; eg I2C, not
I2c.
- Function and method names are all lowercase with words separated by
a single underscore as necessary to improve readability; eg mem_read.
@ -64,7 +84,12 @@ Naming conventions:
C code conventions
==================
When writing new C code, please adhere to the following conventions.
C code is auto-formatted using [uncrustify](https://github.com/uncrustify/uncrustify)
and the corresponding configuration file `tools/uncrustify.cfg`, with a few
minor fix-ups applied by `tools/codeformat.py`. When writing new C code please
adhere to the existing style and use `tools/codeformat.py` to check any changes.
The main conventions, and things not enforceable via the auto-formatter, are
described below.
White space:
- Expand tabs to 4 spaces.
@ -125,7 +150,7 @@ Braces, spaces, names and comments:
foo(x + TO_ADD, some_value - 1);
}
for (int my_counter = 0; my_counter < x; my_counter++) {
for (int my_counter = 0; my_counter < x; ++my_counter) {
}
}

View File

@ -3,6 +3,6 @@ make sure that you are acquainted with Contributor Guidelines:
https://github.com/micropython/micropython/wiki/ContributorGuidelines
and Code Conventions:
as well as the Code Conventions, which includes details of how to commit:
https://github.com/micropython/micropython/blob/master/CODECONVENTIONS.md

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2013-2019 Damien P. George
Copyright (c) 2013-2020 Damien P. George
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,4 +1,4 @@
[![Build Status](https://travis-ci.org/micropython/micropython.png?branch=master)](https://travis-ci.org/micropython/micropython) [![Coverage Status](https://coveralls.io/repos/micropython/micropython/badge.png?branch=master)](https://coveralls.io/r/micropython/micropython?branch=master)
[![Build Status](https://travis-ci.com/micropython/micropython.png?branch=master)](https://travis-ci.com/micropython/micropython) [![Coverage Status](https://coveralls.io/repos/micropython/micropython/badge.png?branch=master)](https://coveralls.io/r/micropython/micropython?branch=master)
The MicroPython project
=======================
@ -99,7 +99,7 @@ Use `CTRL-D` (i.e. EOF) to exit the shell.
Learn about command-line options (in particular, how to increase heap size
which may be needed for larger applications):
$ ./micropython --help
$ ./micropython -h
Run complete testsuite:
@ -144,7 +144,7 @@ options (like cross-compiling), the same set of options should be passed
to `make deplibs`. To actually enable/disable use of dependencies, edit
`ports/unix/mpconfigport.mk` file, which has inline descriptions of the options.
For example, to build SSL module (required for `upip` tool described above,
and so enabled by dfeault), `MICROPY_PY_USSL` should be set to 1.
and so enabled by default), `MICROPY_PY_USSL` should be set to 1.
For some ports, building required dependences is transparent, and happens
automatically. But they still need to be fetched with the `make submodules`

View File

@ -3,7 +3,7 @@
# You can set these variables from the command line.
PYTHON = python3
SPHINXOPTS =
SPHINXOPTS = -W --keep-going
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build/$(MICROPY_PORT)

View File

@ -25,6 +25,21 @@ In `micropython/docs`, build the docs:
You'll find the index page at `micropython/docs/build/html/index.html`.
Having readthedocs.org build the documentation
----------------------------------------------
If you would like to have docs for forks/branches hosted on GitHub, GitLab or
BitBucket an alternative to building the docs locally is to sign up for a free
https://readthedocs.org account. The rough steps to follow are:
1. sign-up for an account, unless you already have one
2. in your account settings: add GitHub as a connected service (assuming
you have forked this repo on github)
3. in your account projects: import your forked/cloned micropython repository
into readthedocs
4. in the project's versions: add the branches you are developing on or
for which you'd like readthedocs to auto-generate docs whenever you
push a change
PDF manual generation
---------------------

View File

@ -66,7 +66,7 @@ master_doc = 'index'
# General information about the project.
project = 'MicroPython'
copyright = '2014-2019, Damien P. George, Paul Sokolovsky, and contributors'
copyright = '2014-2020, 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
@ -74,7 +74,7 @@ copyright = '2014-2019, Damien P. George, Paul Sokolovsky, and contributors'
#
# We don't follow "The short X.Y version" vs "The full version, including alpha/beta/rc tags"
# breakdown, so use the same version identifier for both to avoid confusion.
version = release = '1.12'
version = release = '1.13'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View File

@ -8,7 +8,8 @@ limitations with the Python environment, often due to an inability to access
certain hardware resources or Python speed limitations.
If your limitations can't be resolved with suggestions in :ref:`speed_python`,
writing some or all of your module in C is a viable option.
writing some or all of your module in C (and/or C++ if implemented for your port)
is a viable option.
If your module is designed to access or work with commonly available
hardware or libraries please consider implementing it inside the MicroPython
@ -29,7 +30,7 @@ Structure of an external C module
A MicroPython user C module is a directory with the following files:
* ``*.c`` and/or ``*.h`` source code files for your module.
* ``*.c`` / ``*.cpp`` / ``*.h`` source code files for your module.
These will typically include the low level functionality being implemented and
the MicroPython binding functions to expose the functions and module(s).
@ -44,137 +45,128 @@ A MicroPython user C module is a directory with the following files:
in your ``micropython.mk`` to a local make variable,
eg ``EXAMPLE_MOD_DIR := $(USERMOD_DIR)``
Your ``micropython.mk`` must add your modules C files relative to your
Your ``micropython.mk`` must add your modules source files relative to your
expanded copy of ``$(USERMOD_DIR)`` to ``SRC_USERMOD``, eg
``SRC_USERMOD += $(EXAMPLE_MOD_DIR)/example.c``
If you have custom ``CFLAGS`` settings or include folders to define, these
should be added to ``CFLAGS_USERMOD``.
If you have custom compiler options (like ``-I`` to add directories to search
for header files), these should be added to ``CFLAGS_USERMOD`` for C code
and to ``CXXFLAGS_USERMOD`` for C++ code.
See below for full usage example.
Basic Example
Basic example
-------------
This simple module named ``example`` provides a single function
``example.add_ints(a, b)`` which adds the two integer args together and returns
the result.
This simple module named ``cexample`` provides a single function
``cexample.add_ints(a, b)`` which adds the two integer args together and returns
the result. It can be found in the MicroPython source tree
`in the examples directory <https://github.com/micropython/micropython/tree/master/examples/usercmodule/cexample>`_
and has a source file and a Makefile fragment with content as descibed above::
Directory::
micropython/
└──examples/
└──usercmodule/
└──cexample/
├── examplemodule.c
└── micropython.mk
example/
├── example.c
└── micropython.mk
``example.c``
.. code-block:: c
// Include required definitions first.
#include "py/obj.h"
#include "py/runtime.h"
#include "py/builtin.h"
// This is the function which will be called from Python as example.add_ints(a, b).
STATIC mp_obj_t example_add_ints(mp_obj_t a_obj, mp_obj_t b_obj) {
// Extract the ints from the micropython input objects
int a = mp_obj_get_int(a_obj);
int b = mp_obj_get_int(b_obj);
// Calculate the addition and convert to MicroPython object.
return mp_obj_new_int(a + b);
}
// Define a Python reference to the function above
STATIC MP_DEFINE_CONST_FUN_OBJ_2(example_add_ints_obj, example_add_ints);
// Define all properties of the example module.
// Table entries are key/value pairs of the attribute name (a string)
// and the MicroPython object reference.
// All identifiers and strings are written as MP_QSTR_xxx and will be
// optimized to word-sized integers by the build system (interned strings).
STATIC const mp_rom_map_elem_t example_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_example) },
{ MP_ROM_QSTR(MP_QSTR_add_ints), MP_ROM_PTR(&example_add_ints_obj) },
};
STATIC MP_DEFINE_CONST_DICT(example_module_globals, example_module_globals_table);
// Define module object.
const mp_obj_module_t example_user_cmodule = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&example_module_globals,
};
// Register the module to make it available in Python
MP_REGISTER_MODULE(MP_QSTR_example, example_user_cmodule, MODULE_EXAMPLE_ENABLED);
``micropython.mk``
.. code-block:: make
EXAMPLE_MOD_DIR := $(USERMOD_DIR)
# Add all C files to SRC_USERMOD.
SRC_USERMOD += $(EXAMPLE_MOD_DIR)/example.c
# We can add our module folder to include paths if needed
# This is not actually needed in this example.
CFLAGS_USERMOD += -I$(EXAMPLE_MOD_DIR)
Finally you will need to define ``MODULE_EXAMPLE_ENABLED`` to 1. This
can be done by adding ``CFLAGS_EXTRA=-DMODULE_EXAMPLE_ENABLED=1`` to
the ``make`` command, or editing ``mpconfigport.h`` or
``mpconfigboard.h`` to add
.. code-block:: c
#define MODULE_EXAMPLE_ENABLED (1)
Note that the exact method depends on the port as they have different
structures. If not done correctly it will compile but importing will
fail to find the module.
Refer to the comments in these 2 files for additional explanation.
Next to the ``cexample`` module there's also ``cppexample`` which
works in the same way but shows one way of mixing C and C++ code
in MicroPython.
Compiling the cmodule into MicroPython
--------------------------------------
To build such a module, compile MicroPython (see `getting started
<https://github.com/micropython/micropython/wiki/Getting-Started>`_) with an
extra ``make`` flag named ``USER_C_MODULES`` set to the directory containing
all modules you want included (not to the module itself). For example:
<https://github.com/micropython/micropython/wiki/Getting-Started>`_),
applying 2 modifications:
- an extra ``make`` flag named ``USER_C_MODULES`` set to the directory
containing all modules you want included (not to the module itself).
For building the example modules which come with MicroPython,
set ``USER_C_MODULES`` to the ``examples/usercmodule`` directory.
For your own projects it's more convenient to keep custom code out of
the main source tree so a typical project directory structure will look
like this::
my_project/
├── modules/
│ └──example1/
│ ├──example1.c
│ └──micropython.mk
│ └──example2/
│ ├──example2.c
│ └──micropython.mk
└── micropython/
├──ports/
... ├──stm32/
...
Directory::
with ``USER_C_MODULES`` set to the ``my_project/modules`` directory.
my_project/
├── modules/
│ └──example/
│ ├──example.c
│ └──micropython.mk
└── micropython/
├──ports/
... ├──stm32/
...
- all modules found in this directory will be compiled, but only those
which are explicitly enabled will be availabe for importing. Enabling a
module is done by setting the preprocessor define from its module
registration to 1. For example if the source code defines the module with
Building for stm32 port:
.. code-block:: c
MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule, MODULE_CEXAMPLE_ENABLED);
then ``MODULE_CEXAMPLE_ENABLED`` has to be set to 1 to make the module available.
This can be done by adding ``CFLAGS_EXTRA=-DMODULE_CEXAMPLE_ENABLED=1`` to
the ``make`` command, or editing ``mpconfigport.h`` or ``mpconfigboard.h``
to add
.. code-block:: c
#define MODULE_CEXAMPLE_ENABLED (1)
Note that the exact method depends on the port as they have different
structures. If not done correctly it will compile but importing will
fail to find the module.
To sum up, here's how the ``cexample`` module from the ``examples/usercmodule``
directory can be built for the unix port:
.. code-block:: bash
cd micropython/ports/unix
make USER_C_MODULES=../../examples/usercmodule CFLAGS_EXTRA=-DMODULE_CEXAMPLE_ENABLED=1 all
The build output will show the modules found::
...
Including User C Module from ../../examples/usercmodule/cexample
Including User C Module from ../../examples/usercmodule/cppexample
...
Or for your own project with a directory structure as shown above,
including both modules and building the stm32 port for example:
.. code-block:: bash
cd my_project/micropython/ports/stm32
make USER_C_MODULES=../../../modules CFLAGS_EXTRA=-DMODULE_EXAMPLE_ENABLED=1 all
make USER_C_MODULES=../../../modules \
CFLAGS_EXTRA="-DMODULE_EXAMPLE1_ENABLED=1 -DMODULE_EXAMPLE2_ENABLED=1" all
Module usage in MicroPython
---------------------------
Once built into your copy of MicroPython, the module implemented
in ``example.c`` above can now be accessed in Python just
like any other builtin module, eg
Once built into your copy of MicroPython, the module
can now be accessed in Python just like any other builtin module, e.g.
.. code-block:: python
import example
print(example.add_ints(1, 3))
import cexample
print(cexample.add_ints(1, 3))
# should display 4

View File

@ -21,7 +21,8 @@ language which can be compiled to stand-alone machine code can be put into a
A native .mpy module is built using the ``mpy_ld.py`` tool, which is found in the
``tools/`` directory of the project. This tool takes a set of object files
(.o files) and links them together to create a native .mpy files.
(.o files) and links them together to create a native .mpy files. It requires
CPython 3 and the library pyelftools v0.25 or greater.
Supported features and limitations
----------------------------------
@ -67,6 +68,19 @@ The known limitations are:
So, if your C code has writable data, make sure the data is defined globally,
without an initialiser, and only written to within functions.
Linker limitation: the native module is not linked against the symbol table of the
full MicroPython firmware. Rather, it is linked against an explicit table of exported
symbols found in ``mp_fun_table`` (in ``py/nativeglue.h``), that is fixed at firmware
build time. It is thus not possible to simply call some arbitrary HAL/OS/RTOS/system
function, for example.
New symbols can be added to the end of the table and the firmware rebuilt.
The symbols also need to be added to ``tools/mpy_ld.py``'s ``fun_table`` dict in the
same location. This allows ``mpy_ld.py`` to be able to pick the new symbols up and
provide relocations for them when the mpy is imported. Finally, if the symbol is a
function, a macro or stub should be added to ``py/dynruntime.h`` to make it easy to
call the function.
Defining a native module
------------------------
@ -152,10 +166,10 @@ The file ``Makefile`` contains:
MPY_DIR = ../../..
# Name of module
MOD = features0
MOD = factorial
# Source files (.c or .py)
SRC = features0.c
SRC = factorial.c
# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin)
ARCH = x64
@ -166,6 +180,14 @@ The file ``Makefile`` contains:
Compiling the module
--------------------
The prerequisite tools needed to build a native .mpy file are:
* The MicroPython repository (at least the ``py/`` and ``tools/`` directories).
* CPython 3, and the library pyelftools (eg ``pip install 'pyelftools>=0.25'``).
* GNU make.
* A C compiler for the target architecture (if C source is used).
* Optionally ``mpy-cross``, built from the MicroPython repository (if .py source is used).
Be sure to select the correct ``ARCH`` for the target you are going to run on.
Then build with::

View File

@ -51,7 +51,7 @@ Processing happens in the following stages:
through the C pre-processor. This means that any conditionally disabled code
will be removed, and macros expanded. This means we don't add strings to the
pool that won't be used in the final firmware. Because at this stage (thanks
to the ``NO_QSTR`` macro added by ``QSTR_GEN_EXTRA_CFLAGS``) there is no
to the ``NO_QSTR`` macro added by ``QSTR_GEN_CFLAGS``) there is no
definition for ``MP_QSTR_Foo`` it passes through this stage unaffected. This
file also includes comments from the preprocessor that include line number
information. Note that this step only uses files that have changed, which

View File

@ -82,6 +82,7 @@ The :mod:`network` module::
ap = network.WLAN(network.AP_IF) # create access-point interface
ap.config(essid='ESP-AP') # set the ESSID of the access point
ap.config(max_clients=10) # set how many clients can connect to the network
ap.active(True) # activate the interface
A useful function for connecting to your local WiFi network is::
@ -117,17 +118,21 @@ Use the :mod:`time <utime>` module::
Timers
------
Virtual (RTOS-based) timers are supported. Use the :ref:`machine.Timer <machine.Timer>` class
with timer ID of -1::
The ESP32 port has four hardware timers. Use the :ref:`machine.Timer <machine.Timer>` class
with a timer ID from 0 to 3 (inclusive)::
from machine import Timer
tim = Timer(-1)
tim.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1))
tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(2))
tim0 = Timer(0)
tim0.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(0))
tim1 = Timer(1)
tim1.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(1))
The period is in milliseconds.
Virtual timers are not currently supported on this port.
.. _Pins_and_GPIO:
Pins and GPIO
@ -171,9 +176,10 @@ PWM (pulse width modulation)
PWM can be enabled on all output-enabled pins. The base frequency can
range from 1Hz to 40MHz but there is a tradeoff; as the base frequency
*increases* the duty resolution *decreases*. See
*increases* the duty resolution *decreases*. See
`LED Control <https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/ledc.html>`_
for more details.
Currently the duty cycle has to be in the range of 0-1023.
Use the ``machine.PWM`` class::
@ -243,16 +249,15 @@ ESP32 specific ADC class method reference:
Software SPI bus
----------------
There are two SPI drivers. One is implemented in software (bit-banging)
and works on all pins, and is accessed via the :ref:`machine.SPI <machine.SPI>`
class::
Software SPI (using bit-banging) works on all pins, and is accessed via the
:ref:`machine.SoftSPI <machine.SoftSPI>` class::
from machine import Pin, SPI
from machine import Pin, SoftSPI
# construct an SPI bus on the given pins
# 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 = SPI(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(0), mosi=Pin(2), miso=Pin(4))
spi.init(baudrate=200000) # set the baudrate
@ -271,7 +276,7 @@ class::
.. Warning::
Currently *all* of ``sck``, ``mosi`` and ``miso`` *must* be specified when
initialising Software SPI.
initialising Software SPI.
Hardware SPI bus
----------------
@ -292,39 +297,54 @@ mosi 13 23
miso 12 19
===== =========== ============
Hardware SPI has the same methods as Software SPI above::
Hardware SPI is accessed via the :ref:`machine.SPI <machine.SPI>` class and
has the same methods as software SPI above::
from machine import Pin, SPI
hspi = SPI(1, 10000000, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
vspi = SPI(2, baudrate=80000000, polarity=0, phase=0, bits=8, firstbit=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
Software I2C bus
----------------
I2C bus
-------
Software I2C (using bit-banging) works on all output-capable pins, and is
accessed via the :ref:`machine.SoftI2C <machine.SoftI2C>` class::
The I2C driver has both software and hardware implementations, and the two
hardware peripherals have identifiers 0 and 1. Any available output-capable
pins can be used for SCL and SDA. The driver is accessed via the
:ref:`machine.I2C <machine.I2C>` class::
from machine import Pin, SoftI2C
from machine import Pin, I2C
i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100000)
# construct a software I2C bus
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
i2c.scan() # scan for devices
# construct a hardware I2C bus
i2c = I2C(0)
i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000)
i2c.scan() # scan for slave devices
i2c.readfrom(0x3a, 4) # read 4 bytes from slave device with address 0x3a
i2c.writeto(0x3a, '12') # write '12' to slave device with address 0x3a
i2c.readfrom(0x3a, 4) # read 4 bytes from device with address 0x3a
i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a
buf = bytearray(10) # create a buffer with 10 bytes
i2c.writeto(0x3a, buf) # write the given buffer to the slave
Hardware I2C bus
----------------
There are two hardware I2C peripherals with identifiers 0 and 1. Any available
output-capable pins can be used for SCL and SDA but the defaults are given
below.
===== =========== ============
\ I2C(0) I2C(1)
===== =========== ============
scl 18 25
sda 19 26
===== =========== ============
The driver is accessed via the :ref:`machine.I2C <machine.I2C>` class and
has the same methods as software I2C above::
from machine import Pin, I2C
i2c = I2C(0)
i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000)
Real time clock (RTC)
---------------------
@ -435,7 +455,7 @@ For low-level driving of a NeoPixel::
``NeoPixel`` object.
Capacitive Touch
Capacitive touch
----------------
Use the ``TouchPad`` class in the ``machine`` module::
@ -443,11 +463,11 @@ Use the ``TouchPad`` class in the ``machine`` module::
from machine import TouchPad, Pin
t = TouchPad(Pin(14))
t.read() # Returns a smaller number when touched
t.read() # Returns a smaller number when touched
``TouchPad.read`` returns a value relative to the capacitive variation. Small numbers (typically in
the *tens*) are common when a pin is touched, larger numbers (above *one thousand*) when
no touch is present. However the values are *relative* and can vary depending on the board
the *tens*) are common when a pin is touched, larger numbers (above *one thousand*) when
no touch is present. However the values are *relative* and can vary depending on the board
and surrounding composition so some calibration may be required.
There are ten capacitive touch-enabled pins that can be used on the ESP32: 0, 2, 4, 12, 13

View File

@ -138,6 +138,45 @@ Also note that Pin(16) is a special pin (used for wakeup from deepsleep
mode) and may be not available for use with higher-level classes like
``Neopixel``.
UART (serial bus)
-----------------
See :ref:`machine.UART <machine.UART>`. ::
from machine import UART
uart = UART(0, baudrate=9600)
uart.write('hello')
uart.read(5) # read up to 5 bytes
Two UARTs are available. UART0 is on Pins 1 (TX) and 3 (RX). UART0 is
bidirectional, and by default is used for the REPL. UART1 is on Pins 2
(TX) and 8 (RX) however Pin 8 is used to connect the flash chip, so
UART1 is TX only.
When UART0 is attached to the REPL, all incoming chars on UART(0) go
straight to stdin so uart.read() will always return None. Use
sys.stdin.read() if it's needed to read characters from the UART(0)
while it's also used for the REPL (or detach, read, then reattach).
When detached the UART(0) can be used for other purposes.
If there are no objects in any of the dupterm slots when the REPL is
started (on hard or soft reset) then UART(0) is automatically attached.
Without this, the only way to recover a board without a REPL would be to
completely erase and reflash (which would install the default boot.py which
attaches the REPL).
To detach the REPL from UART0, use::
import uos
uos.dupterm(None, 1)
The REPL is attached by default. If you have detached it, to reattach
it use::
import uos, machine
uart = machine.UART(0, 115200)
uos.dupterm(uart, 1)
PWM (pulse width modulation)
----------------------------
@ -175,15 +214,15 @@ Software SPI bus
----------------
There are two SPI drivers. One is implemented in software (bit-banging)
and works on all pins, and is accessed via the :ref:`machine.SPI <machine.SPI>`
and works on all pins, and is accessed via the :ref:`machine.SoftSPI <machine.SoftSPI>`
class::
from machine import Pin, SPI
from machine import Pin, SoftSPI
# construct an SPI 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 = SPI(-1, 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(0), mosi=Pin(2), miso=Pin(4))
spi.init(baudrate=200000) # set the baudrate
@ -219,7 +258,8 @@ I2C bus
-------
The I2C driver is implemented in software and works on all pins,
and is accessed via the :ref:`machine.I2C <machine.I2C>` class::
and is accessed via the :ref:`machine.I2C <machine.I2C>` class (which is an
alias of :ref:`machine.SoftI2C <machine.SoftI2C>`)::
from machine import Pin, I2C

View File

@ -118,5 +118,6 @@ that contains a table with the state of all the GPIO pins::
break
rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins]
response = html % '\n'.join(rows)
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(response)
cl.close()

View File

@ -12,3 +12,4 @@ MicroPython documentation and references
esp8266/quickref.rst
esp32/quickref.rst
wipy/quickref.rst
unix/quickref.rst

View File

@ -76,7 +76,7 @@ Example::
Functions
---------
.. function:: open(stream, \*, flags=0, pagesize=0, cachesize=0, minkeypage=0)
.. function:: open(stream, *, flags=0, pagesize=0, cachesize=0, minkeypage=0)
Open a database from a random-access `stream` (like an open file). All
other parameters are optional and keyword-only, and allow to tweak advanced
@ -116,9 +116,9 @@ Methods
Flush any data in cache to the underlying stream.
.. method:: btree.__getitem__(key)
btree.get(key, default=None)
btree.get(key, default=None, /)
btree.__setitem__(key, val)
btree.__detitem__(key)
btree.__delitem__(key)
btree.__contains__(key)
Standard dictionary methods.

View File

@ -31,7 +31,7 @@ Functions
The system enters the set sleep mode automatically when possible.
.. function:: deepsleep(time=0)
.. function:: deepsleep(time_us=0, /)
**Note**: ESP8266 only - use `machine.deepsleep()` on ESP32

View File

@ -38,10 +38,35 @@ Functions
Read the raw value of the internal Hall sensor, returning an integer.
.. function:: idf_heap_info(capabilities)
Returns information about the ESP-IDF heap memory regions. One of them contains
the MicroPython heap and the others are used by ESP-IDF, e.g., for network
buffers and other data. This data is useful to get a sense of how much memory
is available to ESP-IDF and the networking stack in particular. It may shed
some light on situations where ESP-IDF operations fail due to allocation failures.
The information returned is *not* useful to troubleshoot Python allocation failures,
use `micropython.mem_info()` instead.
The capabilities parameter corresponds to ESP-IDF's ``MALLOC_CAP_XXX`` values but the
two most useful ones are predefined as `esp32.HEAP_DATA` for data heap regions and
`esp32.HEAP_EXEC` for executable regions as used by the native code emitter.
The return value is a list of 4-tuples, where each 4-tuple corresponds to one heap
and contains: the total bytes, the free bytes, the largest free block, and
the minimum free seen over time.
Example after booting::
>>> import esp32; esp32.idf_heap_info(esp32.HEAP_DATA)
[(240, 0, 0, 0), (7288, 0, 0, 0), (16648, 4, 4, 4), (79912, 35712, 35512, 35108),
(15072, 15036, 15036, 15036), (113840, 0, 0, 0)]
Flash partitions
----------------
This class gives access to the partitions in the device's flash memory.
This class gives access to the partitions in the device's flash memory and includes
methods to enable over-the-air (OTA) updates.
.. class:: Partition(id)
@ -51,16 +76,17 @@ This class gives access to the partitions in the device's flash memory.
.. classmethod:: Partition.find(type=TYPE_APP, subtype=0xff, label=None)
Find a partition specified by *type*, *subtype* and *label*. Returns a
(possibly empty) list of Partition objects.
(possibly empty) list of Partition objects. Note: ``subtype=0xff`` matches any subtype
and ``label=None`` matches any label.
.. method:: Partition.info()
Returns a 6-tuple ``(type, subtype, addr, size, label, encrypted)``.
.. method:: Partition.readblocks(block_num, buf)
.. method:: Partition.readblocks(block_num, buf, offset)
Partition.readblocks(block_num, buf, offset)
.. method:: Partition.writeblocks(block_num, buf)
.. method:: Partition.writeblocks(block_num, buf, offset)
Partition.writeblocks(block_num, buf, offset)
.. method:: Partition.ioctl(cmd, arg)
These methods implement the simple and :ref:`extended
@ -74,6 +100,19 @@ This class gives access to the partitions in the device's flash memory.
.. method:: Partition.get_next_update()
Gets the next update partition after this one, and returns a new Partition object.
Typical usage is ``Partition(Partition.RUNNING).get_next_update()``
which returns the next partition to update given the current running one.
.. classmethod:: Partition.mark_app_valid_cancel_rollback()
Signals that the current boot is considered successful.
Calling ``mark_app_valid_cancel_rollback`` is required on the first boot of a new
partition to avoid an automatic rollback at the next boot.
This uses the ESP-IDF "app rollback" feature with "CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE"
and an ``OSError(-261)`` is raised if called on firmware that doesn't have the
feature enabled.
It is OK to call ``mark_app_valid_cancel_rollback`` on every boot and it is not
necessary when booting firmare that was loaded using esptool.
Constants
~~~~~~~~~
@ -81,13 +120,21 @@ Constants
.. data:: Partition.BOOT
Partition.RUNNING
Used in the `Partition` constructor to fetch various partitions.
Used in the `Partition` constructor to fetch various partitions: ``BOOT`` is the
partition that will be booted at the next reset and ``RUNNING`` is the currently
running partition.
.. data:: Partition.TYPE_APP
Partition.TYPE_DATA
Used in `Partition.find` to specify the partition type.
Used in `Partition.find` to specify the partition type: ``APP`` is for bootable
firmware partitions (typically labelled ``factory``, ``ota_0``, ``ota_1``), and
``DATA`` is for other partitions, e.g. ``nvs``, ``otadata``, ``phy_init``, ``vfs``.
.. data:: HEAP_DATA
HEAP_EXEC
Used in `idf_heap_info`.
.. _esp32.RMT:
@ -104,6 +151,11 @@ used to transmit or receive many other types of digital signals::
r = esp32.RMT(0, pin=Pin(18), clock_div=8)
r # RMT(channel=0, pin=18, source_freq=80000000, clock_div=8)
# To use carrier frequency
r = esp32.RMT(0, pin=Pin(18), clock_div=8, carrier_freq=38000)
r # RMT(channel=0, pin=18, source_freq=80000000, clock_div=8, carrier_freq=38000, carrier_duty_percent=50)
# The channel resolution is 100ns (1/(source_freq/clock_div)).
r.write_pulses((1, 20, 2, 40), start=0) # Send 0 for 100ns, 1 for 2000ns, 0 for 200ns, 1 for 4000ns
@ -117,6 +169,9 @@ define the pulses.
multiplying the resolution by a 15-bit (0-32,768) number. There are eight
channels (0-7) and each can have a different clock divider.
To enable the carrier frequency feature of the esp32 hardware, specify the
``carrier_freq`` as something like 38000, a typical IR carrier frequency.
So, in the example above, the 80MHz clock is divided by 8. Thus the
resolution is (1/(80Mhz/8)) 100ns. Since the ``start`` level is 0 and toggles
with each number, the bitstream is ``0101`` with durations of [100ns, 2000ns,
@ -127,17 +182,20 @@ For more details see Espressif's `ESP-IDF RMT documentation.
.. Warning::
The current MicroPython RMT implementation lacks some features, most notably
receiving pulses and carrier transmit. RMT should be considered a
receiving pulses. RMT should be considered a
*beta feature* and the interface may change in the future.
.. class:: RMT(channel, \*, pin=None, clock_div=8)
.. class:: RMT(channel, *, pin=None, clock_div=8, carrier_freq=0, carrier_duty_percent=50)
This class provides access to one of the eight RMT channels. *channel* is
required and identifies which RMT channel (0-7) will be configured. *pin*,
also required, configures which Pin is bound to the RMT channel. *clock_div*
is an 8-bit clock divider that divides the source clock (80MHz) to the RMT
channel allowing the resolution to be specified.
channel allowing the resolution to be specified. *carrier_freq* is used to
enable the carrier feature and specify its frequency, default value is ``0``
(not enabled). To enable, specify a positive integer. *carrier_duty_percent*
defaults to 50.
.. method:: RMT.source_freq()
@ -151,19 +209,21 @@ For more details see Espressif's `ESP-IDF RMT documentation.
.. method:: RMT.wait_done(timeout=0)
Returns True if `RMT.write_pulses` has completed.
Returns ``True`` if the channel is currently transmitting a stream of pulses
started with a call to `RMT.write_pulses`.
If *timeout* (defined in ticks of ``source_freq / clock_div``) is specified
the method will wait for *timeout* or until `RMT.write_pulses` is complete,
returning ``False`` if the channel continues to transmit.
.. Warning::
Avoid using ``wait_done()`` if looping is enabled.
the method will wait for *timeout* or until transmission is complete,
returning ``False`` if the channel continues to transmit. If looping is
enabled with `RMT.loop` and a stream has started, then this method will
always (wait and) return ``False``.
.. method:: RMT.loop(enable_loop)
Configure looping on the channel, allowing a stream of pulses to be
indefinitely repeated. *enable_loop* is bool, set to True to enable looping.
Configure looping on the channel. *enable_loop* is bool, set to ``True`` to
enable looping on the *next* call to `RMT.write_pulses`. If called with
``False`` while a looping stream is currently being transmitted then the
current set of pulses will be completed before transmission stops.
.. method:: RMT.write_pulses(pulses, start)
@ -172,9 +232,18 @@ For more details see Espressif's `ESP-IDF RMT documentation.
resolution ``(1 / (source_freq / clock_div))``. *start* defines whether the
stream starts at 0 or 1.
If transmission of a stream is currently in progress then this method will
block until transmission of that stream has ended before beginning sending
*pulses*.
The Ultra-Low-Power co-processor
--------------------------------
If looping is enabled with `RMT.loop`, the stream of pulses will be repeated
indefinitely. Further calls to `RMT.write_pulses` will end the previous
stream - blocking until the last set of pulses has been transmitted -
before starting the next stream.
Ultra-Low-Power co-processor
----------------------------
.. class:: ULP()

View File

@ -1,4 +1,4 @@
:mod:`framebuf` --- Frame buffer manipulation
:mod:`framebuf` --- frame buffer manipulation
=============================================
.. module:: framebuf
@ -28,7 +28,7 @@ For example::
Constructors
------------
.. class:: FrameBuffer(buffer, width, height, format, stride=width)
.. class:: FrameBuffer(buffer, width, height, format, stride=width, /)
Construct a FrameBuffer object. The parameters are:
@ -130,7 +130,7 @@ Constants
Monochrome (1-bit) color format
This defines a mapping where the bits in a byte are horizontally mapped.
Each byte occupies 8 horizontal pixels with bit 0 being the leftmost.
Each byte occupies 8 horizontal pixels with bit 7 being the leftmost.
Subsequent bytes appear at successive horizontal locations until the
rightmost edge is reached. Further bytes are rendered on the next row, one
pixel lower.
@ -139,7 +139,7 @@ Constants
Monochrome (1-bit) color format
This defines a mapping where the bits in a byte are horizontally mapped.
Each byte occupies 8 horizontal pixels with bit 7 being the leftmost.
Each byte occupies 8 horizontal pixels with bit 0 being the leftmost.
Subsequent bytes appear at successive horizontal locations until the
rightmost edge is reached. Further bytes are rendered on the next row, one
pixel lower.

View File

@ -23,7 +23,7 @@ into MicroPython. There are a few categories of such modules:
* Modules which implement a subset of Python functionality, with a provision
for extension by the user (via Python code).
* Modules which implement MicroPython extensions to the Python standard libraries.
* Modules specific to a particular `MicroPython port` and thus not portable.
* Modules specific to a particular :term:`MicroPython port` and thus not portable.
Note about the availability of the modules and their contents: This documentation
in general aspires to describe all modules and functions/classes which are
@ -38,7 +38,7 @@ in a module (or even the entire module) described in this documentation **may be
unavailable** in a particular build of MicroPython on a particular system. The
best place to find general information of the availability/non-availability
of a particular feature is the "General Information" section which contains
information pertaining to a specific `MicroPython port`.
information pertaining to a specific :term:`MicroPython port`.
On some ports you are able to discover the available, built-in libraries that
can be imported by entering the following at the REPL::
@ -77,8 +77,8 @@ it will fallback to loading the built-in ``ujson`` module.
cmath.rst
gc.rst
math.rst
sys.rst
uarray.rst
uasyncio.rst
ubinascii.rst
ucollections.rst
uerrno.rst
@ -92,6 +92,7 @@ it will fallback to loading the built-in ``ujson`` module.
usocket.rst
ussl.rst
ustruct.rst
usys.rst
utime.rst
uzlib.rst
_thread.rst

View File

@ -37,7 +37,7 @@ For example::
Constructors
------------
.. class:: LCD160CR(connect=None, \*, pwr=None, i2c=None, spi=None, i2c_addr=98)
.. class:: LCD160CR(connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98)
Construct an LCD160CR object. The parameters are:

View File

@ -22,7 +22,7 @@ Usage::
Constructors
------------
.. class:: ADCWiPy(id=0, \*, bits=12)
.. class:: ADCWiPy(id=0, *, bits=12)
Create an ADC object associated with the given pin.
This allows you to then read analog values on that pin.
@ -39,7 +39,7 @@ Constructors
Methods
-------
.. method:: ADCWiPy.channel(id, \*, pin)
.. method:: ADCWiPy.channel(id, *, pin)
Create an analog pin. If only channel ID is given, the correct pin will
be selected. Alternatively, only the pin can be passed and the correct

View File

@ -12,6 +12,14 @@ when created, or initialised later on.
Printing the I2C object gives you information about its configuration.
Both hardware and software I2C implementations exist via the
:ref:`machine.I2C <machine.I2C>` and `machine.SoftI2C` classes. Hardware I2C uses
underlying hardware support of the system to perform the reads/writes and is
usually efficient and fast but may have restrictions on which pins can be used.
Software I2C is implemented by bit-banging and can be used on any pin but is not
as efficient. These classes have the same methods available and differ primarily
in the way they are constructed.
Example usage::
from machine import I2C
@ -33,26 +41,38 @@ Example usage::
Constructors
------------
.. class:: I2C(id=-1, \*, scl, sda, freq=400000)
.. class:: I2C(id, *, scl, sda, freq=400000)
Construct and return a new I2C object using the following parameters:
- *id* identifies a particular I2C peripheral. The default
value of -1 selects a software implementation of I2C which can
work (in most cases) with arbitrary pins for SCL and SDA.
If *id* is -1 then *scl* and *sda* must be specified. Other
allowed values for *id* depend on the particular port/board,
and specifying *scl* and *sda* may or may not be required or
allowed in this case.
- *id* identifies a particular I2C peripheral. Allowed values for
depend on the particular port/board
- *scl* should be a pin object specifying the pin to use for SCL.
- *sda* should be a pin object specifying the pin to use for SDA.
- *freq* should be an integer which sets the maximum frequency
for SCL.
Note that some ports/boards will have default values of *scl* and *sda*
that can be changed in this constructor. Others will have fixed values
of *scl* and *sda* that cannot be changed.
.. _machine.SoftI2C:
.. class:: SoftI2C(scl, sda, *, freq=400000, timeout=255)
Construct a new software I2C object. The parameters are:
- *scl* should be a pin object specifying the pin to use for SCL.
- *sda* should be a pin object specifying the pin to use for SDA.
- *freq* should be an integer which sets the maximum frequency
for SCL.
- *timeout* is the maximum time in microseconds to wait for clock
stretching (SCL held low by another device on the bus), after
which an ``OSError(ETIMEDOUT)`` exception is raised.
General Methods
---------------
.. method:: I2C.init(scl, sda, \*, freq=400000)
.. method:: I2C.init(scl, sda, *, freq=400000)
Initialise the I2C bus with the given arguments:
@ -79,7 +99,7 @@ The following methods implement the primitive I2C master bus operations and can
be combined to make any I2C transaction. They are provided if you need more
control over the bus, otherwise the standard methods (see below) can be used.
These methods are available on software I2C only.
These methods are only available on the `machine.SoftI2C` class.
.. method:: I2C.start()
@ -89,7 +109,7 @@ These methods are available on software I2C only.
Generate a STOP condition on the bus (SDA transitions to high while SCL is high).
.. method:: I2C.readinto(buf, nack=True)
.. method:: I2C.readinto(buf, nack=True, /)
Reads bytes from the bus and stores them into *buf*. The number of bytes
read is the length of *buf*. An ACK will be sent on the bus after
@ -109,13 +129,13 @@ Standard bus operations
The following methods implement the standard I2C master read and write
operations that target a given slave device.
.. method:: I2C.readfrom(addr, nbytes, stop=True)
.. method:: I2C.readfrom(addr, nbytes, stop=True, /)
Read *nbytes* from the slave specified by *addr*.
If *stop* is true then a STOP condition is generated at the end of the transfer.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_into(addr, buf, stop=True)
.. method:: I2C.readfrom_into(addr, buf, stop=True, /)
Read into *buf* from the slave specified by *addr*.
The number of bytes read will be the length of *buf*.
@ -123,7 +143,7 @@ operations that target a given slave device.
The method returns ``None``.
.. method:: I2C.writeto(addr, buf, stop=True)
.. method:: I2C.writeto(addr, buf, stop=True, /)
Write the bytes from *buf* to the slave specified by *addr*. If a
NACK is received following the write of a byte from *buf* then the
@ -131,7 +151,7 @@ operations that target a given slave device.
generated at the end of the transfer, even if a NACK is received.
The function returns the number of ACKs that were received.
.. method:: I2C.writevto(addr, vector, stop=True)
.. method:: I2C.writevto(addr, vector, stop=True, /)
Write the bytes contained in *vector* to the slave specified by *addr*.
*vector* should be a tuple or list of objects with the buffer protocol.
@ -153,14 +173,14 @@ from and written to. In this case there are two addresses associated with an
I2C transaction: the slave address and the memory address. The following
methods are convenience functions to communicate with such devices.
.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8)
.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, *, addrsize=8)
Read *nbytes* from the slave specified by *addr* starting from the memory
address specified by *memaddr*.
The argument *addrsize* specifies the address size in bits.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, \*, addrsize=8)
.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, *, addrsize=8)
Read into *buf* from the slave specified by *addr* starting from the
memory address specified by *memaddr*. The number of bytes read is the
@ -170,7 +190,7 @@ methods are convenience functions to communicate with such devices.
The method returns ``None``.
.. method:: I2C.writeto_mem(addr, memaddr, buf, \*, addrsize=8)
.. method:: I2C.writeto_mem(addr, memaddr, buf, *, addrsize=8)
Write *buf* to the slave specified by *addr* starting from the
memory address specified by *memaddr*.

View File

@ -42,7 +42,7 @@ Usage Model::
Constructors
------------
.. class:: Pin(id, mode=-1, pull=-1, \*, value, drive, alt)
.. class:: Pin(id, mode=-1, pull=-1, *, value, drive, alt)
Access the pin peripheral (GPIO pin) associated with the given ``id``. If
additional arguments are given in the constructor then they are used to initialise
@ -106,7 +106,7 @@ Constructors
Methods
-------
.. method:: Pin.init(mode=-1, pull=-1, \*, value, drive, alt)
.. method:: Pin.init(mode=-1, pull=-1, *, value, drive, alt)
Re-initialise the pin using the given parameters. Only those arguments that
are specified will be set. The rest of the pin peripheral state will remain
@ -179,7 +179,7 @@ Methods
Availability: WiPy.
.. method:: Pin.irq(handler=None, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING), \*, priority=1, wake=None, hard=False)
.. method:: Pin.irq(handler=None, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING), *, priority=1, wake=None, hard=False)
Configure an interrupt handler to be called when the trigger source of the
pin is active. If the pin mode is ``Pin.IN`` then the trigger source is
@ -216,6 +216,7 @@ Methods
- ``hard`` if true a hardware interrupt is used. This reduces the delay
between the pin change and the handler being called. Hard interrupt
handlers may not allocate memory; see :ref:`isr_rules`.
Not all ports support this argument.
This method returns a callback object.

View File

@ -38,7 +38,7 @@ Methods
Resets the RTC to the time of January 1, 2015 and starts running it again.
.. method:: RTC.alarm(id, time, \*, repeat=False)
.. method:: RTC.alarm(id, time, *, repeat=False)
Set the RTC alarm. Time might be either a millisecond value to program the alarm to
current time + time_in_ms in the future, or a datetimetuple. If the time passed is in
@ -52,7 +52,7 @@ Methods
Cancel a running alarm.
.. method:: RTC.irq(\*, trigger, handler=None, wake=machine.IDLE)
.. method:: RTC.irq(*, trigger, handler=None, wake=machine.IDLE)
Create an irq object triggered by a real time clock alarm.

View File

@ -23,7 +23,7 @@ arguments that might need to be set in order to use either a non-standard slot
or a non-standard pin assignment. The exact subset of arguments supported will
vary from platform to platform.
.. class:: SDCard(slot=1, width=1, cd=None, wp=None, sck=None, miso=None, mosi=None, cs=None)
.. class:: SDCard(slot=1, width=1, cd=None, wp=None, sck=None, miso=None, mosi=None, cs=None, freq=20000000)
This class provides access to SD or MMC storage cards using either
a dedicated SD/MMC interface hardware or through an SPI channel.
@ -50,6 +50,8 @@ vary from platform to platform.
- *mosi* can be used to specify an SPI mosi pin.
- *cs* can be used to specify an SPI chip select pin.
- *freq* selects the SD/MMC interface frequency in Hz (only supported on the ESP32).
Implementation-specific details
-------------------------------

View File

@ -11,25 +11,39 @@ SS (Slave Select), to select a particular device on a bus with which
communication takes place. Management of an SS signal should happen in
user code (via machine.Pin class).
Both hardware and software SPI implementations exist via the
:ref:`machine.SPI <machine.SPI>` and `machine.SoftSPI` classes. Hardware SPI uses underlying
hardware support of the system to perform the reads/writes and is usually
efficient and fast but may have restrictions on which pins can be used.
Software SPI is implemented by bit-banging and can be used on any pin but
is not as efficient. These classes have the same methods available and
differ primarily in the way they are constructed.
Constructors
------------
.. class:: SPI(id, ...)
Construct an SPI object on the given bus, ``id``. Values of ``id`` depend
Construct an SPI object on the given bus, *id*. Values of *id* depend
on a particular port and its hardware. Values 0, 1, etc. are commonly used
to select hardware SPI block #0, #1, etc. Value -1 can be used for
bitbanging (software) implementation of SPI (if supported by a port).
to select hardware SPI block #0, #1, etc.
With no additional parameters, the SPI object is created but not
initialised (it has the settings from the last initialisation of
the bus, if any). If extra arguments are given, the bus is initialised.
See ``init`` for parameters of initialisation.
.. _machine.SoftSPI:
.. class:: SoftSPI(baudrate=500000, *, polarity=0, phase=0, bits=8, firstbit=MSB, sck=None, mosi=None, miso=None)
Construct a new software SPI object. Additional parameters must be
given, usually at least *sck*, *mosi* and *miso*, and these are used
to initialise the bus. See `SPI.init` for a description of the parameters.
Methods
-------
.. method:: SPI.init(baudrate=1000000, \*, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None, pins=(SCK, MOSI, MISO))
.. method:: SPI.init(baudrate=1000000, *, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None, pins=(SCK, MOSI, MISO))
Initialise the SPI bus with the given parameters:

View File

@ -55,7 +55,7 @@ Following is the guide when Signal vs Pin should be used:
* Use Pin: If you implement a higher-level protocol or bus to communicate
with more complex devices.
The split between Pin and Signal come from the usecases above and the
The split between Pin and Signal come from the use cases above and the
architecture of MicroPython: Pin offers the lowest overhead, which may
be important when bit-banging protocols. But Signal adds additional
flexibility on top of Pin, at the cost of minor overhead (much smaller
@ -75,7 +75,7 @@ Constructors
------------
.. class:: Signal(pin_obj, invert=False)
Signal(pin_arguments..., \*, invert=False)
Signal(pin_arguments..., *, invert=False)
Create a Signal object. There're two ways to create it:

View File

@ -31,11 +31,13 @@ Constructors
Construct a new timer object of the given id. Id of -1 constructs a
virtual timer (if supported by a board).
See ``init`` for parameters of initialisation.
Methods
-------
.. method:: Timer.init(\*, mode=Timer.PERIODIC, period=-1, callback=None)
.. method:: Timer.init(*, mode=Timer.PERIODIC, period=-1, callback=None)
Initialise the timer. Example::

View File

@ -39,7 +39,7 @@ Constructors
Methods
-------
.. method:: TimerWiPy.init(mode, \*, width=16)
.. method:: TimerWiPy.init(mode, *, width=16)
Initialise the timer. Example::
@ -64,7 +64,7 @@ Methods
Deinitialises the timer. Stops the timer, and disables the timer peripheral.
.. method:: TimerWiPy.channel(channel, \**, freq, period, polarity=TimerWiPy.POSITIVE, duty_cycle=0)
.. method:: TimerWiPy.channel(channel, **, freq, period, polarity=TimerWiPy.POSITIVE, duty_cycle=0)
If only a channel identifier passed, then a previously initialized channel
object is returned (or ``None`` if there is no previous channel).
@ -113,7 +113,7 @@ TimerChannel objects are created using the Timer.channel() method.
Methods
-------
.. method:: timerchannel.irq(\*, trigger, priority=1, handler=None)
.. method:: timerchannel.irq(*, trigger, priority=1, handler=None)
The behavior of this callback is heavily dependent on the operating
mode of the timer channel:

View File

@ -43,7 +43,7 @@ Constructors
Methods
-------
.. method:: UART.init(baudrate=9600, bits=8, parity=None, stop=1, \*, ...)
.. method:: UART.init(baudrate=9600, bits=8, parity=None, stop=1, *, ...)
Initialise the UART bus with the given parameters:
@ -58,6 +58,9 @@ Methods
- *rx* specifies the RX pin to use.
- *txbuf* specifies the length in characters of the TX buffer.
- *rxbuf* specifies the length in characters of the RX buffer.
- *timeout* specifies the time to wait for the first character (in ms).
- *timeout_char* specifies the time to wait between characters (in ms).
- *invert* specifies which lines to invert.
On the WiPy only the following keyword-only parameter is supported:
@ -87,7 +90,8 @@ Methods
.. method:: UART.read([nbytes])
Read characters. If ``nbytes`` is specified then read at most that many bytes,
otherwise read as much data as possible.
otherwise read as much data as possible. It may return sooner if a timeout
is reached. The timeout is configurable in the constructor.
Return value: a bytes object containing the bytes read in. Returns ``None``
on timeout.
@ -95,14 +99,16 @@ Methods
.. method:: UART.readinto(buf[, nbytes])
Read bytes into the ``buf``. If ``nbytes`` is specified then read at most
that many bytes. Otherwise, read at most ``len(buf)`` bytes.
that many bytes. Otherwise, read at most ``len(buf)`` bytes. It may return sooner if a timeout
is reached. The timeout is configurable in the constructor.
Return value: number of bytes read and stored into ``buf`` or ``None`` on
timeout.
.. method:: UART.readline()
Read a line, ending in a newline character.
Read a line, ending in a newline character. It may return sooner if a timeout
is reached. The timeout is configurable in the constructor.
Return value: the line read or ``None`` on timeout.

View File

@ -15,16 +15,18 @@ Example usage::
wdt = WDT(timeout=2000) # enable it with a timeout of 2s
wdt.feed()
Availability of this class: pyboard, WiPy.
Availability of this class: pyboard, WiPy, esp8266, esp32.
Constructors
------------
.. class:: WDT(id=0, timeout=5000)
Create a WDT object and start it. The timeout must be given in seconds and
the minimum value that is accepted is 1 second. Once it is running the timeout
cannot be changed and the WDT cannot be stopped either.
Create a WDT object and start it. The timeout must be given in milliseconds.
Once it is running the timeout cannot be changed and the WDT cannot be stopped either.
Notes: On the esp32 the minimum timeout is 1 second. On the esp8266 a timeout
cannot be specified, it is determined by the underlying system.
Methods
-------

View File

@ -27,6 +27,12 @@ Reset related functions
Resets the device in a manner similar to pushing the external RESET
button.
.. function:: soft_reset()
Performs a soft reset of the interpreter, deleting all Python objects and
resetting the Python heap. It tries to retain the method by which the user
is connected to the MicroPython REPL (eg serial, USB, Wifi).
.. function:: reset_cause()
Get the reset cause. See :ref:`constants <machine_constants>` for the possible return values.
@ -73,7 +79,7 @@ Power related functions
If *time_ms* is specified then this will be the maximum time in milliseconds that
the sleep will last for. Otherwise the sleep can last indefinitely.
With or without a timout, execution may resume at any time if there are events
With or without a timeout, execution may resume at any time if there are events
that require processing. Such events, or wake sources, should be configured before
sleeping, like `Pin` change or `RTC` timeout.
@ -105,7 +111,7 @@ Miscellaneous functions
varies by hardware (so use substring of a full value if you expect a short
ID). In some MicroPython ports, ID corresponds to the network MAC address.
.. function:: time_pulse_us(pin, pulse_level, timeout_us=1000000)
.. function:: time_pulse_us(pin, pulse_level, timeout_us=1000000, /)
Time a pulse on the given *pin*, and return the duration of the pulse in
microseconds. The *pulse_level* argument should be 0 to time a low pulse

View File

@ -82,17 +82,26 @@ Functions
.. function:: heap_lock()
.. function:: heap_unlock()
.. function:: heap_locked()
Lock or unlock the heap. When locked no memory allocation can occur and a
`MemoryError` will be raised if any heap allocation is attempted.
`heap_locked()` returns a true value if the heap is currently locked.
These functions can be nested, ie `heap_lock()` can be called multiple times
in a row and the lock-depth will increase, and then `heap_unlock()` must be
called the same number of times to make the heap available again.
Both `heap_unlock()` and `heap_locked()` return the current lock depth
(after unlocking for the former) as a non-negative integer, with 0 meaning
the heap is not locked.
If the REPL becomes active with the heap locked then it will be forcefully
unlocked.
Note: `heap_locked()` is not enabled on most ports by default,
requires ``MICROPY_PY_MICROPYTHON_HEAP_LOCKED``.
.. function:: kbd_intr(chr)
Set the character that will raise a `KeyboardInterrupt` exception. By

View File

@ -51,7 +51,7 @@ Constructors
Methods
-------
.. method:: CC3K.connect(ssid, key=None, \*, security=WPA2, bssid=None)
.. method:: CC3K.connect(ssid, key=None, *, security=WPA2, bssid=None)
Connect to a WiFi access point using the given SSID, and other security
parameters.

View File

@ -32,7 +32,7 @@ Methods
argument is passed. Otherwise, query current state if no argument is
provided. Most other methods require active interface.
.. method:: WLAN.connect(ssid=None, password=None, \*, bssid=None)
.. method:: WLAN.connect(ssid=None, password=None, *, bssid=None)
Connect to the specified wireless network, using the specified password.
If *bssid* is given then the connection will be restricted to the
@ -101,7 +101,7 @@ Methods
nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
.. method:: WLAN.config('param')
.. method:: WLAN.config(param=value, ...)
WLAN.config(param=value, ...)
Get or set general network interface parameters. These methods allow to work
with additional parameters beyond standard IP configuration (as dealt with by
@ -117,7 +117,7 @@ Methods
print(ap.config('channel'))
Following are commonly supported parameters (availability of a specific parameter
depends on network technology type, driver, and `MicroPython port`).
depends on network technology type, driver, and :term:`MicroPython port`).
============= ===========
Parameter Description

View File

@ -43,7 +43,7 @@ Constructors
Methods
-------
.. method:: WLANWiPy.init(mode, \*, ssid, auth, channel, antenna)
.. method:: WLANWiPy.init(mode, *, ssid, auth, channel, antenna)
Set or get the WiFi network processor configuration.
@ -69,7 +69,7 @@ Methods
# configure as an station
wlan.init(mode=WLAN.STA)
.. method:: WLANWiPy.connect(ssid, \*, auth=None, bssid=None, timeout=None)
.. method:: WLANWiPy.connect(ssid, *, auth=None, bssid=None, timeout=None)
Connect to a WiFi access point using the given SSID, and other security
parameters.
@ -131,7 +131,7 @@ Methods
Get or set a 6-byte long bytes object with the MAC address.
.. method:: WLANWiPy.irq(\*, handler, wake)
.. method:: WLANWiPy.irq(*, handler, wake)
Create a callback to be triggered when a WLAN event occurs during ``machine.SLEEP``
mode. Events are triggered by socket activity or by WLAN connection/disconnection.

View File

@ -39,7 +39,7 @@ Common network adapter interface
================================
This section describes an (implied) abstract base class for all network
interface classes implemented by `MicroPython ports <MicroPython port>`
interface classes implemented by :term:`MicroPython ports <MicroPython port>`
for different hardware. This means that MicroPython does not actually
provide ``AbstractNIC`` class, but any actual NIC class, as described
in the following sections, implements methods as described here.
@ -58,7 +58,7 @@ parameter should be `id`.
interface (behavior of calling them on inactive interface is
undefined).
.. method:: AbstractNIC.connect([service_id, key=None, \*, ...])
.. method:: AbstractNIC.connect([service_id, key=None, *, ...])
Connect the interface to a network. This method is optional, and
available only for interfaces which are not "always connected".
@ -82,7 +82,7 @@ parameter should be `id`.
Returns ``True`` if connected to network, otherwise returns ``False``.
.. method:: AbstractNIC.scan(\*, ...)
.. method:: AbstractNIC.scan(*, ...)
Scan for the available network services/connections. Returns a
list of tuples with discovered service parameters. For various

View File

@ -49,7 +49,7 @@ Class Methods
Methods
-------
.. method:: CAN.init(mode, extframe=False, prescaler=100, \*, sjw=1, bs1=6, bs2=8, auto_restart=False)
.. method:: CAN.init(mode, extframe=False, prescaler=100, *, sjw=1, bs1=6, bs2=8, auto_restart=False)
Initialise the CAN bus with the given parameters:
@ -135,7 +135,7 @@ Methods
- number of pending RX messages on fifo 0
- number of pending RX messages on fifo 1
.. method:: CAN.setfilter(bank, mode, fifo, params, \*, rtr)
.. method:: CAN.setfilter(bank, mode, fifo, params, *, rtr)
Configure a filter bank:
@ -187,7 +187,7 @@ Methods
Return ``True`` if any message waiting on the FIFO, else ``False``.
.. method:: CAN.recv(fifo, list=None, \*, timeout=5000)
.. method:: CAN.recv(fifo, list=None, *, timeout=5000)
Receive data on the bus:
@ -220,7 +220,7 @@ Methods
# No heap memory is allocated in the following call
can.recv(0, lst)
.. method:: CAN.send(data, id, \*, timeout=0, rtr=False)
.. method:: CAN.send(data, id, *, timeout=0, rtr=False)
Send a message on the bus:

View File

@ -49,7 +49,7 @@ To output a continuous sine-wave at 12-bit resolution::
Constructors
------------
.. class:: pyb.DAC(port, bits=8, \*, buffering=None)
.. class:: pyb.DAC(port, bits=8, *, buffering=None)
Construct a new DAC object.
@ -76,7 +76,7 @@ Constructors
Methods
-------
.. method:: DAC.init(bits=8, \*, buffering=None)
.. method:: DAC.init(bits=8, *, buffering=None)
Reinitialise the DAC. *bits* can be 8 or 12. *buffering* can be
``None``, ``False`` or ``True``; see above constructor for the meaning
@ -103,7 +103,7 @@ Methods
value is 2\*\*``bits``-1, where ``bits`` is set when creating the DAC
object or by using the ``init`` method.
.. method:: DAC.write_timed(data, freq, \*, mode=DAC.NORMAL)
.. method:: DAC.write_timed(data, freq, *, mode=DAC.NORMAL)
Initiates a burst of RAM to DAC using a DMA transfer.
The input data is treated as an array of bytes in 8-bit mode, and

View File

@ -25,7 +25,8 @@ Constructors
This constructor is deprecated and will be removed in a future version of MicroPython.
.. class:: pyb.Flash(\*, start=-1, len=-1)
.. class:: pyb.Flash(*, start=-1, len=-1)
:noindex:
Create and return a block device that accesses the flash at the specified offset. The length defaults to the remaining size of the device.
@ -35,9 +36,9 @@ Methods
-------
.. method:: Flash.readblocks(block_num, buf)
.. method:: Flash.readblocks(block_num, buf, offset)
Flash.readblocks(block_num, buf, offset)
.. method:: Flash.writeblocks(block_num, buf)
.. method:: Flash.writeblocks(block_num, buf, offset)
Flash.writeblocks(block_num, buf, offset)
.. method:: Flash.ioctl(cmd, arg)
These methods implement the simple and :ref:`extended

View File

@ -84,7 +84,7 @@ Methods
Turn off the I2C bus.
.. method:: I2C.init(mode, \*, addr=0x12, baudrate=400000, gencall=False, dma=False)
.. method:: I2C.init(mode, *, addr=0x12, baudrate=400000, gencall=False, dma=False)
Initialise the I2C bus with the given parameters:
@ -100,7 +100,7 @@ Methods
Check if an I2C device responds to the given address. Only valid when in master mode.
.. method:: I2C.mem_read(data, addr, memaddr, \*, timeout=5000, addr_size=8)
.. method:: I2C.mem_read(data, addr, memaddr, *, timeout=5000, addr_size=8)
Read from the memory of an I2C device:
@ -113,7 +113,7 @@ Methods
Returns the read data.
This is only valid in master mode.
.. method:: I2C.mem_write(data, addr, memaddr, \*, timeout=5000, addr_size=8)
.. method:: I2C.mem_write(data, addr, memaddr, *, timeout=5000, addr_size=8)
Write to the memory of an I2C device:
@ -126,7 +126,7 @@ Methods
Returns ``None``.
This is only valid in master mode.
.. method:: I2C.recv(recv, addr=0x00, \*, timeout=5000)
.. method:: I2C.recv(recv, addr=0x00, *, timeout=5000)
Receive data on the bus:
@ -138,7 +138,7 @@ Methods
Return value: if ``recv`` is an integer then a new buffer of the bytes received,
otherwise the same buffer that was passed in to ``recv``.
.. method:: I2C.send(send, addr=0x00, \*, timeout=5000)
.. method:: I2C.send(send, addr=0x00, *, timeout=5000)
Send data on the bus:

View File

@ -51,7 +51,7 @@ Methods
Turn off the SPI bus.
.. method:: SPI.init(mode, baudrate=328125, \*, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)
.. method:: SPI.init(mode, baudrate=328125, *, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)
Initialise the SPI bus with the given parameters:
@ -64,6 +64,7 @@ Methods
respectively.
- ``bits`` can be 8 or 16, and is the number of bits in each transferred word.
- ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``.
- ``ti`` True indicates Texas Instruments, as opposed to Motorola, signal conventions.
- ``crc`` can be None for no CRC, or a polynomial specifier.
Note that the SPI clock frequency will not always be the requested baudrate.
@ -76,7 +77,7 @@ Methods
Printing the SPI object will show you the computed baudrate and the chosen
prescaler.
.. method:: SPI.recv(recv, \*, timeout=5000)
.. method:: SPI.recv(recv, *, timeout=5000)
Receive data on the bus:
@ -87,7 +88,7 @@ Methods
Return value: if ``recv`` is an integer then a new buffer of the bytes received,
otherwise the same buffer that was passed in to ``recv``.
.. method:: SPI.send(send, \*, timeout=5000)
.. method:: SPI.send(send, *, timeout=5000)
Send data on the bus:
@ -96,7 +97,7 @@ Methods
Return value: ``None``.
.. method:: SPI.send_recv(send, recv=None, \*, timeout=5000)
.. method:: SPI.send_recv(send, recv=None, *, timeout=5000)
Send and receive data on the bus at the same time:

View File

@ -62,7 +62,7 @@ Constructors
Methods
-------
.. method:: Timer.init(\*, freq, prescaler, period)
.. method:: Timer.init(*, freq, prescaler, period, mode=Timer.UP, div=1, callback=None, deadtime=0)
Initialise the timer. Initialisation must be either by frequency (in Hz)
or by prescaler and period::

View File

@ -48,13 +48,16 @@ Constructors
.. class:: pyb.UART(bus, ...)
Construct a UART object on the given bus. ``bus`` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'.
Construct a UART object on the given bus.
For Pyboard ``bus`` can be 1-4, 6, 'XA', 'XB', 'YA', or 'YB'.
For Pyboard Lite ``bus`` can be 1, 2, 6, 'XB', or 'YA'.
For Pyboard D ``bus`` can be 1-4, 'XA', 'YA' or 'YB'.
With no additional parameters, the UART object is created but not
initialised (it has the settings from the last initialisation of
the bus, if any). If extra arguments are given, the bus is initialised.
See ``init`` for parameters of initialisation.
The physical pins of the UART busses are:
The physical pins of the UART busses on Pyboard are:
- ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)``
- ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)``
@ -62,14 +65,26 @@ Constructors
- ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)``
- ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)``
The Pyboard Lite supports UART(1), UART(2) and UART(6) only. Pins are as above except:
The Pyboard Lite supports UART(1), UART(2) and UART(6) only, pins are:
- ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)``
- ``UART(6)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PC6, PC7)``
- ``UART(2)`` is on: ``(TX, RX) = (X1, X2) = (PA2, PA3)``
The Pyboard D supports UART(1), UART(2), UART(3) and UART(4) only, pins are:
- ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)``
- ``UART(1)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PA9, PA10)``
- ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)``
- ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)``
*Note:* Pyboard D has ``UART(1)`` on ``YA``, unlike Pyboard and Pyboard Lite that both
have ``UART(1)`` on ``XB`` and ``UART(6)`` on ``YA``.
Methods
-------
.. method:: UART.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=0, flow=0, timeout_char=0, read_buf_len=64)
.. method:: UART.init(baudrate, bits=8, parity=None, stop=1, *, timeout=0, flow=0, timeout_char=0, read_buf_len=64)
Initialise the UART bus with the given parameters:

View File

@ -21,7 +21,7 @@ Constructors
Methods
-------
.. method:: USB_HID.recv(data, \*, timeout=5000)
.. method:: USB_HID.recv(data, *, timeout=5000)
Receive data on the bus:

View File

@ -21,7 +21,7 @@ Constructors
Methods
-------
.. method:: USB_VCP.init(\*, flow=-1)
.. method:: USB_VCP.init(*, flow=-1)
Configure the USB VCP port. If the *flow* argument is not -1 then the value sets
the flow control, which can be a bitwise-or of ``USB_VCP.RTS`` and ``USB_VCP.CTS``.
@ -89,7 +89,7 @@ Methods
Returns the number of bytes written.
.. method:: USB_VCP.recv(data, \*, timeout=5000)
.. method:: USB_VCP.recv(data, *, timeout=5000)
Receive data on the bus:
@ -100,7 +100,7 @@ Methods
Return value: if ``data`` is an integer then a new buffer of the bytes received,
otherwise the number of bytes read into ``data`` is returned.
.. method:: USB_VCP.send(data, \*, timeout=5000)
.. method:: USB_VCP.send(data, *, timeout=5000)
Send data over the USB VCP:

View File

@ -210,7 +210,7 @@ Miscellaneous functions
It only makes sense to call this function from within boot.py.
.. function:: mount(device, mountpoint, \*, readonly=False, mkfs=False)
.. function:: mount(device, mountpoint, *, readonly=False, mkfs=False)
.. note:: This function is deprecated. Mounting and unmounting devices should
be performed by :meth:`uos.mount` and :meth:`uos.umount` instead.

View File

@ -0,0 +1,303 @@
:mod:`uasyncio` --- asynchronous I/O scheduler
==============================================
.. module:: uasyncio
:synopsis: asynchronous I/O scheduler for writing concurrent code
|see_cpython_module|
`asyncio <https://docs.python.org/3.8/library/asyncio.html>`_
Example::
import uasyncio
async def blink(led, period_ms):
while True:
led.on()
await uasyncio.sleep_ms(5)
led.off()
await uasyncio.sleep_ms(period_ms)
async def main(led1, led2):
uasyncio.create_task(blink(led1, 700))
uasyncio.create_task(blink(led2, 400))
await uasyncio.sleep_ms(10_000)
# Running on a pyboard
from pyb import LED
uasyncio.run(main(LED(1), LED(2)))
# Running on a generic board
from machine import Pin
uasyncio.run(main(Pin(1), Pin(2)))
Core functions
--------------
.. function:: create_task(coro)
Create a new task from the given coroutine and schedule it to run.
Returns the corresponding `Task` object.
.. function:: run(coro)
Create a new task from the given coroutine and run it until it completes.
Returns the value returned by *coro*.
.. function:: sleep(t)
Sleep for *t* seconds (can be a float).
This is a coroutine.
.. function:: sleep_ms(t)
Sleep for *t* milliseconds.
This is a coroutine, and a MicroPython extension.
Additional functions
--------------------
.. function:: wait_for(awaitable, timeout)
Wait for the *awaitable* to complete, but cancel it if it takes longer
that *timeout* seconds. If *awaitable* is not a task then a task will be
created from it.
If a timeout occurs, it cancels the task and raises ``asyncio.TimeoutError``:
this should be trapped by the caller.
Returns the return value of *awaitable*.
This is a coroutine.
.. function:: wait_for_ms(awaitable, timeout)
Similar to `wait_for` but *timeout* is an integer in milliseconds.
This is a coroutine, and a MicroPython extension.
.. function:: gather(*awaitables, return_exceptions=False)
Run all *awaitables* concurrently. Any *awaitables* that are not tasks are
promoted to tasks.
Returns a list of return values of all *awaitables*.
This is a coroutine.
class Task
----------
.. class:: Task()
This object wraps a coroutine into a running task. Tasks can be waited on
using ``await task``, which will wait for the task to complete and return
the return value of the task.
Tasks should not be created directly, rather use `create_task` to create them.
.. method:: Task.cancel()
Cancel the task by injecting a ``CancelledError`` into it. The task may
or may not ignore this exception.
class Event
-----------
.. class:: Event()
Create a new event which can be used to synchronise tasks. Events start
in the cleared state.
.. method:: Event.is_set()
Returns ``True`` if the event is set, ``False`` otherwise.
.. method:: Event.set()
Set the event. Any tasks waiting on the event will be scheduled to run.
.. method:: Event.clear()
Clear the event.
.. method:: Event.wait()
Wait for the event to be set. If the event is already set then it returns
immediately.
This is a coroutine.
class Lock
----------
.. class:: Lock()
Create a new lock which can be used to coordinate tasks. Locks start in
the unlocked state.
In addition to the methods below, locks can be used in an ``async with`` statement.
.. method:: Lock.locked()
Returns ``True`` if the lock is locked, otherwise ``False``.
.. method:: Lock.acquire()
Wait for the lock to be in the unlocked state and then lock it in an atomic
way. Only one task can acquire the lock at any one time.
This is a coroutine.
.. method:: Lock.release()
Release the lock. If any tasks are waiting on the lock then the next one in the
queue is scheduled to run and the lock remains locked. Otherwise, no tasks are
waiting an the lock becomes unlocked.
TCP stream connections
----------------------
.. function:: open_connection(host, port)
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.
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
the connection could not be made.
This is a coroutine.
.. function:: start_server(callback, host, port, backlog=5)
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.
Returns a `Server` object.
This is a coroutine.
.. class:: Stream()
This represents a TCP stream connection. To minimise code this class implements
both a reader and a writer, and both ``StreamReader`` and ``StreamWriter`` alias to
this class.
.. method:: Stream.get_extra_info(v)
Get extra information about the stream, given by *v*. The valid values for *v* are:
``peername``.
.. method:: Stream.close()
Close the stream.
.. method:: Stream.wait_closed()
Wait for the stream to close.
This is a coroutine.
.. method:: Stream.read(n)
Read up to *n* bytes and return them.
This is a coroutine.
.. method:: Stream.readline()
Read a line and return it.
This is a coroutine.
.. method:: Stream.write(buf)
Accumulated *buf* to the output buffer. The data is only flushed when
`Stream.drain` is called. It is recommended to call `Stream.drain` immediately
after calling this function.
.. method:: Stream.drain()
Drain (write) all buffered output data out to the stream.
This is a coroutine.
.. class:: Server()
This represents the server class returned from `start_server`. It can be used
in an ``async with`` statement to close the server upon exit.
.. method:: Server.close()
Close the server.
.. method:: Server.wait_closed()
Wait for the server to close.
This is a coroutine.
Event Loop
----------
.. function:: get_event_loop()
Return the event loop used to schedule and run tasks. See `Loop`.
.. function:: new_event_loop()
Reset the event loop and return it.
Note: since MicroPython only has a single event loop this function just
resets the loop's state, it does not create a new one.
.. class:: Loop()
This represents the object which schedules and runs tasks. It cannot be
created, use `get_event_loop` instead.
.. method:: Loop.create_task(coro)
Create a task from the given *coro* and return the new `Task` object.
.. method:: Loop.run_forever()
Run the event loop until `stop()` is called.
.. method:: Loop.run_until_complete(awaitable)
Run the given *awaitable* until it completes. If *awaitable* is not a task
then it will be promoted to one.
.. method:: Loop.stop()
Stop the event loop.
.. method:: Loop.close()
Close the event loop.
.. method:: Loop.set_exception_handler(handler)
Set the exception handler to call when a Task raises an exception that is not
caught. The *handler* should accept two arguments: ``(loop, context)``.
.. method:: Loop.get_exception_handler()
Get the current exception handler. Returns the handler, or ``None`` if no
custom handler is set.
.. method:: Loop.default_exception_handler(context)
The default exception handler that is called.
.. method:: Loop.call_exception_handler(context)
Call the current exception handler. The argument *context* is passed through and
is a dictionary containing keys: ``'message'``, ``'exception'``, ``'future'``.

View File

@ -6,8 +6,8 @@
This module provides an interface to a Bluetooth controller on a board.
Currently this supports Bluetooth Low Energy (BLE) in Central, Peripheral,
Broadcaster, and Observer roles, and a device may operate in multiple
roles concurrently.
Broadcaster, and Observer roles, as well as GATT Server and Client. A device
may operate in multiple roles concurrently.
This API is intended to match the low-level Bluetooth protocol and provide
building-blocks for higher-level abstractions such as specific device types.
@ -28,15 +28,15 @@ Constructor
Configuration
-------------
.. method:: BLE.active([active])
.. method:: BLE.active([active], /)
Optionally changes the active state of the BLE radio, and returns the
current state.
The radio must be made active before using any other methods on this class.
.. method:: BLE.config('param')
BLE.config(param=value, ...)
.. method:: BLE.config('param', /)
BLE.config(*, param=value, ...)
Get or set configuration values of the BLE interface. To get a value the
parameter name should be quoted as a string, and just one parameter is
@ -45,34 +45,65 @@ Configuration
Currently supported values are:
- ``'mac'``: Returns the device MAC address. If a device has a fixed address
(e.g. PYBD) then it will be returned. Otherwise (e.g. ESP32) a random
address will be generated when the BLE interface is made active.
- ``'mac'``: The current address in use, depending on the current address mode.
This returns a tuple of ``(addr_type, addr)``.
- ``'rxbuf'``: Set the size in bytes of the internal buffer used to store
See :meth:`gatts_write <BLE.gap_scan>` for details about address type.
This may only be queried while the interface is currently active.
- ``'addr_mode'``: Sets the address mode. Values can be:
* 0x00 - PUBLIC - Use the controller's public address.
* 0x01 - RANDOM - Use a generated static address.
* 0x02 - RPA - Use resolvable private addresses.
* 0x03 - NRPA - Use non-resolvable private addresses.
By default the interface mode will use a PUBLIC address if available, otherwise
it will use a RANDOM address.
- ``'gap_name'``: Get/set the GAP device name used by service 0x1800,
characteristic 0x2a00. This can be set at any time and changed multiple
times.
- ``'rxbuf'``: Get/set the size in bytes of the internal buffer used to store
incoming events. This buffer is global to the entire BLE driver and so
handles incoming data for all events, including all characteristics.
Increasing this allows better handling of bursty incoming data (for
example scan results) and the ability for a central role to receive
larger characteristic values.
example scan results) and the ability to receive larger characteristic values.
- ``'mtu'``: Get/set the MTU that will be used during an MTU exchange. The
resulting MTU will be the minimum of this and the remote device's MTU.
MTU exchange will not happen automatically (unless the remote device initiates
it), and must be manually initiated with
:meth:`gattc_exchange_mtu<BLE.gattc_exchange_mtu>`.
Use the ``_IRQ_MTU_EXCHANGED`` event to discover the MTU for a given connection.
Event Handling
--------------
.. method:: BLE.irq(handler, trigger=0xffff)
.. method:: BLE.irq(handler, /)
Registers a callback for events from the BLE stack. The *handler* takes two
arguments, ``event`` (which will be one of the codes below) and ``data``
(which is an event-specific tuple of values).
The optional *trigger* parameter allows you to set a mask of events that
your program is interested in. The default is all events.
**Note:** As an optimisation to prevent unnecessary allocations, the ``addr``,
``adv_data``, ``char_data``, ``notify_data``, and ``uuid`` entries in the
tuples are read-only memoryview instances pointing to ubluetooth's internal
ringbuffer, and are only valid during the invocation of the IRQ handler
function. If your program needs to save one of these values to access after
the IRQ handler has returned (e.g. by saving it in a class instance or global
variable), then it needs to take a copy of the data, either by using ``bytes()``
or ``bluetooth.UUID()``, like this::
Note: the ``addr``, ``adv_data`` and ``uuid`` entries in the tuples are
references to data managed by the :mod:`ubluetooth` module (i.e. the same
instance will be re-used across multiple calls to the event handler). If
your program wants to use this data outside of the handler, then it must
copy them first, e.g. by using ``bytes(addr)`` or ``bluetooth.UUID(uuid)``.
connected_addr = bytes(addr) # equivalently: adv_data, char_data, or notify_data
matched_uuid = bluetooth.UUID(uuid)
For example, the IRQ handler for a scan result might inspect the ``adv_data``
to decide if it's the correct device, and only then copy the address data to be
used elsewhere in the program. And to print data from within the IRQ handler,
``print(bytes(addr))`` will be needed.
An event handler showing all possible events::
@ -84,17 +115,17 @@ Event Handling
# A central has disconnected from this peripheral.
conn_handle, addr_type, addr = data
elif event == _IRQ_GATTS_WRITE:
# A central has written to this characteristic or descriptor.
# A client has written to this characteristic or descriptor.
conn_handle, attr_handle = data
elif event == _IRQ_GATTS_READ_REQUEST:
# A central has issued a read. Note: this is a hard IRQ.
# A client has issued a read. Note: this is a hard IRQ.
# Return None to deny the read.
# Note: This event is not supported on ESP32.
conn_handle, attr_handle = data
elif event == _IRQ_SCAN_RESULT:
# A single scan result.
addr_type, addr, connectable, rssi, adv_data = data
elif event == _IRQ_SCAN_COMPLETE:
addr_type, addr, adv_type, rssi, adv_data = data
elif event == _IRQ_SCAN_DONE:
# Scan duration finished or manually stopped.
pass
elif event == _IRQ_PERIPHERAL_CONNECT:
@ -106,43 +137,75 @@ Event Handling
elif event == _IRQ_GATTC_SERVICE_RESULT:
# Called for each service found by gattc_discover_services().
conn_handle, start_handle, end_handle, uuid = data
elif event == _IRQ_GATTC_SERVICE_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, status = data
elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
# Called for each characteristic found by gattc_discover_services().
conn_handle, def_handle, value_handle, properties, uuid = data
elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, status = data
elif event == _IRQ_GATTC_DESCRIPTOR_RESULT:
# Called for each descriptor found by gattc_discover_descriptors().
conn_handle, dsc_handle, uuid = data
elif event == _IRQ_GATTC_DESCRIPTOR_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, status = data
elif event == _IRQ_GATTC_READ_RESULT:
# A gattc_read() has completed.
conn_handle, value_handle, char_data = data
elif event == _IRQ_GATTC_WRITE_STATUS:
elif event == _IRQ_GATTC_READ_DONE:
# A gattc_read() has completed.
# Note: The value_handle will be zero on btstack (but present on NimBLE).
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, value_handle, status = data
elif event == _IRQ_GATTC_WRITE_DONE:
# A gattc_write() has completed.
# Note: The value_handle will be zero on btstack (but present on NimBLE).
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, value_handle, status = data
elif event == _IRQ_GATTC_NOTIFY:
# A peripheral has sent a notify request.
# A server has sent a notify request.
conn_handle, value_handle, notify_data = data
elif event == _IRQ_GATTC_INDICATE:
# A peripheral has sent an indicate request.
# A server has sent an indicate request.
conn_handle, value_handle, notify_data = data
elif event == _IRQ_GATTS_INDICATE_DONE:
# A client has acknowledged the indication.
# Note: Status will be zero on successful acknowledgment, implementation-specific value otherwise.
conn_handle, value_handle, status = data
elif event == _IRQ_MTU_EXCHANGED:
# MTU exchange complete (either initiated by us or the remote device).
conn_handle, mtu = data
The event codes are::
from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_GATTS_WRITE = const(1 << 2)
_IRQ_GATTS_READ_REQUEST = const(1 << 3)
_IRQ_SCAN_RESULT = const(1 << 4)
_IRQ_SCAN_COMPLETE = const(1 << 5)
_IRQ_PERIPHERAL_CONNECT = const(1 << 6)
_IRQ_PERIPHERAL_DISCONNECT = const(1 << 7)
_IRQ_GATTC_SERVICE_RESULT = const(1 << 8)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(1 << 10)
_IRQ_GATTC_READ_RESULT = const(1 << 11)
_IRQ_GATTC_WRITE_STATUS = const(1 << 12)
_IRQ_GATTC_NOTIFY = const(1 << 13)
_IRQ_GATTC_INDICATE = const(1 << 14)
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)
_IRQ_GATTC_SERVICE_RESULT = const(9)
_IRQ_GATTC_SERVICE_DONE = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE = const(14)
_IRQ_GATTC_READ_RESULT = const(15)
_IRQ_GATTC_READ_DONE = const(16)
_IRQ_GATTC_WRITE_DONE = const(17)
_IRQ_GATTC_NOTIFY = const(18)
_IRQ_GATTC_INDICATE = const(19)
_IRQ_GATTS_INDICATE_DONE = const(20)
_IRQ_MTU_EXCHANGED = const(21)
In order to save space in the firmware, these constants are not included on the
:mod:`ubluetooth` module. Add the ones that you need from the list above to your
@ -152,7 +215,7 @@ program.
Broadcaster Role (Advertiser)
-----------------------------
.. method:: BLE.gap_advertise(interval_us, adv_data=None, resp_data=None, connectable=True)
.. method:: BLE.gap_advertise(interval_us, adv_data=None, *, resp_data=None, connectable=True)
Starts advertising at the specified interval (in **micro**\ seconds). This
interval will be rounded down to the nearest 625us. To stop advertising, set
@ -162,7 +225,7 @@ Broadcaster Role (Advertiser)
protocol (e.g. ``bytes``, ``bytearray``, ``str``). *adv_data* is included
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
**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
broadcaster to resume advertising with just ``gap_advertise(interval_us)``.
To clear the advertising payload pass an empty ``bytes``, i.e. ``b''``.
@ -171,7 +234,7 @@ Broadcaster Role (Advertiser)
Observer Role (Scanner)
-----------------------
.. method:: BLE.gap_scan(duration_ms, [interval_us], [window_us])
.. method:: BLE.gap_scan(duration_ms, interval_us=1280000, window_us=11250, active=False, /)
Run a scan operation lasting for the specified duration (in **milli**\ seconds).
@ -185,34 +248,95 @@ Observer Role (Scanner)
interval and window are 1.28 seconds and 11.25 milliseconds respectively
(background scanning).
For each scan result, the ``_IRQ_SCAN_RESULT`` event will be raised.
For each scan result the ``_IRQ_SCAN_RESULT`` event will be raised, with event
data ``(addr_type, addr, adv_type, rssi, adv_data)``.
``addr_type`` values indicate public or random addresses:
* 0x00 - PUBLIC
* 0x01 - RANDOM (either static, RPA, or NRPA, the type is encoded in the address itself)
``adv_type`` values correspond to the Bluetooth Specification:
* 0x00 - ADV_IND - connectable and scannable undirected advertising
* 0x01 - ADV_DIRECT_IND - connectable directed advertising
* 0x02 - ADV_SCAN_IND - scannable undirected advertising
* 0x03 - ADV_NONCONN_IND - non-connectable undirected advertising
* 0x04 - SCAN_RSP - scan response
``active`` can be set ``True`` if you want to receive scan responses in the results.
When scanning is stopped (either due to the duration finishing or when
explicitly stopped), the ``_IRQ_SCAN_COMPLETE`` event will be raised.
explicitly stopped), the ``_IRQ_SCAN_DONE`` event will be raised.
Peripheral Role (GATT Server)
-----------------------------
Central Role
------------
A BLE peripheral has a set of registered services. Each service may contain
A central device can connect to peripherals that it has discovered using the observer role (see :meth:`gap_scan<BLE.gap_scan>`) or with a known address.
.. method:: BLE.gap_connect(addr_type, addr, scan_duration_ms=2000, /)
Connect to a peripheral.
See :meth:`gap_scan <BLE.gap_scan>` for details about address types.
On success, the ``_IRQ_PERIPHERAL_CONNECT`` event will be raised.
Peripheral Role
---------------
A peripheral device is expected to send connectable advertisements (see
:meth:`gap_advertise<BLE.gap_advertise>`). It will usually be acting as a GATT
server, having first registered services and characteristics using
:meth:`gatts_register_services<BLE.gatts_register_services>`.
When a central connects, the ``_IRQ_CENTRAL_CONNECT`` event will be raised.
Central & Peripheral Roles
--------------------------
.. method:: BLE.gap_disconnect(conn_handle, /)
Disconnect the specified connection handle. This can either be a
central that has connected to this device (if acting as a peripheral)
or a peripheral that was previously connected to by this device (if acting
as a central).
On success, the ``_IRQ_PERIPHERAL_DISCONNECT`` or ``_IRQ_CENTRAL_DISCONNECT``
event will be raised.
Returns ``False`` if the connection handle wasn't connected, and ``True``
otherwise.
GATT Server
-----------
A GATT server has a set of registered services. Each service may contain
characteristics, which each have a value. Characteristics can also contain
descriptors, which themselves have values.
These values are stored locally, and are accessed by their "value handle" which
is generated during service registration. They can also be read from or written
to by a remote central device. Additionally, a peripheral can "notify" a
characteristic to a connected central via a connection handle.
to by a remote client device. Additionally, a server can "notify" a
characteristic to a connected client via a connection handle.
A device in either central or peripheral roles may function as a GATT server,
however in most cases it will be more common for a peripheral device to act
as the server.
Characteristics and descriptors have a default maximum size of 20 bytes.
Anything written to them by a central will be truncated to this length. However,
Anything written to them by a client will be truncated to this length. However,
any local write will increase the maximum size, so if you want to allow larger
writes from a central to a given characteristic, use
writes from a client to a given characteristic, use
:meth:`gatts_write<BLE.gatts_write>` after registration. e.g.
``gatts_write(char_handle, bytes(100))``.
.. method:: BLE.gatts_register_services(services_definition)
.. method:: BLE.gatts_register_services(services_definition, /)
Configures the peripheral with the specified services, replacing any
Configures the server with the specified services, replacing any
existing services.
*services_definition* is a list of **services**, where each **service** is a
@ -245,30 +369,42 @@ writes from a central to a given characteristic, use
( (hr,), (tx, rx,), ) = bt.gatts_register_services(SERVICES)
The three value handles (``hr``, ``tx``, ``rx``) can be used with
:meth:`gatts_read <BLE.gatts_read>`, :meth:`gatts_write <BLE.gatts_write>`,
and :meth:`gatts_notify <BLE.gatts_notify>`.
:meth:`gatts_read <BLE.gatts_read>`, :meth:`gatts_write <BLE.gatts_write>`, :meth:`gatts_notify <BLE.gatts_notify>`, and
:meth:`gatts_indicate <BLE.gatts_indicate>`.
**Note:** Advertising must be stopped before registering services.
.. method:: BLE.gatts_read(value_handle)
.. method:: BLE.gatts_read(value_handle, /)
Reads the local value for this handle (which has either been written by
:meth:`gatts_write <BLE.gatts_write>` or by a remote central).
:meth:`gatts_write <BLE.gatts_write>` or by a remote client).
.. method:: BLE.gatts_write(value_handle, data)
.. method:: BLE.gatts_write(value_handle, data, /)
Writes the local value for this handle, which can be read by a central.
Writes the local value for this handle, which can be read by a client.
.. method:: BLE.gatts_notify(conn_handle, value_handle, [data])
.. method:: BLE.gatts_notify(conn_handle, value_handle, data=None, /)
Notifies a connected central that this value has changed and that it should
issue a read of the current value from this peripheral.
Sends a notification request to a connected client.
If *data* is specified, then the that value is sent to the central as part
of the notification, avoiding the need for a separate read request. Note
that this will not update the local value stored.
If *data* is not ``None``, then that value is sent to the client as part of
the notification. The local value will not be modified.
.. method:: BLE.gatts_set_buffer(value_handle, len, append=False)
Otherwise, if *data* is ``None``, then the current local value (as
set with :meth:`gatts_write <BLE.gatts_write>`) will be sent.
.. method:: BLE.gatts_indicate(conn_handle, value_handle, /)
Sends an indication request to a connected client.
**Note:** This does not currently support sending a custom value, it will
always send the current local value (as set with :meth:`gatts_write
<BLE.gatts_write>`).
On acknowledgment (or failure, e.g. timeout), the
``_IRQ_GATTS_INDICATE_DONE`` event will be raised.
.. method:: BLE.gatts_set_buffer(value_handle, len, append=False, /)
Sets the internal buffer size for a value in bytes. This will limit the
largest possible write that can be received. The default is 20.
@ -279,70 +415,82 @@ writes from a central to a given characteristic, use
be cleared after reading. This feature is useful when implementing something
like the Nordic UART Service.
GATT Client
-----------
Central Role (GATT Client)
--------------------------
A GATT client can discover and read/write characteristics on a remote GATT server.
.. method:: BLE.gap_connect(addr_type, addr, scan_duration_ms=2000)
It is more common for a central role device to act as the GATT client, however
it's also possible for a peripheral to act as a client in order to discover
information about the central that has connected to it (e.g. to read the
device name from the device information service).
Connect to a peripheral.
.. method:: BLE.gattc_discover_services(conn_handle, uuid=None, /)
On success, the ``_IRQ_PERIPHERAL_CONNECT`` event will be raised.
Query a connected server for its services.
.. method:: BLE.gap_disconnect(conn_handle)
Optionally specify a service *uuid* to query for that service only.
Disconnect the specified connection handle.
For each service discovered, the ``_IRQ_GATTC_SERVICE_RESULT`` event will
be raised, followed by ``_IRQ_GATTC_SERVICE_DONE`` on completion.
On success, the ``_IRQ_PERIPHERAL_DISCONNECT`` event will be raised.
.. method:: BLE.gattc_discover_characteristics(conn_handle, start_handle, end_handle, uuid=None, /)
Returns ``False`` if the connection handle wasn't connected, and ``True``
otherwise.
Query a connected server for characteristics in the specified range.
.. method:: BLE.gattc_discover_services(conn_handle)
Optionally specify a characteristic *uuid* to query for that
characteristic only.
Query a connected peripheral for its services.
For each service discovered, the ``_IRQ_GATTC_SERVICE_RESULT`` event will be
raised.
.. method:: BLE.gattc_discover_characteristics(conn_handle, start_handle, end_handle)
Query a connected peripheral for characteristics in the specified range.
You can use ``start_handle=1``, ``end_handle=0xffff`` to search for a
characteristic in any service.
For each characteristic discovered, the ``_IRQ_GATTC_CHARACTERISTIC_RESULT``
event will be raised.
event will be raised, followed by ``_IRQ_GATTC_CHARACTERISTIC_DONE`` on completion.
.. method:: BLE.gattc_discover_descriptors(conn_handle, start_handle, end_handle)
.. method:: BLE.gattc_discover_descriptors(conn_handle, start_handle, end_handle, /)
Query a connected peripheral for descriptors in the specified range.
Query a connected server for descriptors in the specified range.
For each descriptor discovered, the ``_IRQ_GATTC_DESCRIPTOR_RESULT`` event
will be raised.
will be raised, followed by ``_IRQ_GATTC_DESCRIPTOR_DONE`` on completion.
.. method:: BLE.gattc_read(conn_handle, value_handle)
.. method:: BLE.gattc_read(conn_handle, value_handle, /)
Issue a remote read to a connected peripheral for the specified
Issue a remote read to a connected server for the specified
characteristic or descriptor handle.
On success, the ``_IRQ_GATTC_READ_RESULT`` event will be raised.
When a value is available, the ``_IRQ_GATTC_READ_RESULT`` event will be
raised. Additionally, the ``_IRQ_GATTC_READ_DONE`` will be raised.
.. method:: BLE.gattc_write(conn_handle, value_handle, data, mode=0)
.. method:: BLE.gattc_write(conn_handle, value_handle, data, mode=0, /)
Issue a remote write to a connected peripheral for the specified
Issue a remote write to a connected server for the specified
characteristic or descriptor handle.
The argument *mode* specifies the write behaviour, with the currently
supported values being:
* ``mode=0`` (default) is a write-without-response: the write will
be sent to the remote peripheral but no confirmation will be
be sent to the remote server but no confirmation will be
returned, and no event will be raised.
* ``mode=1`` is a write-with-response: the remote peripheral is
* ``mode=1`` is a write-with-response: the remote server is
requested to send a response/acknowledgement that it received the
data.
If a response is received from the remote peripheral the
``_IRQ_GATTC_WRITE_STATUS`` event will be raised.
If a response is received from the remote server the
``_IRQ_GATTC_WRITE_DONE`` event will be raised.
.. method:: BLE.gattc_exchange_mtu(conn_handle, /)
Initiate MTU exchange with a connected server, using the preferred MTU
set using ``BLE.config(mtu=value)``.
The ``_IRQ_MTU_EXCHANGED`` event will be raised when MTU exchange
completes.
**Note:** MTU exchange is typically initiated by the central. When using
the BlueKitchen stack in the central role, it does not support a remote
peripheral initiating the MTU exchange. NimBLE works for both roles.
class UUID
@ -352,7 +500,7 @@ class UUID
Constructor
-----------
.. class:: UUID(value)
.. class:: UUID(value, /)
Creates a UUID instance with the specified **value**.

View File

@ -180,7 +180,7 @@ Following are encoding examples for various field types:
Module contents
---------------
.. class:: struct(addr, descriptor, layout_type=NATIVE)
.. class:: struct(addr, descriptor, layout_type=NATIVE, /)
Instantiate a "foreign data structure" object based on structure address in
memory, descriptor (encoded as a dictionary), and layout type (see below).
@ -200,7 +200,7 @@ Module contents
Layout type for a native structure - with data endianness and alignment
conforming to the ABI of the system on which MicroPython runs.
.. function:: sizeof(struct, layout_type=NATIVE)
.. function:: sizeof(struct, layout_type=NATIVE, /)
Return size of data structure in bytes. The *struct* argument can be
either a structure class or a specific instantiated structure object

View File

@ -7,7 +7,7 @@
|see_cpython_module| :mod:`python:errno`.
This module provides access to symbolic error codes for `OSError` exception.
A particular inventory of codes depends on `MicroPython port`.
A particular inventory of codes depends on :term:`MicroPython port`.
Constants
---------
@ -16,7 +16,7 @@ Constants
Error codes, based on ANSI C/POSIX standard. All error codes start with
"E". As mentioned above, inventory of the codes depends on
`MicroPython port`. Errors are usually accessible as ``exc.args[0]``
:term:`MicroPython port`. Errors are usually accessible as ``exc.args[0]``
where ``exc`` is an instance of `OSError`. Usage example::
try:

View File

@ -114,7 +114,9 @@ Classes
Get the current contents of the underlying buffer which holds data.
.. class:: StringIO(alloc_size)
:noindex:
.. class:: BytesIO(alloc_size)
:noindex:
Create an empty `StringIO`/`BytesIO` object, preallocated to hold up
to *alloc_size* number of bytes. That means that writing that amount

View File

@ -112,7 +112,7 @@ Filesystem access
Terminal redirection and duplication
------------------------------------
.. function:: dupterm(stream_object, index=0)
.. function:: dupterm(stream_object, index=0, /)
Duplicate or switch the MicroPython terminal (the REPL) on the given `stream`-like
object. The *stream_object* argument must be a native stream object, or derive
@ -144,7 +144,7 @@ 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)
.. 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()``
@ -178,7 +178,7 @@ represented by VFS classes.
Build a FAT filesystem on *block_dev*.
.. class:: VfsLfs1(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
@ -187,23 +187,31 @@ represented by VFS classes.
See :ref:`filesystem` for more information.
.. staticmethod:: mkfs(block_dev)
.. 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)
.. 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 `uos.stat` on files without timestamps will return 0 for the timestamp.
See :ref:`filesystem` for more information.
.. staticmethod:: mkfs(block_dev)
.. staticmethod:: mkfs(block_dev, readsize=32, progsize=32, lookahead=32)
Build a Lfs2 filesystem on *block_dev*.
@ -218,11 +226,19 @@ represented by VFS classes.
Block devices
-------------
A block device is an object which implements the block protocol, which is a set
of methods described below by the :class:`AbstractBlockDev` class. A concrete
implementation of this class will usually allow access to the memory-like
functionality a piece of hardware (like flash memory). A block device can be
used by a particular filesystem driver to store the data for its filesystem.
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 ``uos``
methods.
See :ref:`filesystem` for example implementations of block devices using the
two variants of the block protocol described below.
.. _block-device-interface:
@ -244,7 +260,7 @@ that the block device supports the extended interface.
dependent on the specific block device.
.. method:: readblocks(block_num, buf)
.. method:: readblocks(block_num, buf, offset)
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
@ -259,7 +275,7 @@ that the block device supports the extended interface.
The number of bytes to read is given by the length of *buf*.
.. method:: writeblocks(block_num, buf)
.. method:: writeblocks(block_num, buf, offset)
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.
@ -294,5 +310,12 @@ that the block device supports the extended interface.
(*arg* is unused)
- 6 -- erase a block, *arg* is the block number to erase
See :ref:`filesystem` for example implementations of block devices using both
protocols.
As a minimum ``ioctl(4, ...)`` must be intercepted; for littlefs
``ioctl(6, ...)`` must also be intercepted. The need for others is
hardware dependent.
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.

View File

@ -124,7 +124,7 @@ Functions
string for first position which matches regex (which still may be
0 if regex is anchored).
.. function:: sub(regex_str, replace, string, count=0, flags=0)
.. function:: sub(regex_str, replace, string, count=0, flags=0, /)
Compile *regex_str* and search for it in *string*, replacing all matches
with *replace*, and returning the new string.
@ -138,12 +138,12 @@ Functions
If *count* is specified and non-zero then substitution will stop after
this many substitutions are made. The *flags* argument is ignored.
Note: availability of this function depends on `MicroPython port`.
Note: availability of this function depends on :term:`MicroPython port`.
.. data:: DEBUG
Flag value, display debug information about compiled expression.
(Availability depends on `MicroPython port`.)
(Availability depends on :term:`MicroPython port`.)
.. _regex:
@ -156,14 +156,14 @@ Compiled regular expression. Instances of this class are created using
.. method:: regex.match(string)
regex.search(string)
regex.sub(replace, string, count=0, flags=0)
regex.sub(replace, string, count=0, flags=0, /)
Similar to the module-level functions :meth:`match`, :meth:`search`
and :meth:`sub`.
Using methods is (much) more efficient if the same regex is applied to
multiple strings.
.. method:: regex.split(string, max_split=-1)
.. method:: regex.split(string, max_split=-1, /)
Split a *string* using regex. If *max_split* is given, it specifies
maximum number of splits to perform. Returns list of strings (there
@ -184,7 +184,7 @@ to the replacement function in `sub()`.
Return a tuple containing all the substrings of the groups of the match.
Note: availability of this method depends on `MicroPython port`.
Note: availability of this method depends on :term:`MicroPython port`.
.. method:: match.start([index])
match.end([index])
@ -193,10 +193,10 @@ to the replacement function in `sub()`.
substring group that was matched. *index* defaults to the entire
group, otherwise it will select a group.
Note: availability of these methods depends on `MicroPython port`.
Note: availability of these methods depends on :term:`MicroPython port`.
.. method:: match.span([index])
Returns the 2-tuple ``(match.start(index), match.end(index))``.
Note: availability of this method depends on `MicroPython port`.
Note: availability of this method depends on :term:`MicroPython port`.

View File

@ -58,7 +58,7 @@ Methods
Modify the *eventmask* for *obj*. If *obj* is not registered, `OSError`
is raised with error of ENOENT.
.. method:: poll.poll(timeout=-1)
.. method:: poll.poll(timeout=-1, /)
Wait for at least one of the registered objects to become ready or have an
exceptional condition, with optional timeout in milliseconds (if *timeout*
@ -81,7 +81,7 @@ Methods
Tuples returned may contain more than 2 elements as described above.
.. method:: poll.ipoll(timeout=-1, flags=0)
.. method:: poll.ipoll(timeout=-1, flags=0, /)
Like :meth:`poll.poll`, but instead returns an iterator which yields a
`callee-owned tuple`. This function provides an efficient, allocation-free

View File

@ -37,8 +37,8 @@ power) and portable way to work with addresses.
However, ``socket`` module (note the difference with native MicroPython
``usocket`` module described here) provides CPython-compatible way to specify
addresses using tuples, as described below. Note that depending on a
`MicroPython port`, ``socket`` module can be builtin or need to be
installed from `micropython-lib` (as in the case of `MicroPython Unix port`),
:term:`MicroPython port`, ``socket`` module can be builtin or need to be
installed from `micropython-lib` (as in the case of :term:`MicroPython Unix port`),
and some ports still accept only numeric addresses in the tuple format,
and require to use `getaddrinfo` function to resolve domain names.
@ -61,12 +61,12 @@ Tuple address format for ``socket`` module:
must be 0. *scopeid* is the interface scope identifier for link-local
addresses. Note the domain names are not accepted as *ipv6_address*,
they should be resolved first using `usocket.getaddrinfo()`. Availability
of IPv6 support depends on a `MicroPython port`.
of IPv6 support depends on a :term:`MicroPython port`.
Functions
---------
.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)
.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, /)
Create a new socket using the given address family, socket type and
protocol number. Note that specifying *proto* in most cases is not
@ -79,9 +79,9 @@ Functions
# Create DGRAM UDP socket
socket(AF_INET, SOCK_DGRAM)
.. function:: getaddrinfo(host, port, af=0, type=0, proto=0, flags=0)
.. function:: getaddrinfo(host, port, af=0, type=0, proto=0, flags=0, /)
Translate the host/port argument into a sequence of 5-tuples that contain all the
Translate the host/port argument into a sequence of 5-tuples that contain all the
necessary arguments for creating a socket connected to that service. Arguments
*af*, *type*, and *proto* (which have the same meaning as for the `socket()` function)
can be used to filter which kind of addresses are returned. If a parameter is not
@ -141,7 +141,7 @@ Constants
.. data:: AF_INET
AF_INET6
Address family types. Availability depends on a particular `MicroPython port`.
Address family types. Availability depends on a particular :term:`MicroPython port`.
.. data:: SOCK_STREAM
SOCK_DGRAM
@ -151,7 +151,7 @@ Constants
.. data:: IPPROTO_UDP
IPPROTO_TCP
IP protocol numbers. Availability depends on a particular `MicroPython port`.
IP protocol numbers. Availability depends on a particular :term:`MicroPython port`.
Note that you don't need to specify these in a call to `usocket.socket()`,
because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and
`SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants
@ -160,12 +160,12 @@ Constants
.. data:: usocket.SOL_*
Socket option levels (an argument to `setsockopt()`). The exact
inventory depends on a `MicroPython port`.
inventory depends on a :term:`MicroPython port`.
.. data:: usocket.SO_*
Socket options (an argument to `setsockopt()`). The exact
inventory depends on a `MicroPython port`.
inventory depends on a :term:`MicroPython port`.
Constants specific to WiPy:
@ -185,7 +185,7 @@ Methods
on the socket object will fail. The remote end will receive EOF indication if
supported by protocol.
Sockets are automatically closed when they are garbage-collected, but it is recommended
Sockets are automatically closed when they are garbage-collected, but it is recommended
to `close()` them explicitly as soon you finished working with them.
.. method:: socket.bind(address)
@ -259,7 +259,7 @@ Methods
completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket
is put in blocking mode.
Not every `MicroPython port` supports this method. A more portable and
Not every :term:`MicroPython port` supports this method. A more portable and
generic solution is to use `uselect.poll` object. This allows to wait on
multiple objects at the same time (and not just on sockets, but on generic
`stream` objects which support polling). Example::
@ -293,7 +293,7 @@ Methods
* ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``
* ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)``
.. method:: socket.makefile(mode='rb', buffering=0)
.. method:: socket.makefile(mode='rb', buffering=0, /)
Return a file object associated with the socket. The exact returned type depends on the arguments
given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb').

View File

@ -24,7 +24,7 @@ Functions
:meth:`~usocket.socket.accept()` on a non-SSL listening server socket.
Depending on the underlying module implementation in a particular
`MicroPython port`, some or all keyword arguments above may be not supported.
:term:`MicroPython port`, some or all keyword arguments above may be not supported.
.. warning::

View File

@ -35,7 +35,7 @@ Functions
Unpack from the *data* according to the format string *fmt*.
The return value is a tuple of the unpacked values.
.. function:: unpack_from(fmt, data, offset=0)
.. function:: unpack_from(fmt, data, offset=0, /)
Unpack from the *data* starting at *offset* according to the format string
*fmt*. *offset* may be negative to count from the end of *buffer*. The return

View File

@ -1,7 +1,7 @@
:mod:`sys` -- system specific functions
=======================================
:mod:`usys` -- system specific functions
========================================
.. module:: sys
.. module:: usys
:synopsis: system specific functions
|see_cpython_module| :mod:`python:sys`.
@ -9,7 +9,7 @@
Functions
---------
.. function:: exit(retval=0)
.. function:: exit(retval=0, /)
Terminate current program with a given exit code. Underlyingly, this
function raise as `SystemExit` exception. If an argument is given, its
@ -28,10 +28,10 @@ Functions
This function is a MicroPython extension intended to provide similar
functionality to the :mod:`atexit` module in CPython.
.. function:: print_exception(exc, file=sys.stdout)
.. function:: print_exception(exc, file=usys.stdout, /)
Print exception with a traceback to a file-like object *file* (or
`sys.stdout` by default).
`usys.stdout` by default).
.. admonition:: Difference to CPython
:class: attention
@ -84,7 +84,7 @@ Constants
value directly, but instead count number of bits in it::
bits = 0
v = sys.maxsize
v = usys.maxsize
while v:
bits += 1
v >>= 1
@ -113,7 +113,7 @@ Constants
is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython
reference board. It thus can be used to distinguish one board from another.
If you need to check whether your program runs on MicroPython (vs other
Python implementation), use `sys.implementation` instead.
Python implementation), use `usys.implementation` instead.
.. data:: stderr

View File

@ -36,11 +36,17 @@ behave not as expected.
Functions
---------
.. function:: localtime([secs])
.. function:: gmtime([secs])
localtime([secs])
Convert a time expressed in seconds since the Epoch (see above) into an 8-tuple which
contains: (year, month, mday, hour, minute, second, weekday, yearday)
If secs is not provided or None, then the current time from the RTC is used.
Convert the time *secs* expressed in seconds since the Epoch (see above) into an
8-tuple which contains: ``(year, month, mday, hour, minute, second, weekday, yearday)``
If *secs* is not provided or None, then the current time from the RTC is used.
The `gmtime()` function returns a date-time tuple in UTC, and `localtime()` returns a
date-time tuple in local time.
The format of the entries in the 8-tuple are:
* year includes the century (for example 2014).
* month is 1-12
@ -210,8 +216,9 @@ Functions
function returns number of seconds since a port-specific reference point in time (for
embedded boards without a battery-backed RTC, usually since power up or reset). If you
want to develop portable MicroPython application, you should not rely on this function
to provide higher than second precision. If you need higher precision, use
`ticks_ms()` and `ticks_us()` functions, if you need calendar time,
to provide higher than second precision. If you need higher precision, absolute
timestamps, use `time_ns()`. If relative times are acceptable then use the
`ticks_ms()` and `ticks_us()` functions. If you need calendar time, `gmtime()` or
`localtime()` without an argument is a better choice.
.. admonition:: Difference to CPython
@ -227,3 +234,8 @@ Functions
hardware also lacks battery-powered RTC, so returns number of seconds
since last power-up or from other relative, hardware-specific point
(e.g. reset).
.. function:: time_ns()
Similar to `time()` but returns nanoseconds since the Epoch, as an integer (usually
a big integer, so will allocate on the heap).

View File

@ -14,7 +14,7 @@ is not yet implemented.
Functions
---------
.. function:: decompress(data, wbits=0, bufsize=0)
.. function:: decompress(data, wbits=0, bufsize=0, /)
Return decompressed *data* as bytes. *wbits* is DEFLATE dictionary window
size used during compression (8-15, the dictionary size is power of 2 of
@ -23,7 +23,7 @@ Functions
to be raw DEFLATE stream. *bufsize* parameter is for compatibility with
CPython and is ignored.
.. class:: DecompIO(stream, wbits=0)
.. class:: DecompIO(stream, wbits=0, /)
Create a `stream` wrapper which allows transparent decompression of
compressed data in another *stream*. This allows to process compressed

View File

@ -6,6 +6,7 @@ if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set SPHINXOPTS=-W --keep-going
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (

View File

@ -1,7 +1,7 @@
.. _pyboard_tutorial_switch:
The Switch, callbacks and interrupts
====================================
Switches, callbacks and interrupts
==================================
The pyboard has 2 small switches, labelled USR and RST. The RST switch
is a hard-reset switch, and if you press it then it restarts the pyboard

View File

@ -1,4 +1,4 @@
Assembler Directives
Assembler directives
====================
Labels

View File

@ -1,5 +1,5 @@
Floating Point instructions
==============================
Floating point instructions
===========================
These instructions support the use of the ARM floating point coprocessor
(on platforms such as the Pyboard which are equipped with one). The FPU
@ -61,7 +61,7 @@ Where ``[Rn + offset]`` denotes the memory address obtained by adding Rn to the
is specified in bytes. Since each float value occupies a 32 bit word, when accessing arrays of
floats the offset must always be a multiple of four bytes.
Data Comparison
Data comparison
---------------
* vcmp(Sd, Sm)

View File

@ -1,6 +1,6 @@
.. _asm_thumb2_index:
Inline Assembler for Thumb2 architectures
Inline assembler for Thumb2 architectures
=========================================
This document assumes some familiarity with assembly language programming and should be read after studying
@ -25,7 +25,7 @@ This enables the effect of instructions to be demonstrated in Python. In certain
because Python doesn't support concepts such as indirection. The pseudocode employed in such cases is
described on the relevant page.
Instruction Categories
Instruction categories
----------------------
The following sections details the subset of the ARM Thumb-2 instruction set supported by MicroPython.

View File

@ -1,4 +1,4 @@
Logical & Bitwise instructions
Logical & bitwise instructions
==============================
Document conventions

View File

@ -1,6 +1,6 @@
.. _constrained:
MicroPython on Microcontrollers
MicroPython on microcontrollers
===============================
MicroPython is designed to be capable of running on microcontrollers. These
@ -12,7 +12,7 @@ based on a variety of architectures, the methods presented are generic: in some
cases it will be necessary to obtain detailed information from platform specific
documentation.
Flash Memory
Flash memory
------------
On the Pyboard the simple way to address the limited capacity is to fit a micro
@ -58,7 +58,7 @@ heap fragmentation. In general terms it is best to minimise the repeated
creation and destruction of objects. The reason for this is covered in the
section covering the `heap`_.
Compilation Phase
Compilation phase
~~~~~~~~~~~~~~~~~
When a module is imported, MicroPython compiles the code to bytecode which is
@ -85,7 +85,7 @@ imported in the usual way. Alternatively some or all modules may be implemented
as frozen bytecode: on most platforms this saves even more RAM as the bytecode
is run directly from flash rather than being stored in RAM.
Execution Phase
Execution phase
~~~~~~~~~~~~~~~
There are a number of coding techniques for reducing RAM usage.
@ -292,7 +292,7 @@ The Q(xxx) lines should be gone.
.. _heap:
The Heap
The heap
--------
When a running program instantiates an object the necessary RAM is allocated
@ -391,7 +391,7 @@ Symbol Meaning
Each letter represents a single block of memory, a block being 16 bytes. So each
line of the heap dump represents 0x400 bytes or 1KiB of RAM.
Control of Garbage Collection
Control of garbage collection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A GC can be demanded at any time by issuing `gc.collect()`. It is advantageous
@ -420,7 +420,7 @@ initialisation the compiler may be starved of RAM when subsequent modules are
imported. If modules do instantiate data on import then `gc.collect()` issued
after the import will ameliorate the problem.
String Operations
String operations
-----------------
MicroPython handles strings in an efficient manner and understanding this can

View File

@ -178,7 +178,8 @@ Board FAT littlefs v1 littlefs v2
==================== ===== =========== ===========
pyboard 1.0, 1.1, D Yes No Yes
Other STM32 Yes No No
ESP8266 Yes No No
ESP8266 (1M) No No Yes
ESP8266 (2M+) Yes No Yes
ESP32 Yes No Yes
==================== ===== =========== ===========

View File

@ -177,7 +177,7 @@ Glossary
typically accessible on a host PC via USB.
stream
Also known as a "file-like object". An Python object which provides
Also known as a "file-like object". A Python object which provides
sequential read-write access to the underlying data. A stream object
implements a corresponding interface, which consists of methods like
``read()``, ``write()``, ``readinto()``, ``seek()``, ``flush()``,

View File

@ -1,5 +1,5 @@
The MicroPython language
========================
MicroPython language and implementation
=======================================
MicroPython aims to implement the Python 3.4 standard (with selected
features from later versions) with respect to language syntax, and most

View File

@ -29,7 +29,7 @@ This summarises the points detailed below and lists the principal recommendation
* Allocate an emergency exception buffer (see below).
MicroPython Issues
MicroPython issues
------------------
The emergency exception buffer
@ -43,6 +43,11 @@ for the purpose. Debugging is simplified if the following code is included in an
import micropython
micropython.alloc_emergency_exception_buf(100)
The emergency exception buffer can only hold one exception stack trace. This means that if a second exception is
thrown during the handling of an exception while the heap is locked, that second exception's stack trace will
replace the original one - even if the second exception is cleanly handled. This can lead to confusing exception
messages if the buffer is later printed.
Simplicity
~~~~~~~~~~
@ -214,7 +219,7 @@ Exceptions
If an ISR raises an exception it will not propagate to the main loop. The interrupt will be disabled unless the
exception is handled by the ISR code.
General Issues
General issues
--------------
This is merely a brief introduction to the subject of real time programming. Beginners should note
@ -225,7 +230,7 @@ with an appreciation of the following issues.
.. _ISR:
Interrupt Handler Design
Interrupt handler design
~~~~~~~~~~~~~~~~~~~~~~~~
As mentioned above, ISR's should be designed to be as simple as possible. They should always return in a short,
@ -276,7 +281,7 @@ advanced topic beyond the scope of this tutorial.
.. _Critical:
Critical Sections
Critical sections
~~~~~~~~~~~~~~~~~
An example of a critical section of code is one which accesses more than one variable which can be affected by an ISR. If

View File

@ -14,8 +14,8 @@ packages:
1. Python modules and packages are turned into distribution package
archives, and published at the Python Package Index (PyPI).
2. `upip` package manager can be used to install a distribution package
on a `MicroPython port` with networking capabilities (for example,
2. :term:`upip` package manager can be used to install a distribution package
on a :term:`MicroPython port` with networking capabilities (for example,
on the Unix port).
3. For ports without networking capabilities, an "installation image"
can be prepared on the Unix port, and transferred to a device by
@ -51,14 +51,14 @@ even by the smallest devices.
Besides the small compression dictionary size, MicroPython distribution
packages also have other optimizations, like removing any files from
the archive which aren't used by the installation process. In particular,
`upip` package manager doesn't execute ``setup.py`` during installation
:term:`upip` package manager doesn't execute ``setup.py`` during installation
(see below), and thus that file is not included in the archive.
At the same time, these optimizations make MicroPython distribution
packages not compatible with `CPython`'s package manager, ``pip``.
packages not compatible with :term:`CPython`'s package manager, ``pip``.
This isn't considered a big problem, because:
1. Packages can be installed with `upip`, and then can be used with
1. Packages can be installed with :term:`upip`, and then can be used with
CPython (if they are compatible with it).
2. In the other direction, majority of CPython packages would be
incompatible with MicroPython by various reasons, first of all,
@ -73,12 +73,12 @@ resource constrained devices.
------------------------
MicroPython distribution packages are intended to be installed using
the `upip` package manager. `upip` is a Python application which is
the :term:`upip` package manager. :term:`upip` is a Python application which is
usually distributed (as frozen bytecode) with network-enabled
`MicroPython ports <MicroPython port>`. At the very least,
`upip` is available in the `MicroPython Unix port`.
:term:`MicroPython ports <MicroPython port>`. At the very least,
:term:`upip` is available in the :term:`MicroPython Unix port`.
On any `MicroPython port` providing `upip`, it can be accessed as
On any :term:`MicroPython port` providing :term:`upip`, it can be accessed as
following::
import upip
@ -123,12 +123,12 @@ commands which corresponds to the example above are::
Cross-installing packages
-------------------------
For `MicroPython ports <MicroPython port>` without native networking
For :term:`MicroPython ports <MicroPython port>` without native networking
capabilities, the recommend process is "cross-installing" them into a
"directory image" using the `MicroPython Unix port`, and then
"directory image" using the :term:`MicroPython Unix port`, and then
transferring this image to a device by suitable means.
Installing to a directory image involves using ``-p`` switch to `upip`::
Installing to a directory image involves using ``-p`` switch to :term:`upip`::
micropython -m upip install -p install_dir micropython-pystone_lowmem
@ -137,13 +137,13 @@ packages) will be available in the ``install_dir/`` subdirectory. You
would need to transfer contents of this directory (without the
``install_dir/`` prefix) to the device, at the suitable location, where
it can be found by the Python ``import`` statement (see discussion of
the `upip` installation path above).
the :term:`upip` installation path above).
Cross-installing packages with freezing
---------------------------------------
For the low-memory `MicroPython ports <MicroPython port>`, the process
For the low-memory :term:`MicroPython ports <MicroPython port>`, the process
described in the previous section does not provide the most efficient
resource usage,because the packages are installed in the source form,
so need to be compiled to the bytecome on each import. This compilation
@ -160,7 +160,7 @@ mentioned above:
* Filesystem is not required for frozen packages.
Using frozen bytecode requires building the executable (firmware)
for a given `MicroPython port` from the C source code. Consequently,
for a given :term:`MicroPython port` from the C source code. Consequently,
the process is:
1. Follow the instructions for a particular port on setting up a
@ -168,7 +168,7 @@ the process is:
study instructions in ``ports/esp8266/README.md`` and follow them.
Make sure you can build the port and deploy the resulting
executable/firmware successfully before proceeding to the next steps.
2. Build `MicroPython Unix port` and make sure it is in your PATH and
2. Build :term:`MicroPython Unix port` and make sure it is in your PATH and
you can execute ``micropython``.
3. Change to port's directory (e.g. ``ports/esp8266/`` for ESP8266).
4. Run ``make clean-frozen``. This step cleans up any previous
@ -188,7 +188,7 @@ Few notes:
1. Step 5 in the sequence above assumes that the distribution package
is available from PyPI. If that is not the case, you would need
to copy Python source files manually to ``modules/`` subdirectory
of the port port directory. (Note that upip does not support
of the port directory. (Note that upip does not support
installing from e.g. version control repositories).
2. The firmware for baremetal devices usually has size restrictions,
so adding too many frozen modules may overflow it. Usually, you
@ -281,7 +281,7 @@ following calls::
pkg_resources.resource_stream(__name__, "data/page.html")
pkg_resources.resource_stream(__name__, "data/image.png")
You can develop and debug using the `MicroPython Unix port` as usual.
You can develop and debug using the :term:`MicroPython Unix port` as usual.
When time comes to make a distribution package out of it, just use
overridden "sdist" command from sdist_upip.py module as described in
the previous section.

View File

@ -24,8 +24,8 @@ Running ``pyboard.py --help`` gives the following output:
.. code-block:: text
usage: pyboard [-h] [--device DEVICE] [-b BAUDRATE] [-u USER]
[-p PASSWORD] [-c COMMAND] [-w WAIT] [--follow] [-f]
usage: pyboard [-h] [-d DEVICE] [-b BAUDRATE] [-u USER] [-p PASSWORD]
[-c COMMAND] [-w WAIT] [--follow | --no-follow] [-f]
[files [files ...]]
Run scripts on the pyboard.
@ -35,8 +35,8 @@ Running ``pyboard.py --help`` gives the following output:
optional arguments:
-h, --help show this help message and exit
--device DEVICE the serial device or the IP address of the
pyboard
-d DEVICE, --device DEVICE
the serial device or the IP address of the pyboard
-b BAUDRATE, --baudrate BAUDRATE
the baud rate of the serial device
-u USER, --user USER the telnet login username
@ -59,6 +59,17 @@ with the device.::
$ pyboard.py --device /dev/ttyACM0 -c 'print(1+1)'
2
If you are often interacting with the same device, you can set the environment
variable ``PYBOARD_DEVICE`` as an alternative to using the ``--device``
command line option. For example, the following is equivalent to the previous
example::
$ export PYBOARD_DEVICE=/dev/ttyACM0
$ pyboard.py -c 'print(1+1)'
Similarly, the ``PYBOARD_BAUDRATE`` environment variable can be used
to set the default for the ``--baudrate`` option.
Running a script on the device
------------------------------

View File

@ -103,7 +103,7 @@ For example:
KeyboardInterrupt:
>>>
Paste Mode
Paste mode
----------
If you want to paste some code into your terminal window, the auto-indent feature
@ -143,7 +143,7 @@ the auto-indent feature, and changes the prompt from ``>>>`` to ``===``. For exa
Paste Mode allows blank lines to be pasted. The pasted text is compiled as if
it were a file. Pressing Ctrl-D exits paste mode and initiates the compilation.
Soft Reset
Soft reset
----------
A soft reset will reset the python interpreter, but tries not to reset the
@ -196,7 +196,7 @@ So you can use the underscore to save the result in a variable. For example:
15
>>>
Raw Mode
Raw mode
--------
Raw mode is not something that a person would normally use. It is intended for

View File

@ -1,6 +1,6 @@
.. _speed_python:
Maximising MicroPython Speed
Maximising MicroPython speed
============================
.. contents::
@ -40,7 +40,7 @@ the best algorithm is employed. This is a topic for textbooks rather than for a
MicroPython guide but spectacular performance gains can sometimes be achieved
by adopting algorithms known for their efficiency.
RAM Allocation
RAM allocation
~~~~~~~~~~~~~~
To design efficient MicroPython code it is necessary to have an understanding of the
@ -69,7 +69,7 @@ example, objects which support stream interface (e.g., file or UART) provide ``r
method which allocates new buffer for read data, but also a ``readinto()`` method
to read data into an existing buffer.
Floating Point
Floating point
~~~~~~~~~~~~~~
Some MicroPython ports allocate floating point numbers on heap. Some other ports

View File

@ -4,6 +4,6 @@
.. |see_cpython_module| replace::
*This module implements a subset of the corresponding* `CPython` *module,
*This module implements a subset of the corresponding* :term:`CPython` *module,
as described below. For more information, refer to the original
CPython documentation:*

View File

@ -0,0 +1,94 @@
.. _unix_quickref:
Quick reference for the UNIX and Windows ports
==============================================
Command line options
--------------------
Usage::
micropython [ -h ] [ -i ] [ -O<level> ] [ -v ] [ -X <option> ] [ -c <command> | -m <module> | <script> ] [ <args> ]
Invocation options:
.. option:: -c <command>
Runs the code in ``<command>``. The code can be one or more Python statements.
.. option:: -m <module>
Runs the module ``<module>``. The module must be in ``sys.path``.
.. option:: <script>
Runs the file ``<script>``. The script must be a valid MicroPython source
code file.
If none of the 3 options above are given, then MicroPython is run in an
interactive REPL mode.
.. option:: <args>
Any additional arguments after the module or script will be passed to
``sys.argv`` (not supported with the :option:`-c` option).
General options:
.. option:: -h
Prints a help message containing the command line usage and exits.
.. option:: -i
Enables inspection. When this flag is set, MicroPython will enter the
interactive REPL mode after the command, module or script has finished.
This can be useful for debugging the state after an unhandled exception.
Also see the :envvar:`MICROPYINSPECT` environment variable.
.. option:: -O | -O<level> | -OO...
Sets the optimization level. The ``O`` can be followed by a number or can
be repeated multiple times to indicate the level. E.g. ``-O3`` is the same
as ``-OOO``.
.. option:: -v
Increases the verbosity level. This option can be given multiple times.
This option only has an effect if ``MICROPY_DEBUG_PRINTERS`` was enabled
when MicroPython itself was compiled.
.. option:: -X <option>
Specifies additional implementation-specific options. Possible options are:
- ``-X compile-only`` compiles the command, module or script but does not
run it.
- ``-X emit={bytecode,native,viper}`` sets the default code emitter. Native
emitters may not be available depending on the settings when MicroPython
itself was compiled.
- ``-X heapsize=<n>[w][K|M]`` sets the heap size for the garbage collector.
The suffix ``w`` means words instead of bytes. ``K`` means x1024 and ``M``
means x1024x1024.
Environment variables
---------------------
.. envvar:: MICROPYPATH
Overrides the default search path for MicroPython libraries. ``MICROPYPATH``
should be set to a colon (semicolon for Windows port) separated list of
directories. If ``MICROPYPATH`` is not defined, the search path will be
``~/.micropython/lib:/usr/lib/micropython`` (``~/.micropython/lib`` for Windows port)
or the value of the ``MICROPY_PY_SYS_PATH_DEFAULT`` option if it was set
when MicroPython itself was compiled.
.. envvar:: MICROPYINSPECT
Enables inspection. If ``MICROPYINSPECT`` is set to a non-empty string, it
has the same effect as setting the :option:`-i` command line option.

View File

@ -28,6 +28,8 @@
#include "py/mphal.h"
#define MP_SPI_ADDR_IS_32B(addr) (addr & 0xff000000)
enum {
MP_QSPI_IOCTL_INIT,
MP_QSPI_IOCTL_DEINIT,
@ -54,4 +56,19 @@ typedef struct _mp_soft_qspi_obj_t {
extern const mp_qspi_proto_t mp_soft_qspi_proto;
static inline uint8_t mp_spi_set_addr_buff(uint8_t *buf, uint32_t addr) {
if (MP_SPI_ADDR_IS_32B(addr)) {
buf[0] = addr >> 24;
buf[1] = addr >> 16;
buf[2] = addr >> 8;
buf[3] = addr;
return 4;
} else {
buf[0] = addr >> 16;
buf[1] = addr >> 8;
buf[2] = addr;
return 3;
}
}
#endif // MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H

View File

@ -168,9 +168,10 @@ STATIC void mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len,
STATIC void 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[4] = {cmd, addr >> 16, addr >> 8, addr};
uint8_t cmd_buf[5] = {cmd};
uint8_t addr_len = mp_spi_set_addr_buff(&cmd_buf[1], addr);
CS_LOW(self);
mp_soft_qspi_transfer(self, 4, cmd_buf, NULL);
mp_soft_qspi_transfer(self, addr_len + 1, cmd_buf, NULL);
mp_soft_qspi_transfer(self, len, src, NULL);
CS_HIGH(self);
}
@ -186,10 +187,11 @@ STATIC uint32_t mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len) {
STATIC void 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, addr >> 16, addr >> 8, addr};
uint8_t cmd_buf[7] = {cmd};
uint8_t addr_len = mp_spi_set_addr_buff(&cmd_buf[1], addr);
CS_LOW(self);
mp_soft_qspi_transfer(self, 1, cmd_buf, NULL);
mp_soft_qspi_qwrite(self, 6, &cmd_buf[1]); // 3 addr bytes, 1 extra byte (0), 2 dummy bytes (4 dummy cycles)
mp_soft_qspi_qwrite(self, addr_len + 3, &cmd_buf[1]); // 3/4 addr bytes, 1 extra byte (0), 2 dummy bytes (4 dummy cycles)
mp_soft_qspi_qread(self, len, dest);
CS_HIGH(self);
}

View File

@ -24,6 +24,7 @@
* THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "py/mphal.h"
@ -252,7 +253,7 @@ STATIC const char *cyw43_async_event_name_table[89] = {
STATIC void cyw43_dump_async_event(const cyw43_async_event_t *ev) {
printf("[% 8d] ASYNC(%04x,",
mp_hal_ticks_ms(),
(int)mp_hal_ticks_ms(),
(unsigned int)ev->flags
);
if (ev->event_type < MP_ARRAY_SIZE(cyw43_async_event_name_table)
@ -455,7 +456,9 @@ void cyw43_wifi_set_up(cyw43_t *self, int itf, bool up) {
} else {
country = MAKE_COUNTRY(pyb_country_code[0], pyb_country_code[1], 0);
}
cyw43_wifi_on(self, country);
if (cyw43_wifi_on(self, country) != 0) {
return;
}
cyw43_wifi_pm(self, 10 << 20 | 1 << 16 | 1 << 12 | 20 << 4 | 2);
}
if (itf == CYW43_ITF_AP) {

View File

@ -24,6 +24,7 @@
* THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "py/mphal.h"
@ -49,7 +50,7 @@ STATIC void cyw43_ethernet_trace(cyw43_t *self, struct netif *netif, size_t len,
}
if (self->trace_flags & CYW43_TRACE_MAC) {
printf("[% 8d] ETH%cX itf=%c%c len=%u", mp_hal_ticks_ms(), is_tx ? 'T' : 'R', netif->name[0], netif->name[1], len);
printf("[% 8d] ETH%cX itf=%c%c len=%u", (int)mp_hal_ticks_ms(), is_tx ? 'T' : 'R', netif->name[0], netif->name[1], len);
printf(" MAC type=%d subtype=%d data=", buf[0] >> 2 & 3, buf[0] >> 4);
for (size_t i = 0; i < len; ++i) {
printf(" %02x", buf[i]);

View File

@ -3,7 +3,7 @@
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Damien P. George
* Copyright (c) 2019-2020 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
@ -24,24 +24,30 @@
* THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "py/runtime.h"
#include "py/mphal.h"
#include "pin_static_af.h"
#include "uart.h"
#include "cywbt.h"
#include "nimble/hci_uart.h"
#include "extmod/mpbthci.h"
#if MICROPY_PY_NETWORK_CYW43
extern const char fw_4343WA1_7_45_98_50_start;
#define CYWBT_FW_ADDR (&fw_4343WA1_7_45_98_50_start + 749 * 512 + 29 * 256)
// Provided by the port.
extern pyb_uart_obj_t mp_bluetooth_hci_uart_obj;
// Provided by the port, and also possibly shared with the stack.
extern uint8_t mp_bluetooth_hci_cmd_buf[4 + 256];
/******************************************************************************/
// CYW BT HCI low-level driver
static void cywbt_wait_cts_low(void) {
STATIC void cywbt_wait_cts_low(void) {
mp_hal_pin_config(pyb_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(pyb_pin_BT_CTS) == 0) {
@ -52,13 +58,13 @@ static void cywbt_wait_cts_low(void) {
mp_hal_pin_config_alt_static(pyb_pin_BT_CTS, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, STATIC_AF_USART6_CTS);
}
static int cywbt_hci_cmd_raw(size_t len, uint8_t *buf) {
uart_tx_strn(&bt_hci_uart_obj, (void*)buf, len);
STATIC int cywbt_hci_cmd_raw(size_t len, uint8_t *buf) {
uart_tx_strn(&mp_bluetooth_hci_uart_obj, (void*)buf, len);
for (int i = 0; i < 6; ++i) {
while (!uart_rx_any(&bt_hci_uart_obj)) {
while (!uart_rx_any(&mp_bluetooth_hci_uart_obj)) {
MICROPY_EVENT_POLL_HOOK
}
buf[i] = uart_rx_char(&bt_hci_uart_obj);
buf[i] = uart_rx_char(&mp_bluetooth_hci_uart_obj);
}
// expect a comand complete event (event 0x0e)
@ -75,17 +81,17 @@ static int cywbt_hci_cmd_raw(size_t len, uint8_t *buf) {
int sz = buf[2] - 3;
for (int i = 0; i < sz; ++i) {
while (!uart_rx_any(&bt_hci_uart_obj)) {
while (!uart_rx_any(&mp_bluetooth_hci_uart_obj)) {
MICROPY_EVENT_POLL_HOOK
}
buf[i] = uart_rx_char(&bt_hci_uart_obj);
buf[i] = uart_rx_char(&mp_bluetooth_hci_uart_obj);
}
return 0;
}
static int cywbt_hci_cmd(int ogf, int ocf, size_t param_len, const uint8_t *param_buf) {
uint8_t *buf = bt_hci_cmd_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;
buf[2] = ogf << 2 | ocf >> 8;
@ -96,19 +102,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);
@ -116,12 +122,12 @@ 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;
while (!last_packet) {
uint8_t *buf = bt_hci_cmd_buf;
uint8_t *buf = mp_bluetooth_hci_cmd_buf;
memcpy(buf + 1, firmware, 3);
firmware += 3;
last_packet = buf[1] == 0x4e;
@ -148,15 +154,15 @@ static int cywbt_download_firmware(const uint8_t *firmware) {
cywbt_wait_cts_low();
mp_hal_pin_config(pyb_pin_WL_GPIO_1, MP_HAL_PIN_MODE_INPUT, MP_HAL_PIN_PULL_DOWN, 0); // Select chip antenna (could also select external)
nimble_hci_uart_set_baudrate(115200);
mp_bluetooth_hci_uart_set_baudrate(115200);
cywbt_set_baudrate(3000000);
nimble_hci_uart_set_baudrate(3000000);
mp_bluetooth_hci_uart_set_baudrate(3000000);
return 0;
}
int cywbt_init(void) {
// This is called from Nimble via hal_uart_config which will have already initialized the UART.
int mp_bluetooth_hci_controller_init(void) {
// This is called immediately after the UART is initialised during stack initialisation.
mp_hal_pin_output(pyb_pin_BT_REG_ON);
mp_hal_pin_low(pyb_pin_BT_REG_ON);
@ -168,14 +174,10 @@ int cywbt_init(void) {
mp_hal_pin_config(pyb_pin_WL_GPIO_4, MP_HAL_PIN_MODE_OUTPUT, MP_HAL_PIN_PULL_NONE, 0); // RF-switch power
mp_hal_pin_high(pyb_pin_WL_GPIO_4); // Turn the RF-switch on
return 0;
}
int cywbt_activate(void) {
uint8_t buf[256];
mp_hal_pin_low(pyb_pin_BT_REG_ON);
nimble_hci_uart_set_baudrate(115200);
mp_bluetooth_hci_uart_set_baudrate(115200);
mp_hal_delay_ms(100);
mp_hal_pin_high(pyb_pin_BT_REG_ON);
cywbt_wait_cts_low();
@ -185,7 +187,7 @@ int cywbt_activate(void) {
// Change baudrate
cywbt_set_baudrate(3000000);
nimble_hci_uart_set_baudrate(3000000);
mp_bluetooth_hci_uart_set_baudrate(3000000);
cywbt_download_firmware((const uint8_t*)CYWBT_FW_ADDR);
@ -219,4 +221,57 @@ int cywbt_activate(void) {
return 0;
}
int mp_bluetooth_hci_controller_deinit(void) {
mp_hal_pin_low(pyb_pin_BT_REG_ON);
return 0;
}
#ifdef pyb_pin_BT_DEV_WAKE
STATIC uint32_t bt_sleep_ticks;
#endif
int mp_bluetooth_hci_controller_sleep_maybe(void) {
#ifdef pyb_pin_BT_DEV_WAKE
if (mp_hal_pin_read(pyb_pin_BT_DEV_WAKE) == 0) {
if (mp_hal_ticks_ms() - bt_sleep_ticks > 500) {
mp_hal_pin_high(pyb_pin_BT_DEV_WAKE); // let sleep
}
}
#endif
return 0;
}
bool mp_bluetooth_hci_controller_woken(void) {
#ifdef pyb_pin_BT_HOST_WAKE
bool host_wake = mp_hal_pin_read(pyb_pin_BT_HOST_WAKE);
/*
// this is just for info/tracing purposes
static bool last_host_wake = false;
if (host_wake != last_host_wake) {
printf("HOST_WAKE change %d -> %d\n", last_host_wake, host_wake);
last_host_wake = host_wake;
}
*/
return host_wake;
#else
return true;
#endif
}
int mp_bluetooth_hci_controller_wakeup(void) {
#ifdef pyb_pin_BT_DEV_WAKE
bt_sleep_ticks = mp_hal_ticks_ms();
if (mp_hal_pin_read(pyb_pin_BT_DEV_WAKE) == 1) {
mp_hal_pin_low(pyb_pin_BT_DEV_WAKE); // wake up
// Use delay_us rather than delay_ms to prevent running the scheduler (which
// might result in more BLE operations).
mp_hal_delay_us(5000); // can't go lower than this
}
#endif
return 0;
}
#endif

View File

@ -45,7 +45,7 @@ STATIC mp_obj_t dht_readinto(mp_obj_t pin_in, mp_obj_t buf_in) {
mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE);
if (bufinfo.len < 5) {
mp_raise_ValueError("buffer too small");
mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
}
// issue start command

View File

@ -6,6 +6,7 @@ try:
except:
from pyb import dht_readinto
class DHTBase:
def __init__(self, pin):
self.pin = pin
@ -14,9 +15,10 @@ class DHTBase:
def measure(self):
buf = self.buf
dht_readinto(self.pin, buf)
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xff != buf[4]:
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xFF != buf[4]:
raise Exception("checksum error")
class DHT11(DHTBase):
def humidity(self):
return self.buf[0]
@ -24,12 +26,13 @@ class DHT11(DHTBase):
def temperature(self):
return self.buf[2]
class DHT22(DHTBase):
def humidity(self):
return (self.buf[0] << 8 | self.buf[1]) * 0.1
def temperature(self):
t = ((self.buf[2] & 0x7f) << 8 | self.buf[3]) * 0.1
t = ((self.buf[2] & 0x7F) << 8 | self.buf[3]) * 0.1
if self.buf[2] & 0x80:
t = -t
return t

View File

@ -29,16 +29,17 @@ _uart_baud_table = {
460800: 8,
}
class LCD160CR:
def __init__(self, connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98):
if connect in ('X', 'Y', 'XY', 'YX'):
if connect in ("X", "Y", "XY", "YX"):
i = connect[-1]
j = connect[0]
y = j + '4'
elif connect == 'C':
y = j + "4"
elif connect == "C":
i = 2
j = 2
y = 'A7'
y = "A7"
else:
if pwr is None or i2c is None or spi is None:
raise ValueError('must specify valid "connect" or all of "pwr", "i2c" and "spi"')
@ -74,8 +75,8 @@ class LCD160CR:
# set default orientation and window
self.set_orient(PORTRAIT)
self._fcmd2b('<BBBBBB', 0x76, 0, 0, self.w, self.h) # viewport 'v'
self._fcmd2b('<BBBBBB', 0x79, 0, 0, self.w, self.h) # window 'y'
self._fcmd2b("<BBBBBB", 0x76, 0, 0, self.w, self.h) # viewport 'v'
self._fcmd2b("<BBBBBB", 0x79, 0, 0, self.w, self.h) # window 'y'
def _send(self, cmd):
i = self.i2c.writeto(self.i2c_addr, cmd)
@ -135,7 +136,7 @@ class LCD160CR:
@staticmethod
def rgb(r, g, b):
return ((b & 0xf8) << 8) | ((g & 0xfc) << 3) | (r >> 3)
return ((b & 0xF8) << 8) | ((g & 0xFC) << 3) | (r >> 3)
@staticmethod
def clip_line(c, w, h):
@ -207,43 +208,43 @@ class LCD160CR:
sleep_ms(15)
def set_orient(self, orient):
self._fcmd2('<BBB', 0x14, (orient & 3) + 4)
self._fcmd2("<BBB", 0x14, (orient & 3) + 4)
# update width and height variables
self.iflush()
self._send(b'\x02g0')
self._send(b"\x02g0")
self._waitfor(4, self.buf[5])
self.w = self.buf[5][1]
self.h = self.buf[5][2]
def set_brightness(self, value):
self._fcmd2('<BBB', 0x16, value)
self._fcmd2("<BBB", 0x16, value)
def set_i2c_addr(self, addr):
# 0x0e set i2c addr
if addr & 3:
raise ValueError('must specify mod 4 aligned address')
self._fcmd2('<BBW', 0x0e, 0x433249 | (addr << 24))
raise ValueError("must specify mod 4 aligned address")
self._fcmd2("<BBW", 0x0E, 0x433249 | (addr << 24))
def set_uart_baudrate(self, baudrate):
try:
baudrate = _uart_baud_table[baudrate]
except KeyError:
raise ValueError('invalid baudrate')
self._fcmd2('<BBB', 0x18, baudrate)
raise ValueError("invalid baudrate")
self._fcmd2("<BBB", 0x18, baudrate)
def set_startup_deco(self, value):
self._fcmd2('<BBB', 0x19, value)
self._fcmd2("<BBB", 0x19, value)
def save_to_flash(self):
self._send(b'\x02fn')
self._send(b"\x02fn")
#### PIXEL ACCESS ####
def set_pixel(self, x, y, c):
self._fcmd2b('<BBBBH', 0x41, x, y, c)
self._fcmd2b("<BBBBH", 0x41, x, y, c)
def get_pixel(self, x, y):
self._fcmd2('<BBBB', 0x61, x, y)
self._fcmd2("<BBBB", 0x61, x, y)
t = 1000
while t:
self.i2c.readfrom_into(self.i2c_addr, self.buf1)
@ -256,7 +257,7 @@ class LCD160CR:
def get_line(self, x, y, buf):
l = len(buf) // 2
self._fcmd2b('<BBBBB', 0x10, l, x, y)
self._fcmd2b("<BBBBB", 0x10, l, x, y)
l *= 2
t = 1000
while t:
@ -280,42 +281,47 @@ class LCD160CR:
# split line if more than 254 bytes needed
buflen = (w + 1) // 2
line = bytearray(2 * buflen + 1)
line2 = memoryview(line)[:2 * (w - buflen) + 1]
line2 = memoryview(line)[: 2 * (w - buflen) + 1]
for i in range(min(len(buf) // (2 * w), h)):
ix = i * w * 2
self.get_line(x, y + i, line)
buf[ix:ix + len(line) - 1] = memoryview(line)[1:]
buf[ix : ix + len(line) - 1] = memoryview(line)[1:]
ix += len(line) - 1
if line2:
self.get_line(x + buflen, y + i, line2)
buf[ix:ix + len(line2) - 1] = memoryview(line2)[1:]
buf[ix : ix + len(line2) - 1] = memoryview(line2)[1:]
ix += len(line2) - 1
def screen_load(self, buf):
l = self.w * self.h * 2+2
self._fcmd2b('<BBHBBB', 0x70, l, 16, self.w, self.h)
l = self.w * self.h * 2 + 2
self._fcmd2b("<BBHBBB", 0x70, l, 16, self.w, self.h)
n = 0
ar = memoryview(buf)
while n < len(buf):
if len(buf) - n >= 0x200:
self._send(ar[n:n + 0x200])
self._send(ar[n : n + 0x200])
n += 0x200
else:
self._send(ar[n:])
while n < self.w * self.h * 2:
self._send(b'\x00')
self._send(b"\x00")
n += 1
#### TEXT COMMANDS ####
def set_pos(self, x, y):
self._fcmd2('<BBBB', 0x58, x, y)
self._fcmd2("<BBBB", 0x58, x, y)
def set_text_color(self, fg, bg):
self._fcmd2('<BBHH', 0x63, fg, bg)
self._fcmd2("<BBHH", 0x63, fg, bg)
def set_font(self, font, scale=0, bold=0, trans=0, scroll=0):
self._fcmd2('<BBBB', 0x46, (scroll << 7) | (trans << 6) | ((font & 3) << 4) | (bold & 0xf), scale & 0xff)
self._fcmd2(
"<BBBB",
0x46,
(scroll << 7) | (trans << 6) | ((font & 3) << 4) | (bold & 0xF),
scale & 0xFF,
)
def write(self, s):
# TODO: eventually check for room in LCD input queue
@ -324,14 +330,14 @@ class LCD160CR:
#### PRIMITIVE DRAWING COMMANDS ####
def set_pen(self, line, fill):
self._fcmd2('<BBHH', 0x50, line, fill)
self._fcmd2("<BBHH", 0x50, line, fill)
def erase(self):
self._send(b'\x02\x45')
self._send(b"\x02\x45")
def dot(self, x, y):
if 0 <= x < self.w and 0 <= y < self.h:
self._fcmd2('<BBBB', 0x4b, x, y)
self._fcmd2("<BBBB", 0x4B, x, y)
def rect(self, x, y, w, h, cmd=0x72):
if x + w <= 0 or y + h <= 0 or x >= self.w or y >= self.h:
@ -348,19 +354,19 @@ class LCD160CR:
y = 0
if cmd == 0x51 or cmd == 0x72:
# draw interior
self._fcmd2b('<BBBBBB', 0x51, x, y, min(w, 255), min(h, 255))
self._fcmd2b("<BBBBBB", 0x51, x, y, min(w, 255), min(h, 255))
if cmd == 0x57 or cmd == 0x72:
# draw outline
if left:
self._fcmd2b('<BBBBBB', 0x57, x, y, 1, min(h, 255))
self._fcmd2b("<BBBBBB", 0x57, x, y, 1, min(h, 255))
if top:
self._fcmd2b('<BBBBBB', 0x57, x, y, min(w, 255), 1)
self._fcmd2b("<BBBBBB", 0x57, x, y, min(w, 255), 1)
if x + w < self.w:
self._fcmd2b('<BBBBBB', 0x57, x + w, y, 1, min(h, 255))
self._fcmd2b("<BBBBBB", 0x57, x + w, y, 1, min(h, 255))
if y + h < self.h:
self._fcmd2b('<BBBBBB', 0x57, x, y + h, min(w, 255), 1)
self._fcmd2b("<BBBBBB", 0x57, x, y + h, min(w, 255), 1)
else:
self._fcmd2b('<BBBBBB', cmd, x, y, min(w, 255), min(h, 255))
self._fcmd2b("<BBBBBB", cmd, x, y, min(w, 255), min(h, 255))
def rect_outline(self, x, y, w, h):
self.rect(x, y, w, h, 0x57)
@ -375,48 +381,48 @@ class LCD160CR:
ar4[2] = x2
ar4[3] = y2
if self.clip_line(ar4, self.w, self.h):
self._fcmd2b('<BBBBBB', 0x4c, ar4[0], ar4[1], ar4[2], ar4[3])
self._fcmd2b("<BBBBBB", 0x4C, ar4[0], ar4[1], ar4[2], ar4[3])
def dot_no_clip(self, x, y):
self._fcmd2('<BBBB', 0x4b, x, y)
self._fcmd2("<BBBB", 0x4B, x, y)
def rect_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x72, x, y, w, h)
self._fcmd2b("<BBBBBB", 0x72, x, y, w, h)
def rect_outline_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x57, x, y, w, h)
self._fcmd2b("<BBBBBB", 0x57, x, y, w, h)
def rect_interior_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x51, x, y, w, h)
self._fcmd2b("<BBBBBB", 0x51, x, y, w, h)
def line_no_clip(self, x1, y1, x2, y2):
self._fcmd2b('<BBBBBB', 0x4c, x1, y1, x2, y2)
self._fcmd2b("<BBBBBB", 0x4C, x1, y1, x2, y2)
def poly_dot(self, data):
if len(data) & 1:
raise ValueError('must specify even number of bytes')
self._fcmd2('<BBB', 0x71, len(data) // 2)
raise ValueError("must specify even number of bytes")
self._fcmd2("<BBB", 0x71, len(data) // 2)
self._send(data)
def poly_line(self, data):
if len(data) & 1:
raise ValueError('must specify even number of bytes')
self._fcmd2('<BBB', 0x78, len(data) // 2)
raise ValueError("must specify even number of bytes")
self._fcmd2("<BBB", 0x78, len(data) // 2)
self._send(data)
#### TOUCH COMMANDS ####
def touch_config(self, calib=False, save=False, irq=None):
self._fcmd2('<BBBB', 0x7a, (irq is not None) << 2 | save << 1 | calib, bool(irq) << 7)
self._fcmd2("<BBBB", 0x7A, (irq is not None) << 2 | save << 1 | calib, bool(irq) << 7)
def is_touched(self):
self._send(b'\x02T')
self._send(b"\x02T")
b = self.buf[4]
self._waitfor(3, b)
return b[1] >> 7 != 0
def get_touch(self):
self._send(b'\x02T') # implicit LCD output flush
self._send(b"\x02T") # implicit LCD output flush
b = self.buf[4]
self._waitfor(3, b)
return b[1] >> 7, b[2], b[3]
@ -424,11 +430,13 @@ class LCD160CR:
#### ADVANCED COMMANDS ####
def set_spi_win(self, x, y, w, h):
pack_into('<BBBHHHHHHHH', self.buf19, 0, 2, 0x55, 10, x, y, x + w - 1, y + h - 1, 0, 0, 0, 0xffff)
pack_into(
"<BBBHHHHHHHH", self.buf19, 0, 2, 0x55, 10, x, y, x + w - 1, y + h - 1, 0, 0, 0, 0xFFFF
)
self._send(self.buf19)
def fast_spi(self, flush=True):
self._send(b'\x02\x12')
self._send(b"\x02\x12")
if flush:
self.oflush()
return self.spi
@ -437,27 +445,27 @@ class LCD160CR:
self.fast_spi().write(buf)
def set_scroll(self, on):
self._fcmd2('<BBB', 0x15, on)
self._fcmd2("<BBB", 0x15, on)
def set_scroll_win(self, win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07e0, color=0):
pack_into('<BBBHHHHHHHH', self.buf19, 0, 2, 0x55, win, x, y, w, h, vec, pat, fill, color)
def set_scroll_win(self, win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07E0, color=0):
pack_into("<BBBHHHHHHHH", self.buf19, 0, 2, 0x55, win, x, y, w, h, vec, pat, fill, color)
self._send(self.buf19)
def set_scroll_win_param(self, win, param, value):
self._fcmd2b('<BBBBH', 0x75, win, param, value)
self._fcmd2b("<BBBBH", 0x75, win, param, value)
def set_scroll_buf(self, s):
l = len(s)
if l > 32:
raise ValueError('length must be 32 or less')
self._fcmd2('<BBB', 0x11, l)
raise ValueError("length must be 32 or less")
self._fcmd2("<BBB", 0x11, l)
self._send(s)
def jpeg_start(self, l):
if l > 0xffff:
raise ValueError('length must be 65535 or less')
if l > 0xFFFF:
raise ValueError("length must be 65535 or less")
self.oflush()
self._fcmd2('<BBH', 0x6a, l)
self._fcmd2("<BBH", 0x6A, l)
def jpeg_data(self, buf):
self._send(buf)
@ -467,8 +475,8 @@ class LCD160CR:
self.jpeg_data(buf)
def feed_wdt(self):
self._send(b'\x02\x17')
self._send(b"\x02\x17")
def reset(self):
self._send(b'\x02Y\xef\xbe\xad\xde')
self._send(b"\x02Y\xef\xbe\xad\xde")
sleep_ms(15)

View File

@ -3,11 +3,13 @@
import time, math, framebuf, lcd160cr
def get_lcd(lcd):
if type(lcd) is str:
lcd = lcd160cr.LCD160CR(lcd)
return lcd
def show_adc(lcd, adc):
data = [adc.read_core_temp(), adc.read_core_vbat(), 3.3]
try:
@ -21,24 +23,26 @@ def show_adc(lcd, adc):
lcd.set_pos(0, 100 + i * 16)
else:
lcd.set_font(2, trans=1)
lcd.set_pos(0, lcd.h-60 + i * 16)
lcd.write('%4s: ' % ('TEMP', 'VBAT', 'VREF')[i])
lcd.set_pos(0, lcd.h - 60 + i * 16)
lcd.write("%4s: " % ("TEMP", "VBAT", "VREF")[i])
if i > 0:
s = '%6.3fV' % data[i]
s = "%6.3fV" % data[i]
else:
s = '%5.1f°C' % data[i]
s = "%5.1f°C" % data[i]
if lcd.h == 160:
lcd.set_font(1, bold=0, scale=1)
else:
lcd.set_font(1, bold=0, scale=1, trans=1)
lcd.set_pos(45, lcd.h-60 + i * 16)
lcd.set_pos(45, lcd.h - 60 + i * 16)
lcd.write(s)
def test_features(lcd, orient=lcd160cr.PORTRAIT):
# if we run on pyboard then use ADC and RTC features
try:
import pyb
adc = pyb.ADCAll(12, 0xf0000)
adc = pyb.ADCAll(12, 0xF0000)
rtc = pyb.RTC()
except:
adc = None
@ -53,7 +57,7 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
# create M-logo
mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565)
mlogo.fill(0)
mlogo.fill_rect(1, 1, 15, 15, 0xffffff)
mlogo.fill_rect(1, 1, 15, 15, 0xFFFFFF)
mlogo.vline(4, 4, 12, 0)
mlogo.vline(8, 1, 12, 0)
mlogo.vline(12, 4, 12, 0)
@ -80,15 +84,18 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h:
tx, ty = tx2, ty2
else:
tx = (tx + 1) % w
ty = (ty + 1) % h
tx = (tx + 1) % w
ty = (ty + 1) % h
# create and show the inline framebuf
fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192))
fbuf.line(w // 2, h // 2,
fbuf.line(
w // 2,
h // 2,
w // 2 + int(40 * math.cos(0.2 * i)),
h // 2 + int(40 * math.sin(0.2 * i)),
lcd.rgb(128, 255, 64))
lcd.rgb(128, 255, 64),
)
fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64))
fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64))
fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64))
@ -97,9 +104,12 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase))
fbuf.blit(mlogo, x, y)
for j in range(-3, 3):
fbuf.text('MicroPython',
5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
lcd.rgb(128 + 10 * j, 0, 128 - 10 * j))
fbuf.text(
"MicroPython",
5,
h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
lcd.rgb(128 + 10 * j, 0, 128 - 10 * j),
)
lcd.show_framebuf(fbuf)
# show results from the ADC
@ -111,7 +121,10 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
lcd.set_pos(2, 0)
lcd.set_font(1)
t = rtc.datetime()
lcd.write('%4d-%02d-%02d %2d:%02d:%02d.%01d' % (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000))
lcd.write(
"%4d-%02d-%02d %2d:%02d:%02d.%01d"
% (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000)
)
# compute the frame rate
t1 = time.ticks_us()
@ -120,13 +133,14 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
# show the frame rate
lcd.set_pos(2, 9)
lcd.write('%.2f fps' % (1000000 / dt))
lcd.write("%.2f fps" % (1000000 / dt))
def test_mandel(lcd, orient=lcd160cr.PORTRAIT):
# set orientation and clear screen
lcd = get_lcd(lcd)
lcd.set_orient(orient)
lcd.set_pen(0, 0xffff)
lcd.set_pen(0, 0xFFFF)
lcd.erase()
# function to compute Mandelbrot pixels
@ -148,24 +162,26 @@ def test_mandel(lcd, orient=lcd160cr.PORTRAIT):
spi = lcd.fast_spi()
# draw the Mandelbrot set line-by-line
hh = ((h - 1) / 3.2)
ww = ((w - 1) / 2.4)
hh = (h - 1) / 3.2
ww = (w - 1) / 2.4
for v in range(h):
for u in range(w):
c = in_set((v / hh - 2.3) + (u / ww - 1.2) * 1j)
if c < 16:
rgb = c << 12 | c << 6
else:
rgb = 0xf800 | c << 6
rgb = 0xF800 | c << 6
line[2 * u] = rgb
line[2 * u + 1] = rgb >> 8
spi.write(line)
def test_all(lcd, orient=lcd160cr.PORTRAIT):
lcd = get_lcd(lcd)
test_features(lcd, orient)
test_mandel(lcd, orient)
print('To run all tests: test_all(<lcd>)')
print('Individual tests are: test_features, test_mandel')
print("To run all tests: test_all(<lcd>)")
print("Individual tests are: test_features, test_mandel")
print('<lcd> argument should be a connection, eg "X", or an LCD160CR object')

View File

@ -5,23 +5,23 @@ import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xa4)
SET_NORM_INV = const(0xa6)
SET_DISP = const(0xae)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xa0)
SET_MUX_RATIO = const(0xa8)
SET_COM_OUT_DIR = const(0xc0)
SET_DISP_OFFSET = const(0xd3)
SET_COM_PIN_CFG = const(0xda)
SET_DISP_CLK_DIV = const(0xd5)
SET_PRECHARGE = const(0xd9)
SET_VCOM_DESEL = const(0xdb)
SET_CHARGE_PUMP = const(0x8d)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
@ -37,27 +37,37 @@ class SSD1306(framebuf.FrameBuffer):
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR, 0x00, # horizontal
SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO, self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET, 0x00,
SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET,
0x00,
SET_COM_PIN_CFG,
0x02 if self.width > 2 * self.height else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV, 0x80,
SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
SET_VCOM_DESEL, 0x30, # 0.83*Vcc
SET_DISP_CLK_DIV,
0x80,
SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display
SET_CONTRAST, 0xff, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01): # on
SET_CHARGE_PUMP,
0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01,
): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
@ -92,15 +102,15 @@ class SSD1306(framebuf.FrameBuffer):
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
self.write_list = [b'\x40', None] # Co=0, D/C#=1
self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
@ -120,6 +130,7 @@ class SSD1306_SPI(SSD1306):
self.res = res
self.cs = cs
import time
self.res(1)
time.sleep_ms(1)
self.res(0)

View File

@ -45,6 +45,12 @@
#define CMD_CHIP_ERASE (0xc7)
#define CMD_C4READ (0xeb)
// 32 bit addressing commands
#define CMD_WRITE_32 (0x12)
#define CMD_READ_32 (0x13)
#define CMD_SEC_ERASE_32 (0x21)
#define CMD_C4READ_32 (0xec)
#define WAIT_SR_TIMEOUT (1000000)
#define PAGE_SIZE (256) // maximum bytes we can write in one SPI transfer
@ -76,18 +82,26 @@ STATIC void mp_spiflash_write_cmd_data(mp_spiflash_t *self, uint8_t cmd, size_t
}
}
STATIC void mp_spiflash_write_cmd_addr_data(mp_spiflash_t *self, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) {
STATIC void 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) {
const mp_spiflash_config_t *c = self->config;
if (c->bus_kind == MP_SPIFLASH_BUS_SPI) {
uint8_t buf[4] = {cmd, addr >> 16, addr >> 8, addr};
uint8_t buf[5] = {cmd, 0};
uint8_t buff_len = 1 + mp_spi_set_addr_buff(&buf[1], addr);
mp_hal_pin_write(c->bus.u_spi.cs, 0);
c->bus.u_spi.proto->transfer(c->bus.u_spi.data, 4, buf, NULL);
if (len) {
c->bus.u_spi.proto->transfer(c->bus.u_spi.data, buff_len, buf, NULL);
if (len && (src != NULL)) {
c->bus.u_spi.proto->transfer(c->bus.u_spi.data, len, src, NULL);
} else if (len && (dest != NULL)) {
c->bus.u_spi.proto->transfer(c->bus.u_spi.data, len, dest, dest);
}
mp_hal_pin_write(c->bus.u_spi.cs, 1);
} else {
c->bus.u_qspi.proto->write_cmd_addr_data(c->bus.u_qspi.data, cmd, addr, len, src);
if (dest != NULL) {
c->bus.u_qspi.proto->read_cmd_qaddr_qdata(c->bus.u_qspi.data, cmd, addr, len, dest);
} else {
c->bus.u_qspi.proto->write_cmd_addr_data(c->bus.u_qspi.data, cmd, addr, len, src);
}
}
}
@ -107,25 +121,19 @@ STATIC uint32_t mp_spiflash_read_cmd(mp_spiflash_t *self, uint8_t cmd, size_t le
STATIC void 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) {
uint8_t buf[4] = {CMD_READ, addr >> 16, addr >> 8, addr};
mp_hal_pin_write(c->bus.u_spi.cs, 0);
c->bus.u_spi.proto->transfer(c->bus.u_spi.data, 4, buf, NULL);
c->bus.u_spi.proto->transfer(c->bus.u_spi.data, len, dest, dest);
mp_hal_pin_write(c->bus.u_spi.cs, 1);
cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_READ_32 : CMD_READ;
} else {
c->bus.u_qspi.proto->read_cmd_qaddr_qdata(c->bus.u_qspi.data, CMD_C4READ, addr, len, dest);
cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_C4READ_32 : CMD_C4READ;
}
mp_spiflash_transfer_cmd_addr_data(self, cmd, addr, len, NULL, dest);
}
STATIC void mp_spiflash_write_cmd(mp_spiflash_t *self, uint8_t cmd) {
mp_spiflash_write_cmd_data(self, cmd, 0, 0);
}
STATIC void mp_spiflash_write_cmd_addr(mp_spiflash_t *self, uint8_t cmd, uint32_t addr) {
mp_spiflash_write_cmd_addr_data(self, cmd, addr, 0, NULL);
}
STATIC int mp_spiflash_wait_sr(mp_spiflash_t *self, uint8_t mask, uint8_t val, uint32_t timeout) {
uint8_t sr;
do {
@ -210,7 +218,8 @@ STATIC int mp_spiflash_erase_block_internal(mp_spiflash_t *self, uint32_t addr)
}
// erase the sector
mp_spiflash_write_cmd_addr(self, CMD_SEC_ERASE, addr);
uint8_t cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_SEC_ERASE_32 : CMD_SEC_ERASE;
mp_spiflash_transfer_cmd_addr_data(self, cmd, addr, 0, NULL, NULL);
// wait WIP=0
return mp_spiflash_wait_wip0(self);
@ -227,7 +236,8 @@ STATIC int mp_spiflash_write_page(mp_spiflash_t *self, uint32_t addr, size_t len
}
// write the page
mp_spiflash_write_cmd_addr_data(self, CMD_WRITE, addr, len, src);
uint8_t cmd = MP_SPI_ADDR_IS_32B(addr) ? CMD_WRITE_32 : CMD_WRITE;
mp_spiflash_transfer_cmd_addr_data(self, cmd, addr, len, src, NULL);
// wait WIP=0
return mp_spiflash_wait_wip0(self);

View File

@ -5,49 +5,50 @@ from micropython import const
import utime
# nRF24L01+ registers
CONFIG = const(0x00)
EN_RXADDR = const(0x02)
SETUP_AW = const(0x03)
SETUP_RETR = const(0x04)
RF_CH = const(0x05)
RF_SETUP = const(0x06)
STATUS = const(0x07)
RX_ADDR_P0 = const(0x0a)
TX_ADDR = const(0x10)
RX_PW_P0 = const(0x11)
CONFIG = const(0x00)
EN_RXADDR = const(0x02)
SETUP_AW = const(0x03)
SETUP_RETR = const(0x04)
RF_CH = const(0x05)
RF_SETUP = const(0x06)
STATUS = const(0x07)
RX_ADDR_P0 = const(0x0A)
TX_ADDR = const(0x10)
RX_PW_P0 = const(0x11)
FIFO_STATUS = const(0x17)
DYNPD = const(0x1c)
DYNPD = const(0x1C)
# CONFIG register
EN_CRC = const(0x08) # enable CRC
CRCO = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
PWR_UP = const(0x02) # 1=power up, 0=power down
PRIM_RX = const(0x01) # RX/TX control; 0=PTX, 1=PRX
EN_CRC = const(0x08) # enable CRC
CRCO = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
PWR_UP = const(0x02) # 1=power up, 0=power down
PRIM_RX = const(0x01) # RX/TX control; 0=PTX, 1=PRX
# RF_SETUP register
POWER_0 = const(0x00) # -18 dBm
POWER_1 = const(0x02) # -12 dBm
POWER_2 = const(0x04) # -6 dBm
POWER_3 = const(0x06) # 0 dBm
SPEED_1M = const(0x00)
SPEED_2M = const(0x08)
SPEED_250K = const(0x20)
POWER_0 = const(0x00) # -18 dBm
POWER_1 = const(0x02) # -12 dBm
POWER_2 = const(0x04) # -6 dBm
POWER_3 = const(0x06) # 0 dBm
SPEED_1M = const(0x00)
SPEED_2M = const(0x08)
SPEED_250K = const(0x20)
# STATUS register
RX_DR = const(0x40) # RX data ready; write 1 to clear
TX_DS = const(0x20) # TX data sent; write 1 to clear
MAX_RT = const(0x10) # max retransmits reached; write 1 to clear
RX_DR = const(0x40) # RX data ready; write 1 to clear
TX_DS = const(0x20) # TX data sent; write 1 to clear
MAX_RT = const(0x10) # max retransmits reached; write 1 to clear
# FIFO_STATUS register
RX_EMPTY = const(0x01) # 1 if RX FIFO is empty
RX_EMPTY = const(0x01) # 1 if RX FIFO is empty
# constants for instructions
R_RX_PL_WID = const(0x60) # read RX payload width
R_RX_PAYLOAD = const(0x61) # read RX payload
W_TX_PAYLOAD = const(0xa0) # write TX payload
FLUSH_TX = const(0xe1) # flush TX FIFO
FLUSH_RX = const(0xe2) # flush RX FIFO
NOP = const(0xff) # use to read STATUS register
R_RX_PL_WID = const(0x60) # read RX payload width
R_RX_PAYLOAD = const(0x61) # read RX payload
W_TX_PAYLOAD = const(0xA0) # write TX payload
FLUSH_TX = const(0xE1) # flush TX FIFO
FLUSH_RX = const(0xE2) # flush RX FIFO
NOP = const(0xFF) # use to read STATUS register
class NRF24L01:
def __init__(self, spi, cs, ce, channel=46, payload_size=16):
@ -84,7 +85,7 @@ class NRF24L01:
self.reg_write(SETUP_RETR, (6 << 4) | 8)
# set rf power and speed
self.set_power_speed(POWER_3, SPEED_250K) # Best for point to point links
self.set_power_speed(POWER_3, SPEED_250K) # Best for point to point links
# init CRC
self.set_crc(2)
@ -218,7 +219,7 @@ class NRF24L01:
start = utime.ticks_ms()
result = None
while result is None and utime.ticks_diff(utime.ticks_ms(), start) < timeout:
result = self.send_done() # 1 == success, 2 == fail
result = self.send_done() # 1 == success, 2 == fail
if result == 2:
raise OSError("send failed")
@ -232,18 +233,18 @@ class NRF24L01:
self.spi.readinto(self.buf, W_TX_PAYLOAD)
self.spi.write(buf)
if len(buf) < self.payload_size:
self.spi.write(b'\x00' * (self.payload_size - len(buf))) # pad out data
self.spi.write(b"\x00" * (self.payload_size - len(buf))) # pad out data
self.cs(1)
# enable the chip so it can send the data
self.ce(1)
utime.sleep_us(15) # needs to be >10us
utime.sleep_us(15) # needs to be >10us
self.ce(0)
# returns None if send still in progress, 1 for success, 2 for fail
def send_done(self):
if not (self.reg_read(STATUS) & (TX_DS | MAX_RT)):
return None # tx not finished
return None # tx not finished
# either finished or failed: get and clear status flags, power down
status = self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT)

View File

@ -1,6 +1,6 @@
"""Test for nrf24l01 module. Portable between MicroPython targets."""
import sys
import usys
import ustruct as struct
import utime
from machine import Pin, SPI
@ -14,25 +14,28 @@ _RX_POLL_DELAY = const(15)
# master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266.
_SLAVE_SEND_DELAY = const(10)
if sys.platform == 'pyboard':
cfg = {'spi': 2, 'miso': 'Y7', 'mosi': 'Y8', 'sck': 'Y6', 'csn': 'Y5', 'ce': 'Y4'}
elif sys.platform == 'esp8266': # Hardware SPI
cfg = {'spi': 1, 'miso': 12, 'mosi': 13, 'sck': 14, 'csn': 4, 'ce': 5}
elif sys.platform == 'esp32': # Software SPI
cfg = {'spi': -1, 'miso': 32, 'mosi': 33, 'sck': 25, 'csn': 26, 'ce': 27}
if usys.platform == "pyboard":
cfg = {"spi": 2, "miso": "Y7", "mosi": "Y8", "sck": "Y6", "csn": "Y5", "ce": "Y4"}
elif usys.platform == "esp8266": # Hardware SPI
cfg = {"spi": 1, "miso": 12, "mosi": 13, "sck": 14, "csn": 4, "ce": 5}
elif usys.platform == "esp32": # Software SPI
cfg = {"spi": -1, "miso": 32, "mosi": 33, "sck": 25, "csn": 26, "ce": 27}
else:
raise ValueError('Unsupported platform {}'.format(sys.platform))
raise ValueError("Unsupported platform {}".format(usys.platform))
# Addresses are in little-endian format. They correspond to big-endian
# 0xf0f0f0f0e1, 0xf0f0f0f0d2
pipes = (b"\xe1\xf0\xf0\xf0\xf0", b"\xd2\xf0\xf0\xf0\xf0")
pipes = (b'\xf0\xf0\xf0\xf0\xe1', b'\xf0\xf0\xf0\xf0\xd2')
def master():
csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
if cfg['spi'] == -1:
spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso']))
csn = Pin(cfg["csn"], mode=Pin.OUT, value=1)
ce = Pin(cfg["ce"], mode=Pin.OUT, value=0)
if cfg["spi"] == -1:
spi = SPI(-1, sck=Pin(cfg["sck"]), mosi=Pin(cfg["mosi"]), miso=Pin(cfg["miso"]))
nrf = NRF24L01(spi, csn, ce, payload_size=8)
else:
nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8)
nrf = NRF24L01(SPI(cfg["spi"]), csn, ce, payload_size=8)
nrf.open_tx_pipe(pipes[0])
nrf.open_rx_pipe(1, pipes[1])
@ -43,16 +46,16 @@ def master():
num_failures = 0
led_state = 0
print('NRF24L01 master mode, sending %d packets...' % num_needed)
print("NRF24L01 master mode, sending %d packets..." % num_needed)
while num_successes < num_needed and num_failures < num_needed:
# stop listening and send packet
nrf.stop_listening()
millis = utime.ticks_ms()
led_state = max(1, (led_state << 1) & 0x0f)
print('sending:', millis, led_state)
led_state = max(1, (led_state << 1) & 0x0F)
print("sending:", millis, led_state)
try:
nrf.send(struct.pack('ii', millis, led_state))
nrf.send(struct.pack("ii", millis, led_state))
except OSError:
pass
@ -67,43 +70,50 @@ def master():
timeout = True
if timeout:
print('failed, response timed out')
print("failed, response timed out")
num_failures += 1
else:
# recv packet
got_millis, = struct.unpack('i', nrf.recv())
(got_millis,) = struct.unpack("i", nrf.recv())
# print response and round-trip delay
print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)')
print(
"got response:",
got_millis,
"(delay",
utime.ticks_diff(utime.ticks_ms(), got_millis),
"ms)",
)
num_successes += 1
# delay then loop
utime.sleep_ms(250)
print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures))
print("master finished sending; successes=%d, failures=%d" % (num_successes, num_failures))
def slave():
csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
if cfg['spi'] == -1:
spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso']))
csn = Pin(cfg["csn"], mode=Pin.OUT, value=1)
ce = Pin(cfg["ce"], mode=Pin.OUT, value=0)
if cfg["spi"] == -1:
spi = SPI(-1, sck=Pin(cfg["sck"]), mosi=Pin(cfg["mosi"]), miso=Pin(cfg["miso"]))
nrf = NRF24L01(spi, csn, ce, payload_size=8)
else:
nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8)
nrf = NRF24L01(SPI(cfg["spi"]), csn, ce, payload_size=8)
nrf.open_tx_pipe(pipes[1])
nrf.open_rx_pipe(1, pipes[0])
nrf.start_listening()
print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')
print("NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)")
while True:
if nrf.any():
while nrf.any():
buf = nrf.recv()
millis, led_state = struct.unpack('ii', buf)
print('received:', millis, led_state)
millis, led_state = struct.unpack("ii", buf)
print("received:", millis, led_state)
for led in leds:
if led_state & 1:
led.on()
@ -116,23 +126,25 @@ def slave():
utime.sleep_ms(_SLAVE_SEND_DELAY)
nrf.stop_listening()
try:
nrf.send(struct.pack('i', millis))
nrf.send(struct.pack("i", millis))
except OSError:
pass
print('sent response')
print("sent response")
nrf.start_listening()
try:
import pyb
leds = [pyb.LED(i + 1) for i in range(4)]
except:
leds = []
print('NRF24L01 test module loaded')
print('NRF24L01 pinout for test:')
print(' CE on', cfg['ce'])
print(' CSN on', cfg['csn'])
print(' SCK on', cfg['sck'])
print(' MISO on', cfg['miso'])
print(' MOSI on', cfg['mosi'])
print('run nrf24l01test.slave() on slave, then nrf24l01test.master() on master')
print("NRF24L01 test module loaded")
print("NRF24L01 pinout for test:")
print(" CE on", cfg["ce"])
print(" CSN on", cfg["csn"])
print(" SCK on", cfg["sck"])
print(" MISO on", cfg["miso"])
print(" MOSI on", cfg["mosi"])
print("run nrf24l01test.slave() on slave, then nrf24l01test.master() on master")

View File

@ -4,8 +4,9 @@
from micropython import const
_CONVERT = const(0x44)
_RD_SCRATCH = const(0xbe)
_WR_SCRATCH = const(0x4e)
_RD_SCRATCH = const(0xBE)
_WR_SCRATCH = const(0x4E)
class DS18X20:
def __init__(self, onewire):
@ -26,7 +27,7 @@ class DS18X20:
self.ow.writebyte(_RD_SCRATCH)
self.ow.readinto(self.buf)
if self.ow.crc8(self.buf):
raise Exception('CRC error')
raise Exception("CRC error")
return self.buf
def write_scratch(self, rom, buf):
@ -40,12 +41,12 @@ class DS18X20:
if rom[0] == 0x10:
if buf[1]:
t = buf[0] >> 1 | 0x80
t = -((~t + 1) & 0xff)
t = -((~t + 1) & 0xFF)
else:
t = buf[0] >> 1
return t - 0.25 + (buf[7] - buf[6]) / buf[7]
else:
t = buf[1] << 8 | buf[0]
if t & 0x8000: # sign bit set
t = -((t ^ 0xffff) + 1)
if t & 0x8000: # sign bit set
t = -((t ^ 0xFFFF) + 1)
return t / 16

View File

@ -1,16 +1,17 @@
# 1-Wire driver for MicroPython
# MIT license; Copyright (c) 2016 Damien P. George
from micropython import const
import _onewire as _ow
class OneWireError(Exception):
pass
class OneWire:
SEARCH_ROM = const(0xf0)
MATCH_ROM = const(0x55)
SKIP_ROM = const(0xcc)
SEARCH_ROM = 0xF0
MATCH_ROM = 0x55
SKIP_ROM = 0xCC
def __init__(self, pin):
self.pin = pin
@ -44,14 +45,14 @@ class OneWire:
def select_rom(self, rom):
self.reset()
self.writebyte(MATCH_ROM)
self.writebyte(self.MATCH_ROM)
self.write(rom)
def scan(self):
devices = []
diff = 65
rom = False
for i in range(0xff):
for i in range(0xFF):
rom, diff = self._search_rom(rom, diff)
if rom:
devices += [rom]
@ -62,7 +63,7 @@ class OneWire:
def _search_rom(self, l_rom, diff):
if not self.reset():
return None, 0
self.writebyte(SEARCH_ROM)
self.writebyte(self.SEARCH_ROM)
if not l_rom:
l_rom = bytearray(8)
rom = bytearray(8)
@ -73,10 +74,10 @@ class OneWire:
for bit in range(8):
b = self.readbit()
if self.readbit():
if b: # there are no devices or there is an error on the bus
if b: # there are no devices or there is an error on the bus
return None, 0
else:
if not b: # collision, two devices with different bit meaning
if not b: # collision, two devices with different bit meaning
if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i):
b = 1
next_diff = i

View File

@ -27,15 +27,15 @@ import time
_CMD_TIMEOUT = const(100)
_R1_IDLE_STATE = const(1 << 0)
#R1_ERASE_RESET = const(1 << 1)
# R1_ERASE_RESET = const(1 << 1)
_R1_ILLEGAL_COMMAND = const(1 << 2)
#R1_COM_CRC_ERROR = const(1 << 3)
#R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
#R1_ADDRESS_ERROR = const(1 << 5)
#R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xfc)
_TOKEN_STOP_TRAN = const(0xfd)
_TOKEN_DATA = const(0xfe)
# R1_COM_CRC_ERROR = const(1 << 3)
# R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
# R1_ADDRESS_ERROR = const(1 << 5)
# R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xFC)
_TOKEN_STOP_TRAN = const(0xFD)
_TOKEN_DATA = const(0xFE)
class SDCard:
@ -47,7 +47,7 @@ class SDCard:
self.dummybuf = bytearray(512)
self.tokenbuf = bytearray(1)
for i in range(512):
self.dummybuf[i] = 0xff
self.dummybuf[i] = 0xFF
self.dummybuf_memoryview = memoryview(self.dummybuf)
# initialise the card
@ -72,7 +72,7 @@ class SDCard:
# clock card at least 100 cycles with cs high
for i in range(16):
self.spi.write(b'\xff')
self.spi.write(b"\xff")
# CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts)
for _ in range(5):
@ -82,7 +82,7 @@ class SDCard:
raise OSError("no SD card")
# CMD8: determine card version
r = self.cmd(8, 0x01aa, 0x87, 4)
r = self.cmd(8, 0x01AA, 0x87, 4)
if r == _R1_IDLE_STATE:
self.init_card_v2()
elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND):
@ -96,15 +96,15 @@ class SDCard:
raise OSError("no response from SD card")
csd = bytearray(16)
self.readinto(csd)
if csd[0] & 0xc0 == 0x40: # CSD version 2.0
if csd[0] & 0xC0 == 0x40: # CSD version 2.0
self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024
elif csd[0] & 0xc0 == 0x00: # CSD version 1.0 (old, <=2GB)
elif csd[0] & 0xC0 == 0x00: # CSD version 1.0 (old, <=2GB)
c_size = csd[6] & 0b11 | csd[7] << 2 | (csd[8] & 0b11000000) << 4
c_size_mult = ((csd[9] & 0b11) << 1) | csd[10] >> 7
self.sectors = (c_size + 1) * (2 ** (c_size_mult + 2))
else:
raise OSError("SD card CSD format not supported")
#print('sectors', self.sectors)
# print('sectors', self.sectors)
# CMD16: set block length to 512 bytes
if self.cmd(16, 512, 0) != 0:
@ -118,7 +118,7 @@ class SDCard:
self.cmd(55, 0, 0)
if self.cmd(41, 0, 0) == 0:
self.cdv = 512
#print("[SDCard] v1 card")
# print("[SDCard] v1 card")
return
raise OSError("timeout waiting for v1 card")
@ -130,7 +130,7 @@ class SDCard:
if self.cmd(41, 0x40000000, 0) == 0:
self.cmd(58, 0, 0, 4)
self.cdv = 1
#print("[SDCard] v2 card")
# print("[SDCard] v2 card")
return
raise OSError("timeout waiting for v2 card")
@ -148,24 +148,24 @@ class SDCard:
self.spi.write(buf)
if skip1:
self.spi.readinto(self.tokenbuf, 0xff)
self.spi.readinto(self.tokenbuf, 0xFF)
# wait for the response (response[7] == 0)
for i in range(_CMD_TIMEOUT):
self.spi.readinto(self.tokenbuf, 0xff)
self.spi.readinto(self.tokenbuf, 0xFF)
response = self.tokenbuf[0]
if not (response & 0x80):
# this could be a big-endian integer that we are getting here
for j in range(final):
self.spi.write(b'\xff')
self.spi.write(b"\xff")
if release:
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
return response
# timeout
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
return -1
def readinto(self, buf):
@ -173,7 +173,7 @@ class SDCard:
# read until start byte (0xff)
for i in range(_CMD_TIMEOUT):
self.spi.readinto(self.tokenbuf, 0xff)
self.spi.readinto(self.tokenbuf, 0xFF)
if self.tokenbuf[0] == _TOKEN_DATA:
break
else:
@ -183,15 +183,15 @@ class SDCard:
# read data
mv = self.dummybuf_memoryview
if len(buf) != len(mv):
mv = mv[:len(buf)]
mv = mv[: len(buf)]
self.spi.write_readinto(mv, buf)
# read checksum
self.spi.write(b'\xff')
self.spi.write(b'\xff')
self.spi.write(b"\xff")
self.spi.write(b"\xff")
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
def write(self, token, buf):
self.cs(0)
@ -199,42 +199,42 @@ class SDCard:
# send: start of block, data, checksum
self.spi.read(1, token)
self.spi.write(buf)
self.spi.write(b'\xff')
self.spi.write(b'\xff')
self.spi.write(b"\xff")
self.spi.write(b"\xff")
# check the response
if (self.spi.read(1, 0xff)[0] & 0x1f) != 0x05:
if (self.spi.read(1, 0xFF)[0] & 0x1F) != 0x05:
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
return
# wait for write to finish
while self.spi.read(1, 0xff)[0] == 0:
while self.spi.read(1, 0xFF)[0] == 0:
pass
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
def write_token(self, token):
self.cs(0)
self.spi.read(1, token)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
# wait for write to finish
while self.spi.read(1, 0xff)[0] == 0x00:
while self.spi.read(1, 0xFF)[0] == 0x00:
pass
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
def readblocks(self, block_num, buf):
nblocks = len(buf) // 512
assert nblocks and not len(buf) % 512, 'Buffer length is invalid'
assert nblocks and not len(buf) % 512, "Buffer length is invalid"
if nblocks == 1:
# CMD17: set read address for single block
if self.cmd(17, block_num * self.cdv, 0, release=False) != 0:
# release the card
self.cs(1)
raise OSError(5) # EIO
raise OSError(5) # EIO
# receive the data and release card
self.readinto(buf)
else:
@ -242,7 +242,7 @@ class SDCard:
if self.cmd(18, block_num * self.cdv, 0, release=False) != 0:
# release the card
self.cs(1)
raise OSError(5) # EIO
raise OSError(5) # EIO
offset = 0
mv = memoryview(buf)
while nblocks:
@ -250,23 +250,23 @@ class SDCard:
self.readinto(mv[offset : offset + 512])
offset += 512
nblocks -= 1
if self.cmd(12, 0, 0xff, skip1=True):
raise OSError(5) # EIO
if self.cmd(12, 0, 0xFF, skip1=True):
raise OSError(5) # EIO
def writeblocks(self, block_num, buf):
nblocks, err = divmod(len(buf), 512)
assert nblocks and not err, 'Buffer length is invalid'
assert nblocks and not err, "Buffer length is invalid"
if nblocks == 1:
# CMD24: set write address for single block
if self.cmd(24, block_num * self.cdv, 0) != 0:
raise OSError(5) # EIO
raise OSError(5) # EIO
# send the data
self.write(_TOKEN_DATA, buf)
else:
# CMD25: set write address for first block
if self.cmd(25, block_num * self.cdv, 0) != 0:
raise OSError(5) # EIO
raise OSError(5) # EIO
# send the data
offset = 0
mv = memoryview(buf)
@ -277,5 +277,5 @@ class SDCard:
self.write_token(_TOKEN_STOP_TRAN)
def ioctl(self, op, arg):
if op == 4: # get number of blocks
if op == 4: # get number of blocks
return self.sectors

View File

@ -2,59 +2,60 @@
# Peter hinch 30th Jan 2016
import os, sdcard, machine
def sdtest():
spi = machine.SPI(1)
spi.init() # Ensure right baudrate
sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB
sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB
vfs = os.VfsFat(sd)
os.mount(vfs, '/fc')
print('Filesystem check')
print(os.listdir('/fc'))
os.mount(vfs, "/fc")
print("Filesystem check")
print(os.listdir("/fc"))
line = 'abcdefghijklmnopqrstuvwxyz\n'
lines = line * 200 # 5400 chars
short = '1234567890\n'
line = "abcdefghijklmnopqrstuvwxyz\n"
lines = line * 200 # 5400 chars
short = "1234567890\n"
fn = '/fc/rats.txt'
fn = "/fc/rats.txt"
print()
print('Multiple block read/write')
with open(fn,'w') as f:
print("Multiple block read/write")
with open(fn, "w") as f:
n = f.write(lines)
print(n, 'bytes written')
print(n, "bytes written")
n = f.write(short)
print(n, 'bytes written')
print(n, "bytes written")
n = f.write(lines)
print(n, 'bytes written')
print(n, "bytes written")
with open(fn,'r') as f:
with open(fn, "r") as f:
result1 = f.read()
print(len(result1), 'bytes read')
print(len(result1), "bytes read")
fn = '/fc/rats1.txt'
fn = "/fc/rats1.txt"
print()
print('Single block read/write')
with open(fn,'w') as f:
n = f.write(short) # one block
print(n, 'bytes written')
print("Single block read/write")
with open(fn, "w") as f:
n = f.write(short) # one block
print(n, "bytes written")
with open(fn,'r') as f:
with open(fn, "r") as f:
result2 = f.read()
print(len(result2), 'bytes read')
print(len(result2), "bytes read")
os.umount('/fc')
os.umount("/fc")
print()
print('Verifying data read back')
print("Verifying data read back")
success = True
if result1 == ''.join((lines, short, lines)):
print('Large file Pass')
if result1 == "".join((lines, short, lines)):
print("Large file Pass")
else:
print('Large file Fail')
print("Large file Fail")
success = False
if result2 == short:
print('Small file Pass')
print("Small file Pass")
else:
print('Small file Fail')
print("Small file Fail")
success = False
print()
print('Tests', 'passed' if success else 'failed')
print("Tests", "passed" if success else "failed")

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