ports/nrf: Upmerging port with upstream master

This commit is contained in:
Glenn Ruben Bakke 2017-10-04 21:45:04 +02:00
commit bcab2ba0a8
1226 changed files with 7208 additions and 445341 deletions

23
.gitattributes vendored
View File

@ -15,16 +15,13 @@
# These should also not be modified by git.
tests/basics/string_cr_conversion.py -text
tests/basics/string_crlf_conversion.py -text
stmhal/pybcdc.inf_template -text
stmhal/usbd_* -text
stmhal/boards/*/stm32f4xx_hal_conf.h -text
stmhal/cmsis/** -text
stmhal/hal/** -text
stmhal/usbdev/** -text
stmhal/usbhost/** -text
cc3200/hal/aes.c -text
cc3200/hal/aes.h -text
cc3200/hal/des.c -text
cc3200/hal/i2s.c -text
cc3200/hal/i2s.h -text
cc3200/version.h -text
ports/stm32/pybcdc.inf_template -text
ports/stm32/usbd_* -text
ports/stm32/usbdev/** -text
ports/stm32/usbhost/** -text
ports/cc3200/hal/aes.c -text
ports/cc3200/hal/aes.h -text
ports/cc3200/hal/des.c -text
ports/cc3200/hal/i2s.c -text
ports/cc3200/hal/i2s.h -text
ports/cc3200/version.h -text

4
.gitmodules vendored
View File

@ -11,3 +11,7 @@
[submodule "lib/berkeley-db-1.xx"]
path = lib/berkeley-db-1.xx
url = https://github.com/pfalcon/berkeley-db-1.xx
[submodule "lib/stm32lib"]
path = lib/stm32lib
url = https://github.com/micropython/stm32lib
branch = work-F4-1.13.1+F7-1.5.0+L4-1.3.0

View File

@ -19,49 +19,48 @@ before_script:
- sudo apt-get install -y --force-yes gcc-arm-none-eabi
# For teensy build
- sudo apt-get install realpath
# For coverage testing
# cpp-coveralls 0.4 conflicts with urllib3 preinstalled in Travis VM
- sudo pip install cpp-coveralls==0.3.12
# For coverage testing (upgrade is used to get latest urllib3 version)
- sudo pip install --upgrade cpp-coveralls
- gcc --version
- arm-none-eabi-gcc --version
- python3 --version
script:
- make -C mpy-cross
- make -C minimal CROSS=1 build/firmware.bin
- ls -l minimal/build/firmware.bin
- make -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 minimal/build/firmware.bin ${HOME}/persist/; fi'
- make -C unix deplibs
- make -C unix
- make -C unix nanbox
- make -C bare-arm
- make -C qemu-arm test
- make -C stmhal
- make -C stmhal BOARD=PYBV11 MICROPY_PY_WIZNET5K=1 MICROPY_PY_CC3K=1
- make -C stmhal BOARD=STM32F769DISC
- make -C stmhal BOARD=STM32L476DISC
- make -C teensy
- make -C cc3200 BTARGET=application BTYPE=release
- make -C cc3200 BTARGET=bootloader BTYPE=release
- make -C windows CROSS_COMPILE=i686-w64-mingw32-
- 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then cp ports/minimal/build/firmware.bin ${HOME}/persist/; fi'
- make -C ports/unix deplibs
- make -C ports/unix
- make -C ports/unix nanbox
- make -C ports/bare-arm
- make -C ports/qemu-arm test
- make -C ports/stm32
- make -C ports/stm32 BOARD=PYBV11 MICROPY_PY_WIZNET5K=1 MICROPY_PY_CC3K=1
- make -C ports/stm32 BOARD=STM32F769DISC
- make -C ports/stm32 BOARD=STM32L476DISC
- make -C ports/teensy
- make -C ports/cc3200 BTARGET=application BTYPE=release
- make -C ports/cc3200 BTARGET=bootloader BTYPE=release
- make -C ports/windows CROSS_COMPILE=i686-w64-mingw32-
# run tests without coverage info
#- (cd tests && MICROPY_CPYTHON3=python3.4 ./run-tests)
#- (cd tests && MICROPY_CPYTHON3=python3.4 ./run-tests --emit native)
# run tests with coverage info
- make -C unix coverage
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests)
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests -d thread)
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests --emit native)
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests --via-mpy -d basics float)
- make -C ports/unix coverage
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests)
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests -d thread)
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests --emit native)
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests --via-mpy -d basics float)
# run coveralls coverage analysis (try to, even if some builds/tests failed)
- (cd unix && coveralls --root .. --build-root . --gcov $(which gcov) --gcov-options '\-o build-coverage/' --include py --include extmod)
- (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)
- (grep "FAIL" qemu-arm/build/console.out)
- (grep "FAIL" ports/qemu-arm/build/console.out)

View File

@ -34,10 +34,10 @@ Major components in this repository:
core library.
- mpy-cross/ -- the MicroPython cross-compiler which is used to turn scripts
into precompiled bytecode.
- unix/ -- a version of MicroPython that runs on Unix.
- stmhal/ -- a version of MicroPython that runs on the PyBoard and similar
- ports/unix/ -- a version of MicroPython that runs on Unix.
- ports/stm32/ -- a version of MicroPython that runs on the PyBoard and similar
STM32 boards (using ST's Cube HAL drivers).
- minimal/ -- a minimal MicroPython port. Start with this if you want
- ports/minimal/ -- a minimal MicroPython port. Start with this if you want
to port MicroPython to another microcontroller.
- tests/ -- test framework and test scripts.
- docs/ -- user documentation in Sphinx reStructuredText format. Rendered
@ -45,13 +45,13 @@ Major components in this repository:
to select needed board/port at the bottom left corner).
Additional components:
- bare-arm/ -- a bare minimum version of MicroPython for ARM MCUs. Used
- ports/bare-arm/ -- a bare minimum version of MicroPython for ARM MCUs. Used
mostly to control code size.
- teensy/ -- a version of MicroPython that runs on the Teensy 3.1
- ports/teensy/ -- a version of MicroPython that runs on the Teensy 3.1
(preliminary but functional).
- pic16bit/ -- a version of MicroPython for 16-bit PIC microcontrollers.
- cc3200/ -- a version of MicroPython that runs on the CC3200 from TI.
- esp8266/ -- an experimental port for ESP8266 WiFi modules.
- ports/pic16bit/ -- a version of MicroPython for 16-bit PIC microcontrollers.
- ports/cc3200/ -- a version of MicroPython that runs on the CC3200 from TI.
- ports/esp8266/ -- an experimental port for ESP8266 WiFi modules.
- extmod/ -- additional (non-core) modules implemented in C.
- tools/ -- various tools, including the pyboard.py module.
- examples/ -- a few example Python scripts.
@ -72,7 +72,8 @@ Alternatively, fallback implementation based on setjmp/longjmp can be used.
To build (see section below for required dependencies):
$ cd unix
$ git submodule update --init
$ cd ports/unix
$ make axtls
$ make
@ -104,44 +105,49 @@ Standard library modules come from
External dependencies
---------------------
Building Unix version requires some dependencies installed. For
Building MicroPython ports may require some dependencies installed.
For Unix port, `libffi` library and `pkg-config` tool are required. On
Debian/Ubuntu/Mint derivative Linux distros, install `build-essential`
(includes toolchain and make), `libffi-dev`, and `pkg-config` packages.
Other dependencies can be built together with MicroPython. Oftentimes,
you need to do this to enable extra features or capabilities. To build
Other dependencies can be built together with MicroPython. This may
be required to enable extra features or capabilities, and in recent
versions of MicroPython, these may be enabled by default. To build
these additional dependencies, first fetch git submodules for them:
$ git submodule update --init
Use this same command to get the latest versions of dependencies, as
they are updated from time to time. After that, in `unix/` dir, execute:
Use the same command to get the latest versions of dependencies, as
they are updated from time to time. After that, in the port directory
(e.g. `ports/unix/`), execute:
$ make deplibs
This will build all available dependencies (regardless whether they
are used or not). If you intend to build MicroPython with additional
options (like cross-compiling), the same set of options should be passed
to `make deplibs`. To actually enabled use of dependencies, edit
`unix/mpconfigport.mk` file, which has inline descriptions of the options.
For example, to build SSL module (required for `upip` tool described above),
set `MICROPY_PY_USSL` to 1.
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.
In `unix/mpconfigport.mk`, you can also disable some dependencies enabled
by default, like FFI support, which requires libffi development files to
be installed.
For some ports, building required dependences is transparent, and happens
automatically. They still need to be fetched with the git submodule command
above.
The STM version
---------------
The STM32 version
-----------------
The "stmhal" port requires an ARM compiler, arm-none-eabi-gcc, and associated
The "stm32" port requires an ARM compiler, arm-none-eabi-gcc, and associated
bin-utils. For those using Arch Linux, you need arm-none-eabi-binutils and
arm-none-eabi-gcc packages. Otherwise, try here:
https://launchpad.net/gcc-arm-embedded
To build:
$ cd stmhal
$ git submodule update --init
$ cd ports/stm32
$ make
You then need to get your board into DFU mode. On the pyboard, connect the
@ -155,4 +161,4 @@ Then to flash the code via USB DFU to your device:
This will use the included `tools/pydfu.py` script. If flashing the firmware
does not work it may be because you don't have the correct permissions, and
need to use `sudo make deploy`.
See the README.md file in the stmhal/ directory for further details.
See the README.md file in the ports/stm32/ directory for further details.

View File

@ -1,91 +0,0 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2015 Daniel Campora
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdint.h>
#include <string.h>
#include "py/mpstate.h"
#include "mpexception.h"
/******************************************************************************
DECLARE PRIVATE FUNCTIONS
******************************************************************************/
STATIC void mpexception_set_user_interrupt (int chr, void *data);
/******************************************************************************
DECLARE EXPORTED DATA
******************************************************************************/
const char mpexception_value_invalid_arguments[] = "invalid argument(s) value";
const char mpexception_num_type_invalid_arguments[] = "invalid argument(s) num/type";
const char mpexception_uncaught[] = "uncaught exception";
int user_interrupt_char = -1;
/******************************************************************************
DECLARE PRIVATE DATA
******************************************************************************/
STATIC void *user_interrupt_data = NULL;
/******************************************************************************
DEFINE PUBLIC FUNCTIONS
******************************************************************************/
void mpexception_init0 (void) {
// Create an exception object for interrupting through the stdin uart
MP_STATE_PORT(mp_const_user_interrupt) = mp_obj_new_exception(&mp_type_KeyboardInterrupt);
mpexception_set_user_interrupt (-1, MP_STATE_PORT(mp_const_user_interrupt));
}
void mpexception_set_interrupt_char (int c) {
if (c != -1) {
mp_obj_exception_clear_traceback(MP_STATE_PORT(mp_const_user_interrupt));
}
mpexception_set_user_interrupt(c, MP_STATE_PORT(mp_const_user_interrupt));
}
// Call this function to raise a pending exception during an interrupt.
// It will try to raise the exception "softly" by setting the
// mp_pending_exception variable hoping that the VM will notice it.
void mpexception_nlr_jump (void *o) {
if (MP_STATE_PORT(mp_pending_exception) == MP_OBJ_NULL) {
MP_STATE_PORT(mp_pending_exception) = o;
}
}
void mpexception_keyboard_nlr_jump (void) {
mpexception_nlr_jump (user_interrupt_data);
}
/******************************************************************************
DEFINE PRIVATE FUNCTIONS
******************************************************************************/
STATIC void mpexception_set_user_interrupt (int chr, void *data) {
user_interrupt_char = chr;
user_interrupt_data = data;
}

View File

@ -98,7 +98,7 @@ copyright = '2014-2017, 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.9.1'
version = release = '1.9.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View File

@ -20,6 +20,20 @@ To set the colour of pixels use::
>>> np[1] = (0, 128, 0) # set to green, half brightness
>>> np[2] = (0, 0, 64) # set to blue, quarter brightness
For LEDs with more than 3 colours, such as RGBW pixels or RGBY pixels, the
NeoPixel class takes a ``bpp`` parameter. To setup a NeoPixel object for an
RGBW Pixel, do the following::
>>> import machine, neopixel
>>> np = neopixel.NeoPixel(machine.Pin(4), 8, bpp=4)
In a 4-bpp mode, remember to use 4-tuples instead of 3-tuples to set the colour.
For example to set the first three pixels use::
>>> np[0] = (255, 0, 0, 128) # Orange in an RGBY Setup
>>> np[1] = (0, 255, 0, 128) # Yellow-green in an RGBY Setup
>>> np[2] = (0, 0, 255, 128) # Green-blue in an RGBY Setup
Then use the ``write()`` method to output the colours to the LEDs::
>>> np.write()

View File

@ -76,20 +76,24 @@ Example::
Functions
---------
.. function:: open(stream, \*, flags=0, cachesize=0, pagesize=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
parameters of the database operation (most users will not need them):
* *flags* - Currently unused.
* *cachesize* - Suggested maximum memory cache size in bytes. For a
board with enough memory using larger values may improve performance.
The value is only a recommendation, the module may use more memory if
values set too low.
* *pagesize* - Page size used for the nodes in BTree. Acceptable range
is 512-65536. If 0, underlying I/O block size will be used (the best
compromise between memory usage and performance).
is 512-65536. If 0, a port-specific default will be used, optimized for
port's memory usage and/or performance.
* *cachesize* - Suggested memory cache size in bytes. For a
board with enough memory using larger values may improve performance.
Cache policy is as follows: entire cache is not allocated at once;
instead, accessing a new page in database will allocate a memory buffer
for it, until value specified by *cachesize* is reached. Then, these
buffers will be managed using LRU (least recently used) policy. More
buffers may still be allocated if needed (e.g., if a database contains
big keys and/or values). Allocated cache buffers aren't reclaimed.
* *minkeypage* - Minimum number of keys to store per page. Default value
of 0 equivalent to 2.

View File

@ -38,9 +38,9 @@ Constructors
- *width* is the width of the FrameBuffer in pixels
- *height* is the height of the FrameBuffer in pixels
- *format* specifies the type of pixel used in the FrameBuffer;
valid values are ``framebuf.MVLSB``, ``framebuf.RGB565``
and ``framebuf.GS4_HMSB``. MVLSB is monochrome 1-bit color,
RGB565 is RGB 16-bit color, and GS4_HMSB is grayscale 4-bit color.
permissible values are listed under Constants below. These set the
number of bits used to encode a color value and the layout of these
bits in *buffer*.
Where a color value c is passed to a method, c is a small integer
with an encoding that is dependent on the format of the FrameBuffer.
- *stride* is the number of pixels between each horizontal line
@ -110,8 +110,9 @@ Other methods
corresponding color will be considered transparent: all pixels with that
color value will not be drawn.
This method works between FrameBuffer's utilising different formats, but the
resulting colors may be unexpected due to the mismatch in color formats.
This method works between FrameBuffer instances utilising different formats,
but the resulting colors may be unexpected due to the mismatch in color
formats.
Constants
---------

View File

@ -40,8 +40,7 @@ information pertaining to a specific port.
Beyond the built-in libraries described in this documentation, many more
modules from the Python standard library, as well as further MicroPython
extensions to it, can be found in the `micropython-lib repository
<https://github.com/micropython/micropython-lib>`_.
extensions to it, can be found in `micropython-lib`.
Python standard libraries and micro-libraries
---------------------------------------------
@ -54,7 +53,7 @@ e.g. ``ujson`` instead of ``json``. This is to signify that such a module is
micro-library, i.e. implements only a subset of CPython module functionality.
By naming them differently, a user has a choice to write a Python-level module
to extend functionality for better compatibility with CPython (indeed, this is
what done by micropython-lib project mentioned above).
what done by the `micropython-lib` project mentioned above).
On some embedded platforms, where it may be cumbersome to add Python-level
wrapper modules to achieve naming compatibility with CPython, micro-modules

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

View File

@ -4,17 +4,44 @@
class Signal -- control and sense external I/O devices
======================================================
The Signal class is a simple extension of Pin class. Unlike Pin, which
The Signal class is a simple extension of the `Pin` class. Unlike Pin, which
can be only in "absolute" 0 and 1 states, a Signal can be in "asserted"
(on) or "deasserted" (off) states, while being inverted (active-low) or
not. Summing up, it adds logical inversion support to Pin functionality.
not. In other words, it adds logical inversion support to Pin functionality.
While this may seem a simple addition, it is exactly what is needed to
support wide array of simple digital devices in a way portable across
different boards, which is one of the major MicroPython goals. Regardless
whether different users have an active-high or active-low LED, a normally
open or normally closed relay - you can develop single, nicely looking
of whether different users have an active-high or active-low LED, a normally
open or normally closed relay - you can develop a single, nicely looking
application which works with each of them, and capture hardware
configuration differences in few lines on the config file of your app.
configuration differences in few lines in the config file of your app.
Example::
from machine import Pin, Signal
# Suppose you have an active-high LED on pin 0
led1_pin = Pin(0, Pin.OUT)
# ... and active-low LED on pin 1
led2_pin = Pin(1, Pin.OUT)
# Now to light up both of them using Pin class, you'll need to set
# them to different values
led1_pin.value(1)
led2_pin.value(0)
# Signal class allows to abstract away active-high/active-low
# difference
led1 = Signal(led1_pin, invert=False)
led2 = Signal(led2_pin, invert=True)
# Now lighting up them looks the same
led1.value(1)
led2.value(1)
# Even better:
led1.on()
led2.on()
Following is the guide when Signal vs Pin should be used:
@ -33,11 +60,11 @@ 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
than if you implemented active-high vs active-low device differences in
Python manually!). Also, Pin is low-level object which needs to be
Python manually!). Also, Pin is a low-level object which needs to be
implemented for each support board, while Signal is a high-level object
which comes for free once Pin is implemented.
If in doubt, give the Signal a try! Once again, it is developed to save
If in doubt, give the Signal a try! Once again, it is offered to save
developers from the need to handle unexciting differences like active-low
vs active-high signals, and allow other users to share and enjoy your
application, instead of being frustrated by the fact that it doesn't

View File

@ -46,7 +46,7 @@ Functions
.. function:: mem_info([verbose])
Print information about currently used memory. If the *verbose`* argument
Print information about currently used memory. If the *verbose* argument
is given then extra information is printed.
The information that is printed is implementation dependent, but currently

View File

@ -9,7 +9,7 @@ This module provides network drivers and routing configuration. To use this
module, a MicroPython variant/build with network capabilities must be installed.
Network drivers for specific hardware are available within this module and are
used to configure hardware network interface(s). Network services provided
by configured interfaces are then available for use via the :mod:`socket`
by configured interfaces are then available for use via the :mod:`usocket`
module.
For example::
@ -39,9 +39,9 @@ Common network adapter interface
================================
This section describes an (implied) abstract base class for all network
interface classes implemented by different ports of MicroPython for
different hardware. This means that MicroPython does not actually
provide `AbstractNIC` class, but any actual NIC class, as described
interface classes implemented by `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.
.. class:: AbstractNIC(id=None, ...)
@ -411,7 +411,7 @@ parameter should be `id`.
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 `MicroPython port`).
========= ===========
Parameter Description

View File

@ -28,7 +28,7 @@ Functions
this function takes just exception value instead of exception type,
exception value, and traceback object; *file* argument should be
positional; further arguments are not supported. CPython-compatible
``traceback`` module can be found in micropython-lib.
``traceback`` module can be found in `micropython-lib`.
Constants
---------

View File

@ -29,8 +29,12 @@ Functions
.. function:: a2b_base64(data)
Convert Base64-encoded data to binary representation. Returns bytes string.
Decode base64-encoded data, ignoring invalid characters in the input.
Conforms to `RFC 2045 s.6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_.
Returns a bytes object.
.. function:: b2a_base64(data)
Encode binary data in Base64 format. Returns string.
Encode binary data in base64 format, as in `RFC 3548
<https://tools.ietf.org/html/rfc3548.html>`_. Returns the encoded data
followed by a newline character, as a bytes object.

View File

@ -89,8 +89,22 @@ Functions
Return a bytes object with n random bytes. Whenever possible, it is
generated by the hardware random number generator.
.. function:: dupterm(stream_object)
.. function:: dupterm(stream_object, index=0)
Duplicate or switch MicroPython terminal (the REPL) on the passed stream-like
object. The given object must implement the ``readinto()`` and ``write()``
methods. If ``None`` is passed, previously set redirection is cancelled.
Duplicate or switch the MicroPython terminal (the REPL) on the given stream-like
object. The *stream_object* argument must implement the ``readinto()`` and
``write()`` methods. The stream should be in non-blocking mode and
``readinto()`` should return ``None`` if there is no data available for reading.
After calling this function all terminal output is repeated on this stream,
and any input that is available on the stream is passed on to the terminal input.
The *index* parameter should be a non-negative integer and specifies which
duplication slot is set. A given port may implement more than one slot (slot 0
will always be available) and in that case terminal input and output is
duplicated on all the slots that are set.
If ``None`` is passed as the *stream_object* then duplication is cancelled on
the slot given by *index*.
The function returns the previous stream-like object in the given slot.

View File

@ -9,12 +9,6 @@
This module provides access to the BSD socket interface.
.. admonition:: Difference to CPython
:class: attention
CPython used to have a ``socket.error`` exception which is now deprecated,
and is an alias of `OSError`. In MicroPython, use `OSError` directly.
.. admonition:: Difference to CPython
:class: attention
@ -27,11 +21,47 @@ This module provides access to the BSD socket interface.
Socket address format(s)
------------------------
The functions below which expect a network address, accept it in the format of
*(ipv4_address, port)*, where *ipv4_address* is a string with dot-notation numeric
IPv4 address, e.g. ``"8.8.8.8"``, and port is integer port number in the range
1-65535. Note the domain names are not accepted as *ipv4_address*, they should be
resolved first using `usocket.getaddrinfo()`.
The native socket address format of the ``usocket`` module is an opaque data type
returned by `getaddrinfo` function, which must be used to resolve textual address
(including numeric addresses)::
sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1]
# You must use getaddrinfo() even for numeric addresses
sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1]
# Now you can use that address
sock.connect(addr)
Using `getaddrinfo` is the most efficient (both in terms of memory and processing
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`),
and some ports still accept only numeric addresses in the tuple format,
and require to use `getaddrinfo` function to resolve domain names.
Summing up:
* Always use `getaddrinfo` when writing portable applications.
* Tuple addresses described below can be used as a shortcut for
quick hacks and interactive use, if your port supports them.
Tuple address format for ``socket`` module:
* IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with
dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and
integer port number in the range 1-65535. Note the domain names are not
accepted as *ipv4_address*, they should be resolved first using
`usocket.getaddrinfo()`.
* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address*
is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``,
and *port* is an integer port number in the range 1-65535. *flowinfo*
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`.
Functions
---------
@ -87,12 +117,12 @@ Constants
.. data:: usocket.SOL_*
Socket option levels (an argument to `setsockopt()`). The exact
inventory depends on a MicroPython port.
inventory depends on a `MicroPython port`.
.. data:: usocket.SO_*
Socket options (an argument to `setsockopt()`). The exact
inventory depends on a MicroPython port.
inventory depends on a `MicroPython port`.
Constants specific to WiPy:
@ -250,3 +280,13 @@ Methods
the length of *buf*.
Return value: number of bytes written.
.. exception:: socket.error
MicroPython does NOT have this exception.
.. admonition:: Difference to CPython
:class: attention
CPython used to have a ``socket.error`` exception which is now deprecated,
and is an alias of `OSError`. In MicroPython, use `OSError` directly.

View File

@ -15,4 +15,4 @@ It's as simple as::
if uart.any():
usb.write(uart.read(256))
pass_through(pyb.USB_VCP(), pyb.UART(1, 9600))
pass_through(pyb.USB_VCP(), pyb.UART(1, 9600, timeout=0))

View File

@ -279,7 +279,7 @@ After importing the modules, execute:
Then copy and paste all the Q(xxx) lines into a text editor. Check for and
remove lines which are obviously invalid. Open the file qstrdefsport.h which
will be found in stmhal (or the equivalent directory for the architecture in
will be found in ports/stm32 (or the equivalent directory for the architecture in
use). Copy and paste the corrected lines at the end of the file. Save the file,
rebuild and flash the firmware. The outcome can be checked by importing the
modules and again issuing:

View File

@ -54,11 +54,11 @@ Glossary
separate project
`micropython-lib <https://github.com/micropython/micropython-lib>`_
which provides implementations for many modules from CPython's
standard library. However, large subset of these modules required
standard library. However, large subset of these modules require
POSIX-like environment (Linux, MacOS, Windows may be partially
supported), and thus would work or make sense only with MicroPython
Unix port. Some subset of modules however usable for baremetal ports
too.
supported), and thus would work or make sense only with
`MicroPython Unix port`. Some subset of modules is however usable
for `baremetal` ports too.
Unlike monolithic :term:`CPython` stdlib, micropython-lib modules
are intended to be installed individually - either using manual
@ -68,7 +68,13 @@ Glossary
MicroPython supports different :term:`boards <board>`, RTOSes,
and OSes, and can be relatively easily adapted to new systems.
MicroPython with support for a particular system is called a
"port" to that system.
"port" to that system. Different ports may have widely different
functionality. This documentation is intended to be a reference
of the generic APIs available across different ports ("MicroPython
core"). Note that some ports may still omit some APIs described
here (e.g. due to resource constraints). Any such differences,
and port-specific extensions beyond MicroPython core functionality,
would be described in the separate port-specific documentation.
MicroPython Unix port
Unix port is one of the major :term:`MicroPython ports <MicroPython port>`.

View File

@ -21,6 +21,7 @@ This summarises the points detailed below and lists the principal recommendation
* Keep the code as short and simple as possible.
* Avoid memory allocation: no appending to lists or insertion into dictionaries, no floating point.
* Consider using ``micropython.schedule`` to work around the above constraint.
* Where an ISR returns multiple bytes use a pre-allocated ``bytearray``. If multiple integers are to be
shared between an ISR and the main program consider an array (``array.array``).
* Where data is shared between the main program and an ISR, consider disabling interrupts prior to accessing
@ -158,6 +159,26 @@ On platforms with hardware floating point (such as the Pyboard) the inline ARM T
round this limitation. This is because the processor stores float values in a machine word; values can be shared
between the ISR and main program code via an array of floats.
Using micropython.schedule
~~~~~~~~~~~~~~~~~~~~~~~~~~
This function enables an ISR to schedule a callback for execution "very soon". The callback is queued for
execution which will take place at a time when the heap is not locked. Hence it can create Python objects
and use floats. The callback is also guaranteed to run at a time when the main program has completed any
update of Python objects, so the callback will not encounter partially updated objects.
Typical usage is to handle sensor hardware. The ISR acquires data from the hardware and enables it to
issue a further interrupt. It then schedules a callback to process the data.
Scheduled callbacks should comply with the principles of interrupt handler design outlined below. This is to
avoid problems resulting from I/O activity and the modification of shared data which can arise in any code
which pre-empts the main program loop.
Execution time needs to be considered in relation to the frequency with which interrupts can occur. If an
interrupt occurs while the previous callback is executing, a further instance of the callback will be queued
for execution; this will run after the current instance has completed. A sustained high interrupt repetition
rate therefore carries a risk of unconstrained queue growth and eventual failure with a ``RuntimeError``.
Exceptions
----------

View File

@ -34,8 +34,6 @@
#include <string.h>
#include "py/nlr.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "pin.h"
#include "led.h"

View File

@ -40,7 +40,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) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "buffer too small"));
mp_raise_ValueError("buffer too small");
}
// issue start command

View File

@ -32,7 +32,21 @@ class SSD1306:
self.external_vcc = external_vcc
self.pages = self.height // 8
self.buffer = bytearray(self.pages * self.width)
self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MVLSB)
fb = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
self.framebuf = fb
# Provide methods for accessing FrameBuffer graphics primitives. This is a
# workround because inheritance from a native class is currently unsupported.
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
self.fill = fb.fill
self.pixel = fb.pixel
self.hline = fb.hline
self.vline = fb.vline
self.line = fb.line
self.rect = fb.rect
self.fill_rect = fb.fill_rect
self.text = fb.text
self.scroll = fb.scroll
self.blit = fb.blit
self.poweron()
self.init_display()
@ -88,18 +102,6 @@ class SSD1306:
self.write_cmd(self.pages - 1)
self.write_data(self.buffer)
def fill(self, col):
self.framebuf.fill(col)
def pixel(self, x, y, col):
self.framebuf.pixel(x, y, col)
def scroll(self, dx, dy):
self.framebuf.scroll(dx, dy)
def text(self, string, x, y, col=1):
self.framebuf.text(string, x, y, col)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):

View File

@ -49,10 +49,8 @@ STATIC uint8_t buf[SECTOR_SIZE];
void mp_spiflash_init(mp_spiflash_t *self) {
mp_hal_pin_write(self->cs, 1);
mp_hal_pin_output(self->cs);
mp_hal_pin_write(self->spi.sck, 0);
mp_hal_pin_output(self->spi.sck);
mp_hal_pin_output(self->spi.mosi);
mp_hal_pin_input(self->spi.miso);
const mp_machine_spi_p_t *protocol = self->spi->type->protocol;
protocol->init(self->spi, 0, NULL, (mp_map_t*)&mp_const_empty_map);
}
STATIC void mp_spiflash_acquire_bus(mp_spiflash_t *self) {
@ -66,7 +64,8 @@ STATIC void mp_spiflash_release_bus(mp_spiflash_t *self) {
}
STATIC void mp_spiflash_transfer(mp_spiflash_t *self, size_t len, const uint8_t *src, uint8_t *dest) {
mp_machine_soft_spi_transfer(&self->spi.base, len, src, dest);
const mp_machine_spi_p_t *protocol = self->spi->type->protocol;
protocol->transfer(self->spi, len, src, dest);
}
STATIC int mp_spiflash_wait_sr(mp_spiflash_t *self, uint8_t mask, uint8_t val, uint32_t timeout) {

View File

@ -30,8 +30,7 @@
typedef struct _mp_spiflash_t {
mp_hal_pin_obj_t cs;
// TODO replace with generic SPI object
mp_machine_soft_spi_obj_t spi;
mp_obj_base_t *spi; // object must have protocol pointing to mp_machine_spi_p_t struct
} mp_spiflash_t;
void mp_spiflash_init(mp_spiflash_t *self);

View File

@ -1,8 +1,8 @@
"""Test for nrf24l01 module."""
import struct
import pyb
from pyb import Pin, SPI
import utime
from machine import Pin, SPI
from nrf24l01 import NRF24L01
pipes = (b'\xf0\xf0\xf0\xf0\xe1', b'\xf0\xf0\xf0\xf0\xd2')
@ -24,7 +24,7 @@ def master():
while num_successes < num_needed and num_failures < num_needed:
# stop listening and send packet
nrf.stop_listening()
millis = pyb.millis()
millis = utime.ticks_ms()
led_state = max(1, (led_state << 1) & 0x0f)
print('sending:', millis, led_state)
try:
@ -36,10 +36,10 @@ def master():
nrf.start_listening()
# wait for response, with 250ms timeout
start_time = pyb.millis()
start_time = utime.ticks_ms()
timeout = False
while not nrf.any() and not timeout:
if pyb.elapsed_millis(start_time) > 250:
if utime.ticks_diff(utime.ticks_ms(), start_time) > 250:
timeout = True
if timeout:
@ -51,11 +51,11 @@ def master():
got_millis, = struct.unpack('i', nrf.recv())
# print response and round-trip delay
print('got response:', got_millis, '(delay', pyb.millis() - got_millis, 'ms)')
print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)')
num_successes += 1
# delay then loop
pyb.delay(250)
utime.sleep_ms(250)
print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures))
@ -69,18 +69,19 @@ def slave():
print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')
while True:
pyb.wfi()
machine.idle()
if nrf.any():
while nrf.any():
buf = nrf.recv()
millis, led_state = struct.unpack('ii', buf)
print('received:', millis, led_state)
for i in range(4):
if led_state & (1 << i):
pyb.LED(i + 1).on()
for led in leds:
if led_state & 1:
led.on()
else:
pyb.LED(i + 1).off()
pyb.delay(15)
led.off()
led_state >>= 1
utime.sleep_ms(15)
nrf.stop_listening()
try:
@ -90,6 +91,12 @@ def slave():
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 Y4')

View File

@ -1 +0,0 @@
../../drivers/onewire/ds18x20.py

View File

@ -1 +0,0 @@
../../drivers/onewire/onewire.py

View File

@ -1 +0,0 @@
../../tools/upip.py

View File

@ -1 +0,0 @@
../../tools/upip_utarfile.py

View File

@ -89,7 +89,7 @@
extern const struct _mp_obj_module_t mp_module_os;
#define MICROPY_PORT_BUILTIN_MODULES \
{ MP_OBJ_NEW_QSTR(MP_QSTR_uos), (mp_obj_t)&mp_module_os }, \
{ MP_ROM_QSTR(MP_QSTR_uos), MP_ROM_PTR(&mp_module_os) }, \
#define MICROPY_PORT_ROOT_POINTERS \

View File

@ -1,5 +1,5 @@
# Print a nice list of pins, their current settings, and available afs.
# Requires pins_af.py from stmhal/build-PYBV10/ directory.
# Requires pins_af.py from ports/stm32/build-PYBV10/ directory.
import pyb
import pins_af

View File

@ -269,7 +269,7 @@ int mp_machine_soft_i2c_readfrom(mp_obj_base_t *self_in, uint16_t addr, uint8_t
/******************************************************************************/
// MicroPython bindings for I2C
STATIC void machine_i2c_obj_init_helper(machine_i2c_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
STATIC void machine_i2c_obj_init_helper(machine_i2c_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { ARG_scl, ARG_sda, ARG_freq, ARG_timeout };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_scl, MP_ARG_REQUIRED | MP_ARG_OBJ },

View File

@ -24,8 +24,8 @@
* THE SOFTWARE.
*/
#include "py/runtime.h"
#include "extmod/machine_mem.h"
#include "py/nlr.h"
#if MICROPY_PY_MACHINE

View File

@ -30,6 +30,7 @@
#include "py/obj.h"
#include "py/runtime.h"
#include "extmod/virtpin.h"
#include "extmod/machine_pinbase.h"
// PinBase class
@ -40,10 +41,8 @@ typedef struct _mp_pinbase_t {
mp_obj_base_t base;
} mp_pinbase_t;
STATIC const mp_obj_type_t pinbase_type;
STATIC mp_pinbase_t pinbase_singleton = {
.base = { &pinbase_type },
STATIC const mp_pinbase_t pinbase_singleton = {
.base = { &machine_pinbase_type },
};
STATIC mp_obj_t pinbase_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {

View File

@ -29,9 +29,7 @@
#include <errno.h> // for declaration of global errno variable
#include <fcntl.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/runtime0.h"
#include "py/stream.h"
#if MICROPY_PY_BTREE
@ -281,7 +279,7 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
}
}
STATIC mp_obj_t btree_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
STATIC mp_obj_t btree_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
mp_obj_btree_t *self = MP_OBJ_TO_PTR(lhs_in);
switch (op) {
case MP_BINARY_OP_IN: {

View File

@ -27,13 +27,11 @@
#include <stdio.h>
#include <string.h>
#include "py/nlr.h"
#include "py/obj.h"
#include "py/runtime.h"
#if MICROPY_PY_FRAMEBUF
#include "stmhal/font_petme128_8x8.h"
#include "ports/stm32/font_petme128_8x8.h"
typedef struct _mp_obj_framebuf_t {
mp_obj_base_t base;

View File

@ -29,7 +29,6 @@
#include <string.h>
#include <stdio.h>
#include "py/nlr.h"
#include "py/objlist.h"
#include "py/runtime.h"
#include "py/stream.h"
@ -129,15 +128,15 @@ STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw,
ip_addr_t iplocal, ipremote;
if (!ipaddr_aton(mp_obj_str_get_str(args[1]), &iplocal)) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "not a valid local IP"));
mp_raise_ValueError("not a valid local IP");
}
if (!ipaddr_aton(mp_obj_str_get_str(args[2]), &ipremote)) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "not a valid remote IP"));
mp_raise_ValueError("not a valid remote IP");
}
struct netif *n = &lwip_slip_obj.lwip_netif;
if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "out of memory"));
mp_raise_ValueError("out of memory");
}
netif_set_up(n);
netif_set_default(n);
@ -1033,7 +1032,7 @@ STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) {
break;
}
case MOD_NETWORK_SOCK_DGRAM:
mp_not_implemented("");
mp_raise_NotImplementedError("");
break;
}
@ -1070,7 +1069,7 @@ STATIC mp_obj_t lwip_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_setblocking_obj, lwip_socket_setblocking);
STATIC mp_obj_t lwip_socket_setsockopt(mp_uint_t n_args, const mp_obj_t *args) {
STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) {
(void)n_args; // always 4
lwip_socket_obj_t *socket = args[0];
@ -1120,7 +1119,7 @@ STATIC mp_obj_t lwip_socket_setsockopt(mp_uint_t n_args, const mp_obj_t *args) {
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_setsockopt_obj, 4, 4, lwip_socket_setsockopt);
STATIC mp_obj_t lwip_socket_makefile(mp_uint_t n_args, const mp_obj_t *args) {
STATIC mp_obj_t lwip_socket_makefile(size_t n_args, const mp_obj_t *args) {
(void)n_args;
return args[0];
}

View File

@ -28,13 +28,10 @@
#include <assert.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/binary.h"
#include "extmod/modubinascii.h"
#include "uzlib/tinf.h"
mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) {
// Second argument is for an extension to allow a separator to be used
// between values.
@ -105,54 +102,64 @@ mp_obj_t mod_binascii_unhexlify(mp_obj_t data) {
}
MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_unhexlify_obj, mod_binascii_unhexlify);
// If ch is a character in the base64 alphabet, and is not a pad character, then
// the corresponding integer between 0 and 63, inclusively, is returned.
// Otherwise, -1 is returned.
static int mod_binascii_sextet(byte ch) {
if (ch >= 'A' && ch <= 'Z') {
return ch - 'A';
} else if (ch >= 'a' && ch <= 'z') {
return ch - 'a' + 26;
} else if (ch >= '0' && ch <= '9') {
return ch - '0' + 52;
} else if (ch == '+') {
return 62;
} else if (ch == '/') {
return 63;
} else {
return -1;
}
}
mp_obj_t mod_binascii_a2b_base64(mp_obj_t data) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
if (bufinfo.len % 4 != 0) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incorrect padding"));
}
byte *in = bufinfo.buf;
vstr_t vstr;
byte *in = bufinfo.buf;
if (bufinfo.len == 0) {
vstr_init_len(&vstr, 0);
}
else {
vstr_init_len(&vstr, ((bufinfo.len / 4) * 3) - ((in[bufinfo.len-1] == '=') ? ((in[bufinfo.len-2] == '=') ? 2 : 1 ) : 0));
}
byte *out = (byte*)vstr.buf;
for (mp_uint_t i = bufinfo.len; i; i -= 4) {
char hold[4];
for (int j = 4; j--;) {
if (in[j] >= 'A' && in[j] <= 'Z') {
hold[j] = in[j] - 'A';
} else if (in[j] >= 'a' && in[j] <= 'z') {
hold[j] = in[j] - 'a' + 26;
} else if (in[j] >= '0' && in[j] <= '9') {
hold[j] = in[j] - '0' + 52;
} else if (in[j] == '+') {
hold[j] = 62;
} else if (in[j] == '/') {
hold[j] = 63;
} else if (in[j] == '=') {
if (j < 2 || i > 4) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incorrect padding"));
}
hold[j] = 64;
} else {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid character"));
}
}
in += 4;
vstr_init(&vstr, (bufinfo.len / 4) * 3 + 1); // Potentially over-allocate
byte *out = (byte *)vstr.buf;
*out++ = (hold[0]) << 2 | (hold[1]) >> 4;
if (hold[2] != 64) {
*out++ = (hold[1] & 0x0F) << 4 | hold[2] >> 2;
if (hold[3] != 64) {
*out++ = (hold[2] & 0x03) << 6 | hold[3];
uint shift = 0;
int nbits = 0; // Number of meaningful bits in shift
bool hadpad = false; // Had a pad character since last valid character
for (size_t i = 0; i < bufinfo.len; i++) {
if (in[i] == '=') {
if ((nbits == 2) || ((nbits == 4) && hadpad)) {
nbits = 0;
break;
}
hadpad = true;
}
int sextet = mod_binascii_sextet(in[i]);
if (sextet == -1) {
continue;
}
hadpad = false;
shift = (shift << 6) | sextet;
nbits += 6;
if (nbits >= 8) {
nbits -= 8;
out[vstr.len++] = (shift >> nbits) & 0xFF;
}
}
if (nbits) {
mp_raise_ValueError("incorrect padding");
}
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_a2b_base64_obj, mod_binascii_a2b_base64);
@ -184,7 +191,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
*out++ = (in[0] & 0x03) << 4;
*out++ = 64;
}
*out++ = 64;
*out = 64;
}
// Second pass, we convert number base 64 values to actual base64 ascii encoding
@ -211,6 +218,8 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_b2a_base64_obj, mod_binascii_b2a_base64);
#if MICROPY_PY_UBINASCII_CRC32
#include "uzlib/tinf.h"
mp_obj_t mod_binascii_crc32(size_t n_args, const mp_obj_t *args) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);

View File

@ -28,7 +28,6 @@
#include <string.h>
#include <stdint.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/objtuple.h"
#include "py/binary.h"
@ -118,7 +117,7 @@ typedef struct _mp_obj_uctypes_struct_t {
} mp_obj_uctypes_struct_t;
STATIC NORETURN void syntax_error(void) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "syntax error in uctypes descriptor"));
mp_raise_TypeError("syntax error in uctypes descriptor");
}
STATIC mp_obj_t uctypes_struct_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
@ -215,7 +214,7 @@ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_
// but scalar structure field is lowered into native Python int, so all
// type info is lost. So, we cannot say if it's scalar type description,
// or such lowered scalar.
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Cannot unambiguously get sizeof scalar"));
mp_raise_TypeError("Cannot unambiguously get sizeof scalar");
}
syntax_error();
}
@ -393,7 +392,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set
// TODO: Support at least OrderedDict in addition
if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "struct: no fields"));
mp_raise_TypeError("struct: no fields");
}
mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr));
@ -526,7 +525,7 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_ob
} else {
// load / store
if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "struct: cannot index"));
mp_raise_TypeError("struct: cannot index");
}
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc);

View File

@ -27,7 +27,6 @@
#include <assert.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#if MICROPY_PY_UHASHLIB

View File

@ -24,9 +24,7 @@
* THE SOFTWARE.
*/
#include "py/nlr.h"
#include "py/objlist.h"
#include "py/runtime0.h"
#include "py/runtime.h"
#if MICROPY_PY_UHEAPQ
@ -35,7 +33,7 @@
STATIC mp_obj_list_t *get_heap(mp_obj_t heap_in) {
if (!MP_OBJ_IS_TYPE(heap_in, &mp_type_list)) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "heap must be a list"));
mp_raise_TypeError("heap must be a list");
}
return MP_OBJ_TO_PTR(heap_in);
}

View File

@ -26,7 +26,6 @@
#include <stdio.h>
#include "py/nlr.h"
#include "py/objlist.h"
#include "py/objstringio.h"
#include "py/parsenum.h"
@ -269,7 +268,7 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
return stack_top;
fail:
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "syntax error in JSON"));
mp_raise_ValueError("syntax error in JSON");
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load);

View File

@ -27,7 +27,6 @@
#include <assert.h>
#include <string.h>
//#include "py/nlr.h"
#include "py/runtime.h"
#if MICROPY_PY_URANDOM

View File

@ -28,13 +28,15 @@
#include <assert.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/binary.h"
#include "py/objstr.h"
#include "py/stackctrl.h"
#if MICROPY_PY_URE
#define re1_5_stack_chk() MP_STACK_CHECK()
#include "re1.5/re1.5.h"
#define FLAG_DEBUG 0x1000
@ -156,7 +158,7 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) {
mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, caps[0] - subj.begin);
mp_obj_list_append(retval, s);
if (self->re.sub > 0) {
mp_not_implemented("Splitting with sub-captures");
mp_raise_NotImplementedError("Splitting with sub-captures");
}
subj.begin = caps[1];
if (maxsplit > 0 && --maxsplit == 0) {
@ -200,7 +202,7 @@ STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) {
int error = re1_5_compilecode(&o->re, re_str);
if (error != 0) {
error:
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Error in regex"));
mp_raise_ValueError("Error in regex");
}
if (flags & FLAG_DEBUG) {
re1_5_dumpcode(&o->re);

View File

@ -27,7 +27,6 @@
#include <stdio.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/stream.h"
@ -153,7 +152,7 @@ STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
// Currently supports only blocking mode
(void)self_in;
if (!mp_obj_is_true(flag_in)) {
mp_not_implemented("");
mp_raise_NotImplementedError("");
}
return mp_const_none;
}

View File

@ -31,7 +31,6 @@
#include <string.h>
#include <errno.h> // needed because mp_is_nonblocking_error uses system error codes
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/stream.h"
@ -66,7 +65,7 @@ struct ssl_args {
STATIC const mp_obj_type_t ussl_socket_type;
static void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str) {
void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str) {
printf("DBG:%s:%04d: %s\n", file, line, str);
}
@ -122,8 +121,10 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
mbedtls_x509_crt_init(&o->cert);
mbedtls_pk_init(&o->pkey);
mbedtls_ctr_drbg_init(&o->ctr_drbg);
#ifdef MBEDTLS_DEBUG_C
// Debug level (0-4)
mbedtls_debug_set_threshold(0);
#endif
mbedtls_entropy_init(&o->entropy);
const byte seed[] = "upy";
@ -143,7 +144,9 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_NONE);
mbedtls_ssl_conf_rng(&o->conf, mbedtls_ctr_drbg_random, &o->ctr_drbg);
#ifdef MBEDTLS_DEBUG_C
mbedtls_ssl_conf_dbg(&o->conf, mbedtls_debug, NULL);
#endif
ret = mbedtls_ssl_setup(&o->ssl, &o->conf);
if (ret != 0) {
@ -189,6 +192,16 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
return o;
}
STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) {
mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
if (!mp_obj_is_true(binary_form)) {
mp_raise_NotImplementedError(NULL);
}
const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert);
STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
@ -259,6 +272,7 @@ STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
{ MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&socket_close_obj) },
{ MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) },
};
STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);

View File

@ -27,9 +27,7 @@
#include <string.h>
#include "py/nlr.h"
#include "py/objlist.h"
#include "py/runtime0.h"
#include "py/runtime.h"
#include "py/smallint.h"
@ -189,7 +187,7 @@ STATIC mp_obj_t mod_utimeq_dump(mp_obj_t heap_in) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_dump_obj, mod_utimeq_dump);
#endif
STATIC mp_obj_t utimeq_unary_op(mp_uint_t op, mp_obj_t self_in) {
STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_utimeq_t *self = MP_OBJ_TO_PTR(self_in);
switch (op) {
case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0);

View File

@ -27,7 +27,6 @@
#include <stdio.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "py/mperrno.h"
@ -92,7 +91,7 @@ STATIC mp_obj_t decompio_make_new(const mp_obj_type_t *type, size_t n_args, size
dict_opt = uzlib_zlib_parse_header(&o->decomp);
if (dict_opt < 0) {
header_error:
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "compression header"));
mp_raise_ValueError("compression header");
}
dict_sz = 1 << dict_opt;
} else {

View File

@ -28,8 +28,6 @@
#include <stdint.h>
#include <string.h>
#include "py/nlr.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "py/builtin.h"

View File

@ -28,8 +28,6 @@
#include <stdint.h>
#include <string.h>
#include "py/nlr.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "extmod/modwebsocket.h"

View File

@ -55,7 +55,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode)
for (cnt = 0; *re != ']'; re++, cnt++) {
if (!*re) return NULL;
EMIT(PC++, *re);
if (re[1] == '-') {
if (re[1] == '-' && re[2] != ']') {
re += 2;
}
EMIT(PC++, *re);

View File

@ -48,6 +48,9 @@ void printre(Regexp*);
#ifndef re1_5_fatal
void re1_5_fatal(char*);
#endif
#ifndef re1_5_stack_chk
#define re1_5_stack_chk()
#endif
void *mal(int);
struct Prog

View File

@ -9,7 +9,9 @@ recursiveloop(char *pc, const char *sp, Subject *input, const char **subp, int n
{
const char *old;
int off;
re1_5_stack_chk();
for(;;) {
if(inst_is_consumer(*pc)) {
// If we need to match a character, but there's none left, it's fail

View File

@ -27,7 +27,6 @@
#include <string.h>
#include "py/mpconfig.h"
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/objtuple.h"
#include "py/objarray.h"
@ -68,7 +67,7 @@ void mp_uos_dupterm_tx_strn(const char *str, size_t len) {
}
}
STATIC mp_obj_t mp_uos_dupterm(mp_uint_t n_args, const mp_obj_t *args) {
STATIC mp_obj_t mp_uos_dupterm(size_t n_args, const mp_obj_t *args) {
if (n_args == 0) {
if (MP_STATE_PORT(term_obj) == MP_OBJ_NULL) {
return mp_const_none;

View File

@ -27,7 +27,6 @@
#include <stdint.h>
#include <string.h>
#include "py/runtime0.h"
#include "py/runtime.h"
#include "py/objstr.h"
#include "py/mperrno.h"

View File

@ -33,7 +33,6 @@
#endif
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/mperrno.h"
#include "lib/oofatfs/ff.h"
@ -243,7 +242,7 @@ STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) {
t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink
t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid
t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid
t->items[6] = MP_OBJ_NEW_SMALL_INT(fno.fsize); // st_size
t->items[6] = mp_obj_new_int_from_uint(fno.fsize); // st_size
t->items[7] = MP_OBJ_NEW_SMALL_INT(seconds); // st_atime
t->items[8] = MP_OBJ_NEW_SMALL_INT(seconds); // st_mtime
t->items[9] = MP_OBJ_NEW_SMALL_INT(seconds); // st_ctime

View File

@ -29,7 +29,6 @@
#include <stdio.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "py/mperrno.h"

View File

@ -28,7 +28,6 @@
#if MICROPY_VFS_FAT
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "lib/oofatfs/ff.h"
#include "extmod/vfs_fat.h"

@ -1 +1 @@
Subproject commit dab957dacddcbf6cbc85d42df62e189e4877bb72
Subproject commit 35aaec4418ad78628a3b935885dd189d41ce779b

View File

@ -3,5 +3,5 @@
NORETURN void abort_(void);
NORETURN void abort_(void) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "abort() called"));
mp_raise_msg(&mp_type_RuntimeError, "abort() called");
}

View File

@ -61,7 +61,12 @@ float log2f(float x) { return logf(x) / (float)_M_LN2; }
static const float _M_LN10 = 2.30258509299404; // 0x40135d8e
float log10f(float x) { return logf(x) / (float)_M_LN10; }
float tanhf(float x) { return sinhf(x) / coshf(x); }
float tanhf(float x) {
if (isinf(x)) {
return copysignf(1, x);
}
return sinhf(x) / coshf(x);
}
/*****************************************************************************/
/*****************************************************************************/

View File

@ -29,8 +29,7 @@
#include <stdio.h>
#include <string.h>
#include "py/obj.h"
#include "py/nlr.h"
#include "py/runtime.h"
#include "lib/netutils/netutils.h"
// Takes an array with a raw IPv4 address and returns something like '192.168.0.1'.
@ -80,7 +79,7 @@ void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian
} else if (i > 0 && s < s_top && *s == '.') {
s++;
} else {
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid arguments"));
mp_raise_ValueError("invalid arguments");
}
}
}

1
lib/stm32lib Submodule

@ -0,0 +1 @@
Subproject commit d2bcfda543d3b99361e44112aca929225bdcc07f

View File

@ -29,7 +29,6 @@
#include <stdint.h>
#include <string.h>
#include "py/nlr.h"
#include "py/compile.h"
#include "py/runtime.h"
#include "py/repl.h"

View File

@ -23,10 +23,10 @@ QSTR_DEFS = qstrdefsport.h
UNAME_S := $(shell uname -s)
# include py core make definitions
include ../py/py.mk
include $(TOP)/py/py.mk
INC += -I.
INC += -I..
INC += -I$(TOP)
INC += -I$(BUILD)
# compiler settings
@ -65,10 +65,10 @@ SRC_C = \
# Add fmode when compiling with mingw gcc
COMPILER_TARGET := $(shell $(CC) -dumpmachine)
ifneq (,$(findstring mingw,$(COMPILER_TARGET)))
SRC_C += windows/fmode.c
SRC_C += ports/windows/fmode.c
endif
OBJ = $(PY_O)
OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o))
include ../py/mkrules.mk
include $(TOP)/py/mkrules.mk

View File

@ -29,14 +29,13 @@
#include <stdlib.h>
#include <unistd.h>
#include "py/mpstate.h"
#include "py/compile.h"
#include "py/persistentcode.h"
#include "py/runtime.h"
#include "py/gc.h"
#include "py/stackctrl.h"
#ifdef _WIN32
#include "windows/fmode.h"
#include "ports/windows/fmode.h"
#endif
// Command line options, with their defaults

View File

@ -1,15 +1,15 @@
include ../py/mkenv.mk
include ../../py/mkenv.mk
# qstr definitions (must come before including py.mk)
QSTR_DEFS = qstrdefsport.h
# include py core make definitions
include ../py/py.mk
include $(TOP)/py/py.mk
CROSS_COMPILE = arm-none-eabi-
INC += -I.
INC += -I..
INC += -I$(TOP)
INC += -I$(BUILD)
CFLAGS_CORTEX_M4 = -mthumb -mtune=cortex-m4 -mabi=aapcs-linux -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -Wdouble-promotion
@ -45,4 +45,4 @@ $(BUILD)/firmware.elf: $(OBJ)
$(Q)$(LD) $(LDFLAGS) -o $@ $^ $(LIBS)
$(Q)$(SIZE) $@
include ../py/mkrules.mk
include $(TOP)/py/mkrules.mk

View File

@ -2,7 +2,6 @@
#include <stdio.h>
#include <string.h>
#include "py/nlr.h"
#include "py/compile.h"
#include "py/runtime.h"
#include "py/repl.h"

View File

@ -60,7 +60,7 @@ typedef long mp_off_t;
// extra built in names to add to the global namespace
#define MICROPY_PORT_BUILTINS \
{ MP_OBJ_NEW_QSTR(MP_QSTR_open), (mp_obj_t)&mp_builtin_open_obj },
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&mp_builtin_open_obj) },
// We need to provide a declaration/definition of alloca()
#include <alloca.h>

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