diff options
author | Damien George <damien.p.george@gmail.com> | 2017-08-14 12:15:54 +1000 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2017-08-14 12:15:54 +1000 |
commit | 5e76ea4affd0bd46e67b456496818803010a2d24 (patch) | |
tree | 2be81a889e765b8e24614bcd8bc80c0a4063e2f3 /docs | |
parent | b4078cbbf3354229fc81ecfd26295237d808caa9 (diff) | |
parent | 1459a8d5c9b29c78da2cf5c7cf3c37ab03b34b8e (diff) | |
download | micropython-5e76ea4affd0bd46e67b456496818803010a2d24.tar.gz micropython-5e76ea4affd0bd46e67b456496818803010a2d24.zip |
Merge tag 'v1.8.2' into parse-bytecode
Thread support, ESP8266 memory improvements, btree module, improved docs
This release brings multi-threading support in the form of the _thread
module, which closely matches the semantics of the corresponding CPython
module. There is support for GIL and non-GIL builds; without the GIL
enabled one must protect concurrent access to mutable Python state at the
Python level using Lock objects. Threading with the GIL is enabled in
the cc3200 port on the WiPy. Threading without the GIL is enabled on the
unix port. The ESP8266 port has support for frozen bytecode (for scripts
in the modules/ subdirectory), as well as optimisations for reduced
memory usage and decreased memory fragmentation. The ESP8266 RTC also
resumes correctly after a deepsleep. An initial "btree" module has been
implemented for database support (unix port only), and the documentation
has been further improved, with pre-built PDF versions of the docs now
available.
py core:
- parse: treat constants that start with underscore as private
- objdict: implemented OrderedDict equality check
- support to build berkeley db 1.85 and "btree" module
- mpconfig.h: MP_NOINLINE is universally useful, move from unix port
- makeqstrdefs.py: remove restriction that source path can't be absolute
- mkrules.mk: define "lib" outside conditional block
- rename __QSTR_EXTRACT flag to NO_QSTR
- objtype: instance: inherit protocol vtable from a base class
- mphal.h: if virtpin API is used, automagically include its header
- objtype: inherit protocol vtable from base class only if it exists
- add MP_STATE_THREAD to hold state specific to a given thread
- add basic _thread module, with ability to start a new thread
- modthread: properly cast concrete exception pointer to an object
- modthread: add stack_size() function
- modthread: add exit() function
- modthread: implement lock object, for creating a mutex
- modthread: add with-context capabilities to lock object
- gc: make memory manager and garbage collector thread safe
- modthread: satisfy unused-args warning
- gc: fix 2 cases of concurrent access to ATB and FTB
- modthread: be more careful with root pointers when creating a thread
- modthread: call mp_thread_start/mp_thread_finish around threads
- gc: fix GC+thread bug where ptr gets lost because it's not computed
- make interning of qstrs thread safe
- implement a simple global interpreter lock (GIL)
- don't use gc or qstr mutex when the GIL is enabled, there is no need
- modthread: make Lock objects work when GIL is enabled
- mpthread.h: move GIL macros outside MICROPY_PY_THREAD block
- modthread: allow to properly set the stack limit of a thread
- nlrthumb: convert NLR thumb funcs from asm to C with inline-asm
- nlrsetjmp: update to take into account new location of nlr_top
- mpthread: include mpstate.h when defining GIL macros
- gc: be sure to count last allocated block at heap end in stats
- gc: calculate (and report) maximum contiguous free block size
- builtinimport: disable "imported as namespace package" warning
- mpconfig.h: mention MICROPY_PY_BTREE config option
- objarray: split out header to allow direct access to object
- rename mp_obj_type_t::stream_p to "protocol"
extmod:
- modbtree: initial implementation of "btree" module based on BerkeleyDB
- modbtree: handle default value and error check
- modbtree: implement .items() iterator
- modbtree: actually implement end key support for .items()
- modbtree: items(): Implement "end key inclusive" flag
- modbtree: items(): Implement DESC flag
- modbtree: __getitem__() should raise KeyError for non-existing key
- modbtree: open(): Support "in-memory" database with filename=None
- machine_pinbase: implementation of PinBase class
- machine_pinbase: fix nanbox build
- modlwip: store a chain of incoming pbufs, instead of only one
- modbtree: implement keys(), values(), items() iterators
- modbtree: cleverly implement "for key in btree:" syntax
- modwebsocket: add readinto() method
- modwebrepl: add readinto() method
- modbtree: fix unused argument warning
- modbtree: fixes for nanbox build
- moduos_dupterm: reserve buffer bytearray object for dupterm
- moduos_dupterm: reuse dupterm_arr_obj for write operations
lib:
- berkeley-db-1.xx: add Berkeley DB 1.85 as a submodule
- berkeley-db-1.xx: update to upstream which builds for uPy
- fatfs/option/ccsbcs: follow uPy optional features model
- libm: format code to pass gcc v6.1.1 warning
- libm: remove unused definition of "one"
drivers:
- display/ssd1306: add width arg and support 64px wide displays
tests:
- recursive_iternext: clang/Linux is even more stack-frugal than MacOS
- bench: add testcase to compare bytes(N) vs b"\0" * N
- add testcase for OrderedDict equality
- add a testcase for machine.PinBase class
- extmod: add "btree" module test
- btree1: add testcase for iterating btree object directly
- add tests for _thread module
- add 3 more tests for _thread module
- thread: remove need to sleep to wait for completion in some tests
- thread: add tests for running GC within a thread, and heap stress
- thread: rename thread_stress_XXX.py to stress_XXX.py
- thread: add tests that mutate shared objects
- thread: add test for concurrent interning of strings
- thread: add test for concurrent mutating of user instance
- thread: make stack-size test run correctly and reliable on uPy
- thread: make sure that thread tests don't rely on floating point
- thread: allow thread_sleep1 to run without floating point
- thread: allow some tests to run on ports with not much heap
- meminfo: update for addition of "max free sz" output
- run-tests: If running thread tests on unix, don't run mutate ones
unix port:
- unbreak "minimal" target by disabling FatFs
- mpconfigport_minimal.h: clearly mark where user-define config ends
- deprecate support for GNU Readline (MICROPY_USE_READLINE=2)
- time to build with --gc-sections
- move "utime" module config to C level instead of make level
- Makefile: libffi: Build with -Os
- alloc: add option to use uPy's alloc-exec implementation even for libffi
- alloc: make coverage build and its overzealous warnings happy
- disable FatFs VFS for normal build, keep enabled for coverage
- modmachine: include PinBase class
- modmachine: enable time_pulse_us() function
- fix Makefile to handle gc-sections linker flags on Mac OS
- add basic thread support using pthreads
- file: if write syscall returns because of EINTR then try again
- implement garbage collection with threading
- mpthreadport: use SA_SIGINFO for GC signal handler
- gccollect: provide declaration of exported function
- mpthreadport: suppress compiler warning about unused arguments
- modtime: release the GIL when sleeping
- enable btree module
- Makefile: make "minimal" build be minimal again
- mpconfigport_minimal.h: allow to print a string within 1KB of heap
- main: error out on unknown value of suffix in -X heapsize= option
- main: improve help for -X options a bit
- main: when preparing sys.path, allocate exact strings on uPy heap
- disable the GIL to improve performance of non-thread code
windows port:
- follow unix port changes regarding "utime" module
- msvc: include machine_pinbase.c in build and enable umachine module
stmhal port:
- add board definition files for Olimex STM32-E407
- port of f4 hal commit 1d7fb82 to l4 hal (SD card modifications)
- correct DMA to allow SD card on L4 MCUs
- enable SD card on L4 MCUs
cc3200 port:
- update FreeRTOS to v9.0.0
- define our own FreeRTOS heap so it can go in a special segment
- add basic threading capabilities
- fix call to new exception to be _msg instead of _arg1
- use xTaskCreateStatic instead of osi_TaskCreate
- mpthreadport: make mutex statically allocated
- mpthreadport: properly initialise the main thread's data
- gccollect: use MP_STATE_THREAD(stack_top) to get top of stack
- mpthreadport: scan more root pointers from thread data
- mpthreadport: move mem alloc outside the thread_mutex lock
- enable the GIL
- in FreeRTOSConfig.h, comment on configSUPPORT_STATIC_ALLOCATION
- remove .boot section attribute from osi_TaskCreate function
- start the simplelink spawn task using the static task creator
- shrink the FreeRTOS heap and place TCB+stack in freed location
- allow to compile bootloader with threading enabled
- remove obsolete singleton heart-beat object
teensy port:
- update the README with OSX specific information and tips
esp8266 port:
- modnetwork: use struct bss_info::ssid_len for ESSID length
- let RTC work correctly after deepsleep
- switch floating-point arith routines to BootROM
- Makefile: enable --verify option for esptool.py write_flash
- use RTC to set date & time stamps for files
- main.c: clear the command line history when (re)booting
- enable frozen bytecode, with scripts in modules/ subdir
- README: describe how to build mpy-cross
- websocket_helper.py: avoid extra string allocations
- websocket_helper.py: fix typo in debug output
- modpybuart: allow setting baudrate and other params
- explicitly collect garbage in bootstrap scripts
- switch webrepl_setup to use frozen bytecode
- switch webrepl to use frozen bytecode
- README: promote from "highly experimental" to "experimental"
- main: init recently added dupterm_arr_obj port state var
- esp_mphal: call_dupterm_read: Use readinto() method
- esp_mphal: properly handle dupterm EOF after switching to readinto()
qemu-arm port:
- disable gcc LTO option for nlrthumb.c
docs:
- esp8266/tutorial/network_basics: minor typo fix, ap becomes ap_if
- add link to PDF version of docs in sidebar
- library/network: wipy: fix literal block indentation
- esp.socket: remove unused file
- ure: typo fix
- usocket: there must be empty line after .only::
- library/machine.Pin: mention GPIO and cross-link .value() function
- machine.*: add "currentmodule:: machine" directive
- pyb.*: add "currentmodule:: pyb" directive
- machine.Pin: remove explicit target
- machine.UART: cleanup pyboard section
- machine.*: use proper class case in method headers
- machine.Pin: add class designator to all constants
- pyb.CAN: mark CAN.initfilterbanks() as classmethod explicitly
- pyb.Pin: af_list() is a normal method, not a class method
- pyb.ExtInt,pyb.Pin: mark up class methods as such
- pyb.*: use proper class case in method headers
- pyb.Pin: sort .af() and .af_list() methods together
- builtins: enumerate all builtin functions implemented
- library/index: add builtins.rst
- machine.Pin: disambiguate object call method
- machine*: remove explicit targets and "machine." prefixes on classes
- uctypes: improve documentation
- sys: detailed description of print_exception() diff from traceback module
- add sphinx_selective_exclude extension suite
- conf.py: active sphinx_selective_exclude extensions
- rebuild docs from scratch, as required for proper only:: handling
- select: add an article
- sys: print_exception: Fixes/clarifications
- conf.py: exclude cmath from modindex for wipy
- library: fix typo in docs for usocket.listen()
examples:
- unix/ffi_example.py: update for current "ffi" module API
- unix/ffi_example.py: remove TODO, make output more clear
Diffstat (limited to 'docs')
44 files changed, 829 insertions, 383 deletions
diff --git a/docs/Makefile b/docs/Makefile index 9756fab286..d81d11eeb2 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -6,6 +6,9 @@ SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build/$(MICROPY_PORT) +# Run "make FORCE= ..." to avoid rebuilding from scratch (and risk +# producing incorrect docs). +FORCE = -E # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) @@ -50,7 +53,7 @@ clean: rm -rf $(BUILDDIR)/* html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + $(SPHINXBUILD) $(FORCE) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." @@ -111,7 +114,7 @@ latex: "(use \`make latexpdf' here to do that automatically)." latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + $(SPHINXBUILD) $(FORCE) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." diff --git a/docs/conf.py b/docs/conf.py index 6faeb60406..ba69cf7f7a 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,7 +19,7 @@ import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('.')) # Work out the port to generate the docs for from collections import OrderedDict @@ -48,6 +48,9 @@ html_context = { (ver, url_pattern % (ver, micropy_port)) for ver in micropy_all_versions ], + 'downloads':[ + ('PDF', url_pattern % (micropy_version, 'micropython-%s.pdf' % micropy_port)), + ], } @@ -68,6 +71,9 @@ extensions = [ 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', + 'sphinx_selective_exclude.modindex_exclude', + 'sphinx_selective_exclude.eager_only', + 'sphinx_selective_exclude.search_auto_exclude', ] # Add any paths that contain templates here, relative to this directory. @@ -93,7 +99,7 @@ copyright = '2014-2016, Damien P. George and contributors' # The short X.Y version. version = '1.8' # The full version, including alpha/beta/rc tags. -release = '1.8.1' +release = '1.8.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -313,6 +319,21 @@ intersphinx_mapping = {'http://docs.python.org/': None} # Append the other ports' specific folders/files to the exclude pattern exclude_patterns.extend([port + '*' for port in ports if port != micropy_port]) -# Exclude pyb module if the port is the WiPy -if micropy_port == 'wipy': - exclude_patterns.append('library/pyb*') + +modules_port_specific = { + 'pyboard': ['pyb'], + 'wipy': ['wipy'], + 'esp8266': ['esp'], +} + +modindex_exclude = [] + +for p, l in modules_port_specific.items(): + if p != micropy_port: + modindex_exclude += l + +# Exclude extra modules per port +modindex_exclude += { + 'esp8266': ['cmath', 'select'], + 'wipy': ['cmath'], +}.get(micropy_port, []) diff --git a/docs/esp8266/tutorial/network_basics.rst b/docs/esp8266/tutorial/network_basics.rst index 42aed56642..95d8cba4f9 100644 --- a/docs/esp8266/tutorial/network_basics.rst +++ b/docs/esp8266/tutorial/network_basics.rst @@ -19,7 +19,7 @@ You can check if the interfaces are active by:: You can also check the network settings of the interface by:: - >>> ap.ifconfig() + >>> ap_if.ifconfig() ('192.168.4.1', '255.255.255.0', '192.168.4.1', '8.8.8.8') The returned values are: IP address, netmask, gateway, DNS. diff --git a/docs/library/builtins.rst b/docs/library/builtins.rst new file mode 100644 index 0000000000..d99eadce3e --- /dev/null +++ b/docs/library/builtins.rst @@ -0,0 +1,127 @@ +Builtin Functions +================= + +All builtin functions are described here. They are alse available via +``builtins`` module. + +.. function:: abs() + +.. function:: all() + +.. function:: any() + +.. function:: bin() + +.. class:: bool() + +.. class:: bytearray() + +.. class:: bytes() + +.. function:: callable() + +.. function:: chr() + +.. function:: classmethod() + +.. function:: compile() + +.. class:: complex() + +.. class:: dict() + +.. function:: dir() + +.. function:: divmod() + +.. function:: enumerate() + +.. function:: eval() + +.. function:: exec() + +.. function:: filter() + +.. class:: float() + +.. class:: frozenset() + +.. function:: getattr() + +.. function:: globals() + +.. function:: hasattr() + +.. function:: hash() + +.. function:: hex() + +.. function:: id() + +.. function:: input() + +.. class:: int() + +.. function:: isinstance() + +.. function:: issubclass() + +.. function:: iter() + +.. function:: len() + +.. class:: list() + +.. function:: locals() + +.. function:: map() + +.. function:: max() + +.. class:: memoryview() + +.. function:: min() + +.. function:: next() + +.. class:: object() + +.. function:: oct() + +.. function:: open() + +.. function:: ord() + +.. function:: pow() + +.. function:: print() + +.. function:: property() + +.. function:: range() + +.. function:: repr() + +.. function:: reversed() + +.. function:: round() + +.. class:: set() + +.. function:: setattr() + +.. function:: sorted() + +.. function:: staticmethod() + +.. class:: str() + +.. function:: sum() + +.. function:: super() + +.. class:: tuple() + +.. function:: type() + +.. function:: zip() diff --git a/docs/library/esp.socket.rst b/docs/library/esp.socket.rst deleted file mode 100644 index 4f5234a154..0000000000 --- a/docs/library/esp.socket.rst +++ /dev/null @@ -1,82 +0,0 @@ -class socket -- network socket -============================== - -``socket`` is an object that represents a network socket. Example usage:: - - socket = esp.socket() - socket.onrecv(print) - socket.connect(('207.58.139.247', 80)) - socket.send('GET /testwifi/index.html HTTP/1.0\r\n\r\n') - -Constructors ------------- - -.. class:: esp.socket() - - Create and return a socket object. - - -TCP Methods ------------ - -.. method:: socket.connect(addr) - - Connect to the adress and port specified in the ``addr`` tuple. - -.. method:: socket.close() - - Close the connection. - -.. method:: socket.accept() - - Accept a single connection from the connection queue. - -.. method:: socket.listen(backlog) - - Start listening for incoming connections. - - Note: Only one socket can be listening for connections at a time. - -.. method:: socket.bind(addr) - - Bind the socket to the address and port specified by the ``addr`` tuple. - -.. method:: socket.send(buf) - - Send the bytes from ``buf``. - -.. method:: socket.recv() - - Receive and return bytes from the socket. - - -UDP Methods ------------ - -.. method:: socket.sendto(data, addr) - - Placeholder for UDP support, not implemented yet. - -.. method:: socket.recvfrom(addr) - - Placeholder for UDP support, not implemented yet. - - -Callback Setter Methods ------------------------ - -.. method:: onconnect(lambda):: - - When connection is established, call the callback ``lambda``. - -.. method:: onrecv(lambda):: - - When data is received, call the callback ``lambda``. - -.. method:: onsent(lamda):: - - What data is finished sending, call the callback ``lambda``. - -.. method:: ondisconnect(lambda):: - - Call the callback ``lambda`` when the connection is closed. diff --git a/docs/library/index.rst b/docs/library/index.rst index e3d6e31575..9a105697b7 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -51,6 +51,7 @@ library. .. toctree:: :maxdepth: 1 + builtins.rst cmath.rst gc.rst math.rst @@ -74,6 +75,7 @@ library. .. toctree:: :maxdepth: 1 + builtins.rst cmath.rst gc.rst math.rst @@ -97,6 +99,7 @@ library. .. toctree:: :maxdepth: 1 + builtins.rst gc.rst select.rst sys.rst @@ -113,6 +116,7 @@ library. .. toctree:: :maxdepth: 1 + builtins.rst gc.rst math.rst sys.rst diff --git a/docs/library/machine.ADC.rst b/docs/library/machine.ADC.rst index 309d070b1b..2752878ff3 100644 --- a/docs/library/machine.ADC.rst +++ b/docs/library/machine.ADC.rst @@ -1,4 +1,4 @@ -.. _machine.ADC: +.. currentmodule:: machine class ADC -- analog to digital conversion ========================================= @@ -14,7 +14,7 @@ Usage:: Constructors ------------ -.. class:: machine.ADC(id=0, \*, bits=12) +.. class:: ADC(id=0, \*, bits=12) Create an ADC object associated with the given pin. This allows you to then read analog values on that pin. @@ -31,7 +31,7 @@ Constructors Methods ------- -.. method:: adc.channel(id, \*, pin) +.. method:: ADC.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 @@ -42,11 +42,11 @@ Methods apin = adc.channel(pin='GP3') apin = adc.channel(id=1, pin='GP3') -.. method:: adc.init() +.. method:: ADC.init() Enable the ADC block. -.. method:: adc.deinit() +.. method:: ADC.deinit() Disable the ADC block. diff --git a/docs/library/machine.I2C.rst b/docs/library/machine.I2C.rst index a7e90ca39b..b3bfa68f07 100644 --- a/docs/library/machine.I2C.rst +++ b/docs/library/machine.I2C.rst @@ -1,4 +1,4 @@ -.. _machine.I2C: +.. currentmodule:: machine class I2C -- a two-wire serial protocol ======================================= @@ -44,14 +44,14 @@ Constructors .. only:: port_wipy - .. class:: machine.I2C(bus, ...) + .. class:: I2C(bus, ...) Construct an I2C object on the given bus. `bus` can only be 0. If the bus is not given, the default one will be selected (0). .. only:: port_esp8266 - .. class:: machine.I2C(scl, sda, \*, freq=400000) + .. class:: I2C(scl, sda, \*, freq=400000) Construct and return a new I2C object. See the init method below for a description of the arguments. @@ -61,7 +61,7 @@ General Methods .. only:: port_wipy - .. method:: i2c.init(mode, \*, baudrate=100000, pins=(SDA, SCL)) + .. method:: I2C.init(mode, \*, baudrate=100000, pins=(SDA, SCL)) Initialise the I2C bus with the given parameters: @@ -71,7 +71,7 @@ General Methods .. only:: port_esp8266 - .. method:: i2c.init(scl, sda, \*, freq=400000) + .. method:: I2C.init(scl, sda, \*, freq=400000) Initialise the I2C bus with the given arguments: @@ -79,13 +79,13 @@ General Methods - `sda` is a pin object for the SDA line - `freq` is the SCL clock rate -.. method:: i2c.deinit() +.. method:: I2C.deinit() Turn off the I2C bus. Availability: WiPy. -.. method:: i2c.scan() +.. method:: I2C.scan() Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of those that respond. A device responds if it pulls the SDA line low after @@ -100,19 +100,19 @@ 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. -.. method:: i2c.start() +.. method:: I2C.start() Send a start bit on the bus (SDA transitions to low while SCL is high). Availability: ESP8266. -.. method:: i2c.stop() +.. method:: I2C.stop() Send a stop bit on the bus (SDA transitions to high while SCL is high). Availability: ESP8266. -.. method:: i2c.readinto(buf) +.. method:: I2C.readinto(buf) 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 @@ -121,7 +121,7 @@ control over the bus, otherwise the standard methods (see below) can be used. Availability: ESP8266. -.. method:: i2c.write(buf) +.. method:: I2C.write(buf) Write all the bytes from `buf` to the bus. Checks that an ACK is received after each byte and raises an OSError if not. @@ -134,12 +134,12 @@ 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) +.. method:: I2C.readfrom(addr, nbytes) Read `nbytes` from the slave specified by `addr`. Returns a `bytes` object with the data read. -.. method:: i2c.readfrom_into(addr, buf) +.. method:: I2C.readfrom_into(addr, buf) Read into `buf` from the slave specified by `addr`. The number of bytes read will be the length of `buf`. @@ -147,7 +147,7 @@ operations that target a given slave device. On WiPy the return value is the number of bytes read. Otherwise the return value is `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`. @@ -166,7 +166,7 @@ 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`. @@ -174,7 +174,7 @@ methods are convenience functions to communicate with such devices. this argument is not recognised and the address size is always 8 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 @@ -185,7 +185,7 @@ methods are convenience functions to communicate with such devices. On WiPy the return value is the number of bytes read. Otherwise the return value is `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`. diff --git a/docs/library/machine.Pin.rst b/docs/library/machine.Pin.rst index a2e97c87c2..fdada2f383 100644 --- a/docs/library/machine.Pin.rst +++ b/docs/library/machine.Pin.rst @@ -1,9 +1,10 @@ -.. _machine.Pin: +.. currentmodule:: machine class Pin -- control I/O pins ============================= -A pin is the basic object to control I/O pins. It has methods to set +A pin is the basic object to control I/O pins (also known as GPIO - +general-purpose input/output). It has methods to set the mode of the pin (input, output, etc) and methods to get and set the digital logic level. For analog control of a pin, see the ADC class. @@ -57,17 +58,17 @@ Usage Model: Constructors ------------ -.. class:: machine.Pin(id, ...) +.. class:: Pin(id, ...) Create a new Pin object associated with the id. If additional arguments are given, - they are used to initialise the pin. See :meth:`pin.init`. + they are used to initialise the pin. See :meth:`Pin.init`. Methods ------- .. only:: port_wipy - .. method:: pin.init(mode, pull, \*, drive, alt) + .. method:: Pin.init(mode, pull, \*, drive, alt) Initialise the pin: @@ -97,13 +98,13 @@ Methods Returns: ``None``. - .. method:: pin.id() + .. method:: Pin.id() Get the pin id. .. only:: port_esp8266 - .. method:: pin.init(mode, pull=None, \*, value) + .. method:: Pin.init(mode, pull=None, \*, value) Initialise the pin: @@ -120,7 +121,7 @@ Methods - if `value` is given then it is the output value to set the pin if it is in output mode. -.. method:: pin.value([value]) +.. method:: Pin.value([value]) Get or set the digital logic level of the pin: @@ -129,12 +130,12 @@ Methods anything that converts to a boolean. If it converts to ``True``, the pin is set high, otherwise it is set low. -.. method:: pin([value]) +.. method:: Pin.__call__([value]) Pin objects are callable. The call method provides a (fast) shortcut to set and get the value of the pin. - See **pin.value** for more details. + See :func:`Pin.value` for more details. -.. method:: pin.alt_list() +.. method:: Pin.alt_list() Returns a list of the alternate functions supported by the pin. List items are a tuple of the form: ``('ALT_FUN_NAME', ALT_FUN_INDEX)`` @@ -143,23 +144,23 @@ Methods .. only:: port_wipy - .. method:: pin.toggle() + .. method:: Pin.toggle() Toggle the value of the pin. - .. method:: pin.mode([mode]) + .. method:: Pin.mode([mode]) Get or set the pin mode. - .. method:: pin.pull([pull]) + .. method:: Pin.pull([pull]) Get or set the pin pull. - .. method:: pin.drive([drive]) + .. method:: Pin.drive([drive]) Get or set the pin drive strength. - .. method:: pin.irq(\*, trigger, priority=1, handler=None, wake=None) + .. method:: Pin.irq(\*, trigger, priority=1, handler=None, wake=None) Create a callback to be triggered when the input level at the pin changes. @@ -193,7 +194,7 @@ Methods .. only:: port_esp8266 - .. method:: pin.irq(\*, trigger, handler=None) + .. method:: Pin.irq(\*, trigger, handler=None) Create a callback to be triggered when the input level at the pin changes. @@ -227,28 +228,28 @@ Constants The following constants are used to configure the pin objects. Note that not all constants are available on all ports. -.. data:: IN - OUT - OPEN_DRAIN - ALT - ALT_OPEN_DRAIN +.. data:: Pin.IN + Pin.OUT + Pin.OPEN_DRAIN + Pin.ALT + Pin.ALT_OPEN_DRAIN Selects the pin mode. -.. data:: PULL_UP - PULL_DOWN +.. data:: Pin.PULL_UP + Pin.PULL_DOWN Selects the whether there is a pull up/down resistor. -.. data:: LOW_POWER - MED_POWER - HIGH_POWER +.. data:: Pin.LOW_POWER + Pin.MED_POWER + Pin.HIGH_POWER Selects the pin drive strength. -.. data:: IRQ_FALLING - IRQ_RISING - IRQ_LOW_LEVEL - IRQ_HIGH_LEVEL +.. data:: Pin.IRQ_FALLING + Pin.IRQ_RISING + Pin.IRQ_LOW_LEVEL + Pin.IRQ_HIGH_LEVEL Selects the IRQ trigger type. diff --git a/docs/library/machine.RTC.rst b/docs/library/machine.RTC.rst index c69e4781a2..b6e98e9d1f 100644 --- a/docs/library/machine.RTC.rst +++ b/docs/library/machine.RTC.rst @@ -1,4 +1,4 @@ -.. _machine.RTC: +.. currentmodule:: machine class RTC -- real time clock ============================ @@ -16,42 +16,42 @@ Example usage:: Constructors ------------ -.. class:: machine.RTC(id=0, ...) +.. class:: RTC(id=0, ...) Create an RTC object. See init for parameters of initialization. Methods ------- -.. method:: rtc.init(datetime) +.. method:: RTC.init(datetime) Initialise the RTC. Datetime is a tuple of the form: ``(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])`` -.. method:: rtc.now() +.. method:: RTC.now() Get get the current datetime tuple. -.. method:: rtc.deinit() +.. method:: RTC.deinit() 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 milllisecond value to program the alarm to current time + time_in_ms in the future, or a datetimetuple. If the time passed is in milliseconds, repeat can be set to ``True`` to make the alarm periodic. -.. method:: rtc.alarm_left(alarm_id=0) +.. method:: RTC.alarm_left(alarm_id=0) Get the number of milliseconds left before the alarm expires. -.. method:: rtc.cancel(alarm_id=0) +.. method:: RTC.cancel(alarm_id=0) 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. diff --git a/docs/library/machine.SD.rst b/docs/library/machine.SD.rst index da60121d07..21c28aa200 100644 --- a/docs/library/machine.SD.rst +++ b/docs/library/machine.SD.rst @@ -1,4 +1,4 @@ -.. _machine.SD: +.. currentmodule:: machine class SD -- secure digital memory card ====================================== @@ -24,18 +24,18 @@ Example usage:: Constructors ------------ -.. class:: machine.SD(id,... ) +.. class:: SD(id,... ) Create a SD card object. See ``init()`` for parameters if initialization. Methods ------- -.. method:: sd.init(id=0, pins=('GP10', 'GP11', 'GP15')) +.. method:: SD.init(id=0, pins=('GP10', 'GP11', 'GP15')) Enable the SD card. In order to initalize the card, give it a 3-tuple: ``(clk_pin, cmd_pin, dat0_pin)``. -.. method:: sd.deinit() +.. method:: SD.deinit() Disable the SD card. diff --git a/docs/library/machine.SPI.rst b/docs/library/machine.SPI.rst index eddd62dbdc..f3c95181dc 100644 --- a/docs/library/machine.SPI.rst +++ b/docs/library/machine.SPI.rst @@ -1,4 +1,4 @@ -.. _machine.SPI: +.. currentmodule:: machine class SPI -- a master-driven serial protocol ============================================ @@ -23,7 +23,7 @@ Constructors .. only:: port_wipy - .. class:: machine.SPI(id, ...) + .. class:: SPI(id, ...) Construct an SPI object on the given bus. ``id`` can be only 0. With no additional parameters, the SPI object is created but not @@ -34,7 +34,7 @@ Constructors Methods ------- -.. method:: spi.init(mode, baudrate=1000000, \*, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, pins=(CLK, MOSI, MISO)) +.. method:: SPI.init(mode, baudrate=1000000, \*, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, pins=(CLK, MOSI, MISO)) Initialise the SPI bus with the given parameters: @@ -47,27 +47,27 @@ Methods - ``firstbit`` can be ``SPI.MSB`` only. - ``pins`` is an optional tupple with the pins to assign to the SPI bus. -.. method:: spi.deinit() +.. method:: SPI.deinit() Turn off the SPI bus. -.. method:: spi.write(buf) +.. method:: SPI.write(buf) Write the data contained in ``buf``. Returns the number of bytes written. -.. method:: spi.read(nbytes, *, write=0x00) +.. method:: SPI.read(nbytes, *, write=0x00) Read the ``nbytes`` while writing the data specified by ``write``. Return the number of bytes read. -.. method:: spi.readinto(buf, *, write=0x00) +.. method:: SPI.readinto(buf, *, write=0x00) Read into the buffer specified by ``buf`` while writing the data specified by ``write``. Return the number of bytes read. -.. method:: spi.write_readinto(write_buf, read_buf) +.. method:: SPI.write_readinto(write_buf, read_buf) Write from ``write_buf`` and read into ``read_buf``. Both buffers must have the same length. diff --git a/docs/library/machine.Timer.rst b/docs/library/machine.Timer.rst index daf63c9b93..344d1ea86e 100644 --- a/docs/library/machine.Timer.rst +++ b/docs/library/machine.Timer.rst @@ -1,4 +1,4 @@ -.. _machine.Timer: +.. currentmodule:: machine class Timer -- control internal timers ====================================== @@ -59,7 +59,7 @@ class Timer -- control internal timers Constructors ------------ -.. class:: machine.Timer(id, ...) +.. class:: Timer(id, ...) .. only:: port_wipy @@ -71,7 +71,7 @@ Methods .. only:: port_wipy - .. method:: timer.init(mode, \*, width=16) + .. method:: Timer.init(mode, \*, width=16) Initialise the timer. Example:: @@ -92,14 +92,14 @@ Methods (or large periods), 32-bit timers should be used. 32-bit mode is only available for ``ONE_SHOT`` AND ``PERIODIC`` modes. -.. method:: timer.deinit() +.. method:: Timer.deinit() Deinitialises the timer. Disables all channels and associated IRQs. Stops the timer, and disables the timer peripheral. .. only:: port_wipy - .. method:: timer.channel(channel, \**, freq, period, polarity=Timer.POSITIVE, duty_cycle=0) + .. method:: Timer.channel(channel, \**, freq, period, polarity=Timer.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). diff --git a/docs/library/machine.UART.rst b/docs/library/machine.UART.rst index 7399b9b6e9..27a8801900 100644 --- a/docs/library/machine.UART.rst +++ b/docs/library/machine.UART.rst @@ -1,4 +1,4 @@ -.. _machine.UART: +.. currentmodule:: machine class UART -- duplex serial communication bus ============================================= @@ -36,7 +36,7 @@ using the standard stream methods:: uart.readinto(buf) # read and store into the given buffer uart.write('abc') # write the 3 characters -.. only:: port_machineoard +.. only:: port_pyboard Individual characters can be read/written using:: @@ -47,9 +47,6 @@ using the standard stream methods:: uart.any() # returns True if any characters waiting - *Note:* The stream functions ``read``, ``write``, etc. are new in MicroPython v1.3.4. - Earlier versions use ``uart.send`` and ``uart.recv``. - .. only:: port_wipy To check if there is anything to be read, use:: @@ -61,7 +58,7 @@ Constructors .. only:: port_wipy - .. class:: machine.UART(bus, ...) + .. class:: UART(bus, ...) Construct a UART object on the given bus. ``bus`` can be 0 or 1. If the bus is not given, the default one will be selected (0) or the selection @@ -72,7 +69,7 @@ Methods .. only:: port_wipy - .. method:: uart.init(baudrate=9600, bits=8, parity=None, stop=1, \*, pins=(TX, RX, RTS, CTS)) + .. method:: UART.init(baudrate=9600, bits=8, parity=None, stop=1, \*, pins=(TX, RX, RTS, CTS)) Initialise the UART bus with the given parameters: @@ -88,28 +85,28 @@ Methods .. only:: not port_esp8266 - .. method:: uart.deinit() + .. method:: UART.deinit() Turn off the UART bus. - .. method:: uart.any() + .. method:: UART.any() Return the number of characters available for reading. -.. method:: uart.read([nbytes]) +.. method:: UART.read([nbytes]) Read characters. If ``nbytes`` is specified then read at most that many bytes. Return value: a bytes object containing the bytes read in. Returns ``None`` on timeout. -.. method:: uart.readall() +.. method:: UART.readall() Read as much data as possible. Return value: a bytes object or ``None`` on timeout. -.. method:: uart.readinto(buf[, nbytes]) +.. 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. @@ -117,13 +114,13 @@ Methods Return value: number of bytes read and stored into ``buf`` or ``None`` on timeout. -.. method:: uart.readline() +.. method:: UART.readline() Read a line, ending in a newline character. Return value: the line read or ``None`` on timeout. -.. method:: uart.write(buf) +.. method:: UART.write(buf) Write the buffer of bytes to the bus. @@ -131,7 +128,7 @@ Methods .. only:: not port_esp8266 - .. method:: uart.sendbreak() + .. method:: UART.sendbreak() Send a break condition on the bus. This drives the bus low for a duration of 13 bits. @@ -139,7 +136,7 @@ Methods .. only:: port_wipy - .. method:: uart.irq(trigger, priority=1, handler=None, wake=machine.IDLE) + .. method:: UART.irq(trigger, priority=1, handler=None, wake=machine.IDLE) Create a callback to be triggered when data is received on the UART. diff --git a/docs/library/machine.WDT.rst b/docs/library/machine.WDT.rst index dca74f70f6..d7c801356e 100644 --- a/docs/library/machine.WDT.rst +++ b/docs/library/machine.WDT.rst @@ -1,4 +1,4 @@ -.. _machine.WDT: +.. currentmodule:: machine class WDT -- watchdog timer =========================== @@ -17,7 +17,7 @@ Example usage:: Constructors ------------ -.. class:: machine.WDT(id=0, timeout=5000) +.. 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 diff --git a/docs/library/network.rst b/docs/library/network.rst index fe4eaa7525..b183ef9a4b 100644 --- a/docs/library/network.rst +++ b/docs/library/network.rst @@ -41,11 +41,11 @@ For example:: Example:: - import network - server = network.Server() - server.deinit() # disable the server - # enable the server again with new settings - server.init(login=('user', 'password'), timeout=600) + import network + server = network.Server() + server.deinit() # disable the server + # enable the server again with new settings + server.init(login=('user', 'password'), timeout=600) Constructors ------------ diff --git a/docs/library/pyb.ADC.rst b/docs/library/pyb.ADC.rst index 30957c4c1a..2ffd4e16f5 100644 --- a/docs/library/pyb.ADC.rst +++ b/docs/library/pyb.ADC.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.ADC: class ADC -- analog to digital conversion @@ -35,12 +36,12 @@ Methods .. only:: port_pyboard - .. method:: adc.read() + .. method:: ADC.read() Read the value on the analog pin and return it. The returned value will be between 0 and 4095. - .. method:: adc.read_timed(buf, timer) + .. method:: ADC.read_timed(buf, timer) Read analog values into ``buf`` at a rate set by the ``timer`` object. diff --git a/docs/library/pyb.Accel.rst b/docs/library/pyb.Accel.rst index fd96ec35f9..2ae357fe70 100644 --- a/docs/library/pyb.Accel.rst +++ b/docs/library/pyb.Accel.rst @@ -1,3 +1,5 @@ +.. currentmodule:: pyb + class Accel -- accelerometer control ==================================== @@ -20,7 +22,7 @@ Constructors Methods ------- -.. method:: accel.filtered_xyz() +.. method:: Accel.filtered_xyz() Get a 3-tuple of filtered x, y and z values. @@ -29,18 +31,18 @@ Methods with the sample from the current call. Returned values are therefore 4 times the size of what they would be from the raw x(), y() and z() calls. -.. method:: accel.tilt() +.. method:: Accel.tilt() Get the tilt register. -.. method:: accel.x() +.. method:: Accel.x() Get the x-axis value. -.. method:: accel.y() +.. method:: Accel.y() Get the y-axis value. -.. method:: accel.z() +.. method:: Accel.z() Get the z-axis value. diff --git a/docs/library/pyb.CAN.rst b/docs/library/pyb.CAN.rst index e5d2b9acb1..9e71f12b06 100644 --- a/docs/library/pyb.CAN.rst +++ b/docs/library/pyb.CAN.rst @@ -1,3 +1,5 @@ +.. currentmodule:: pyb + class CAN -- controller area network communication bus ====================================================== @@ -34,7 +36,7 @@ Constructors Class Methods ------------- -.. method:: CAN.initfilterbanks(nr) +.. classmethod:: CAN.initfilterbanks(nr) Reset and disable all filter banks and assign how many banks should be available for CAN(1). @@ -46,7 +48,7 @@ Class Methods Methods ------- -.. method:: can.init(mode, extframe=False, prescaler=100, \*, sjw=1, bs1=6, bs2=8) +.. method:: CAN.init(mode, extframe=False, prescaler=100, \*, sjw=1, bs1=6, bs2=8) Initialise the CAN bus with the given parameters: @@ -78,11 +80,11 @@ Methods See page 680 of the STM32F405 datasheet for more details. -.. method:: can.deinit() +.. method:: CAN.deinit() Turn off the CAN bus. -.. method:: can.setfilter(bank, mode, fifo, params, \*, rtr) +.. method:: CAN.setfilter(bank, mode, fifo, params, \*, rtr) Configure a filter bank: @@ -124,17 +126,17 @@ Methods |CAN.MASK32 |1 | +-----------+----------------------+ -.. method:: can.clearfilter(bank) +.. method:: CAN.clearfilter(bank) Clear and disables a filter bank: - ``bank`` is the filter bank that is to be cleared. -.. method:: can.any(fifo) +.. method:: CAN.any(fifo) Return ``True`` if any message waiting on the FIFO, else ``False``. -.. method:: can.recv(fifo, \*, timeout=5000) +.. method:: CAN.recv(fifo, \*, timeout=5000) Receive data on the bus: @@ -148,7 +150,7 @@ Methods - The FMI (Filter Match Index) value. - An array containing the data. -.. method:: can.send(data, id, \*, timeout=0, rtr=False) +.. method:: CAN.send(data, id, \*, timeout=0, rtr=False) Send a message on the bus: @@ -168,7 +170,7 @@ Methods Return value: ``None``. -.. method:: can.rxcallback(fifo, fun) +.. method:: CAN.rxcallback(fifo, fun) Register a function to be called when a message is accepted into a empty fifo: diff --git a/docs/library/pyb.DAC.rst b/docs/library/pyb.DAC.rst index 7b5b1a6821..4b9651e27e 100644 --- a/docs/library/pyb.DAC.rst +++ b/docs/library/pyb.DAC.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.DAC: class DAC -- digital to analog conversion @@ -62,32 +63,32 @@ Constructors Methods ------- -.. method:: dac.init(bits=8) +.. method:: DAC.init(bits=8) Reinitialise the DAC. ``bits`` can be 8 or 12. -.. method:: dac.deinit() +.. method:: DAC.deinit() De-initialise the DAC making its pin available for other uses. -.. method:: dac.noise(freq) +.. method:: DAC.noise(freq) Generate a pseudo-random noise signal. A new random sample is written to the DAC output at the given frequency. -.. method:: dac.triangle(freq) +.. method:: DAC.triangle(freq) Generate a triangle wave. The value on the DAC output changes at the given frequency, and the frequence of the repeating triangle wave itself is 2048 times smaller. -.. method:: dac.write(value) +.. method:: DAC.write(value) Direct access to the DAC output. The minimum value is 0. The maximum 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 diff --git a/docs/library/pyb.ExtInt.rst b/docs/library/pyb.ExtInt.rst index 61023ebb38..d8f4d92bb8 100644 --- a/docs/library/pyb.ExtInt.rst +++ b/docs/library/pyb.ExtInt.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.ExtInt: class ExtInt -- configure I/O pins to interrupt on external events @@ -71,7 +72,7 @@ Constructors Class methods ------------- -.. method:: ExtInt.regs() +.. classmethod:: ExtInt.regs() Dump the values of the EXTI registers. @@ -79,20 +80,20 @@ Class methods Methods ------- -.. method:: extint.disable() +.. method:: ExtInt.disable() Disable the interrupt associated with the ExtInt object. This could be useful for debouncing. -.. method:: extint.enable() +.. method:: ExtInt.enable() Enable a disabled interrupt. -.. method:: extint.line() +.. method:: ExtInt.line() Return the line number that the pin is mapped to. -.. method:: extint.swint() +.. method:: ExtInt.swint() Trigger the callback from software. diff --git a/docs/library/pyb.I2C.rst b/docs/library/pyb.I2C.rst index 9d17bb0559..210b4ccf21 100644 --- a/docs/library/pyb.I2C.rst +++ b/docs/library/pyb.I2C.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.I2C: class I2C -- a two-wire serial protocol @@ -85,13 +86,13 @@ Constructors Methods ------- -.. method:: i2c.deinit() +.. method:: I2C.deinit() Turn off the I2C bus. .. only:: port_pyboard - .. method:: i2c.init(mode, \*, addr=0x12, baudrate=400000, gencall=False) + .. method:: I2C.init(mode, \*, addr=0x12, baudrate=400000, gencall=False) Initialise the I2C bus with the given parameters: @@ -100,11 +101,11 @@ Methods - ``baudrate`` is the SCL clock rate (only sensible for a master) - ``gencall`` is whether to support general call mode - .. method:: i2c.is_ready(addr) + .. method:: I2C.is_ready(addr) 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: @@ -117,7 +118,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: @@ -130,7 +131,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: @@ -142,7 +143,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: @@ -152,7 +153,7 @@ Methods Return value: ``None``. -.. method:: i2c.scan() +.. method:: I2C.scan() Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. Only valid when in master mode. diff --git a/docs/library/pyb.LCD.rst b/docs/library/pyb.LCD.rst index 7555b6fb09..83cf890b63 100644 --- a/docs/library/pyb.LCD.rst +++ b/docs/library/pyb.LCD.rst @@ -1,3 +1,5 @@ +.. currentmodule:: pyb + class LCD -- LCD control for the LCD touch-sensor pyskin ======================================================== @@ -47,48 +49,48 @@ Constructors Methods ------- -.. method:: lcd.command(instr_data, buf) +.. method:: LCD.command(instr_data, buf) Send an arbitrary command to the LCD. Pass 0 for ``instr_data`` to send an instruction, otherwise pass 1 to send data. ``buf`` is a buffer with the instructions/data to send. -.. method:: lcd.contrast(value) +.. method:: LCD.contrast(value) Set the contrast of the LCD. Valid values are between 0 and 47. -.. method:: lcd.fill(colour) +.. method:: LCD.fill(colour) Fill the screen with the given colour (0 or 1 for white or black). This method writes to the hidden buffer. Use ``show()`` to show the buffer. -.. method:: lcd.get(x, y) +.. method:: LCD.get(x, y) Get the pixel at the position ``(x, y)``. Returns 0 or 1. This method reads from the visible buffer. -.. method:: lcd.light(value) +.. method:: LCD.light(value) Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off. -.. method:: lcd.pixel(x, y, colour) +.. method:: LCD.pixel(x, y, colour) Set the pixel at ``(x, y)`` to the given colour (0 or 1). This method writes to the hidden buffer. Use ``show()`` to show the buffer. -.. method:: lcd.show() +.. method:: LCD.show() Show the hidden buffer on the screen. -.. method:: lcd.text(str, x, y, colour) +.. method:: LCD.text(str, x, y, colour) Draw the given text to the position ``(x, y)`` using the given colour (0 or 1). This method writes to the hidden buffer. Use ``show()`` to show the buffer. -.. method:: lcd.write(str) +.. method:: LCD.write(str) Write the string ``str`` to the screen. It will appear immediately. diff --git a/docs/library/pyb.LED.rst b/docs/library/pyb.LED.rst index aeeb75b8f1..1ab73a69c9 100644 --- a/docs/library/pyb.LED.rst +++ b/docs/library/pyb.LED.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.LED: class LED -- LED object @@ -19,7 +20,7 @@ Constructors Methods ------- -.. method:: led.intensity([value]) +.. method:: LED.intensity([value]) Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on). If no argument is given, return the LED intensity. @@ -31,15 +32,15 @@ Methods relevant LED is set to a value between 1 and 254. Otherwise the timers are free for general purpose use. -.. method:: led.off() +.. method:: LED.off() Turn the LED off. -.. method:: led.on() +.. method:: LED.on() Turn the LED on, to maximum intensity. -.. method:: led.toggle() +.. method:: LED.toggle() Toggle the LED between on (maximum intensity) and off. If the LED is at non-zero intensity then it is considered "on" and toggle will turn it off. diff --git a/docs/library/pyb.Pin.rst b/docs/library/pyb.Pin.rst index 30440f5025..154217ebb7 100644 --- a/docs/library/pyb.Pin.rst +++ b/docs/library/pyb.Pin.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.Pin: class Pin -- control I/O pins @@ -84,20 +85,16 @@ Constructors Class methods ------------- - - .. method:: Pin.af_list() - - Returns an array of alternate functions available for this pin. - - .. method:: Pin.debug([state]) + + .. classmethod:: Pin.debug([state]) Get or set the debugging state (``True`` or ``False`` for on or off). - .. method:: Pin.dict([dict]) + .. classmethod:: Pin.dict([dict]) Get or set the pin mapper dictionary. - .. method:: Pin.mapper([fun]) + .. classmethod:: Pin.mapper([fun]) Get or set the pin mapper function. @@ -107,7 +104,7 @@ Methods .. only:: port_pyboard - .. method:: pin.init(mode, pull=Pin.PULL_NONE, af=-1) + .. method:: Pin.init(mode, pull=Pin.PULL_NONE, af=-1) Initialise the pin: @@ -131,7 +128,7 @@ Methods Returns: ``None``. -.. method:: pin.value([value]) +.. method:: Pin.value([value]) Get or set the digital logic level of the pin: @@ -142,43 +139,47 @@ Methods .. only:: port_pyboard - .. method:: pin.__str__() + .. method:: Pin.__str__() Return a string describing the pin object. - .. method:: pin.af() + .. method:: Pin.af() Returns the currently configured alternate-function of the pin. The integer returned will match one of the allowed constants for the af argument to the init function. + + .. method:: Pin.af_list() + + Returns an array of alternate functions available for this pin. - .. method:: pin.gpio() + .. method:: Pin.gpio() Returns the base address of the GPIO block associated with this pin. - .. method:: pin.mode() + .. method:: Pin.mode() Returns the currently configured mode of the pin. The integer returned will match one of the allowed constants for the mode argument to the init function. - .. method:: pin.name() + .. method:: Pin.name() Get the pin name. - .. method:: pin.names() + .. method:: Pin.names() Returns the cpu and board names for this pin. - .. method:: pin.pin() + .. method:: Pin.pin() Get the pin number. - .. method:: pin.port() + .. method:: Pin.port() Get the pin port. - -.. method:: pin.pull() + +.. method:: Pin.pull() Returns the currently configured pull of the pin. The integer returned will match one of the allowed constants for the pull argument to the init diff --git a/docs/library/pyb.RTC.rst b/docs/library/pyb.RTC.rst index 51b17deccf..383ddf20c2 100644 --- a/docs/library/pyb.RTC.rst +++ b/docs/library/pyb.RTC.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.RTC: class RTC -- real time clock @@ -24,7 +25,7 @@ Constructors Methods ------- -.. method:: rtc.datetime([datetimetuple]) +.. method:: RTC.datetime([datetimetuple]) Get or set the date and time of the RTC. @@ -44,7 +45,7 @@ Methods .. only:: port_pyboard - .. method:: rtc.wakeup(timeout, callback=None) + .. method:: RTC.wakeup(timeout, callback=None) Set the RTC wakeup timer to trigger repeatedly at every ``timeout`` milliseconds. This trigger can wake the pyboard from both the sleep @@ -55,7 +56,7 @@ Methods If ``callback`` is given then it is executed at every trigger of the wakeup timer. ``callback`` must take exactly one argument. - .. method:: rtc.info() + .. method:: RTC.info() Get information about the startup time and reset source. @@ -64,7 +65,7 @@ Methods - Bit 0x10000 is set if a power-on reset occurred. - Bit 0x20000 is set if an external reset occurred - .. method:: rtc.calibration(cal) + .. method:: RTC.calibration(cal) Get or set RTC calibration. diff --git a/docs/library/pyb.SPI.rst b/docs/library/pyb.SPI.rst index b17c804d70..54ecc65b6d 100644 --- a/docs/library/pyb.SPI.rst +++ b/docs/library/pyb.SPI.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.SPI: class SPI -- a master-driven serial protocol @@ -50,13 +51,13 @@ Constructors Methods ------- -.. method:: spi.deinit() +.. method:: SPI.deinit() Turn off the SPI bus. .. only:: port_pyboard - .. 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: @@ -82,7 +83,7 @@ Methods .. only:: port_pyboard - .. method:: spi.recv(recv, \*, timeout=5000) + .. method:: SPI.recv(recv, \*, timeout=5000) Receive data on the bus: @@ -93,7 +94,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: @@ -102,7 +103,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: diff --git a/docs/library/pyb.Servo.rst b/docs/library/pyb.Servo.rst index cea31fd28e..b3ce71d11a 100644 --- a/docs/library/pyb.Servo.rst +++ b/docs/library/pyb.Servo.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.Servo: class Servo -- 3-wire hobby servo driver @@ -37,7 +38,7 @@ Constructors Methods ------- -.. method:: servo.angle([angle, time=0]) +.. method:: Servo.angle([angle, time=0]) If no arguments are given, this function returns the current angle. @@ -48,7 +49,7 @@ Methods angle. If omitted, then the servo moves as quickly as possible to its new position. -.. method:: servo.speed([speed, time=0]) +.. method:: Servo.speed([speed, time=0]) If no arguments are given, this function returns the current speed. @@ -58,14 +59,14 @@ Methods - ``time`` is the number of milliseconds to take to get to the specified speed. If omitted, then the servo accelerates as quickly as possible. -.. method:: servo.pulse_width([value]) +.. method:: Servo.pulse_width([value]) If no arguments are given, this function returns the current raw pulse-width value. If an argument is given, this function sets the raw pulse-width value. -.. method:: servo.calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]]) +.. method:: Servo.calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]]) If no arguments are given, this function returns the current calibration data, as a 5-tuple. diff --git a/docs/library/pyb.Switch.rst b/docs/library/pyb.Switch.rst index daaed19420..bc62b6eee9 100644 --- a/docs/library/pyb.Switch.rst +++ b/docs/library/pyb.Switch.rst @@ -1,3 +1,5 @@ +.. currentmodule:: pyb + class Switch -- switch object ============================= @@ -27,11 +29,12 @@ Constructors Methods ------- -.. method:: switch() +.. method:: Switch.__call__() - Return the switch state: ``True`` if pressed down, ``False`` otherwise. + Call switch object directly to get its state: ``True`` if pressed down, + ``False`` otherwise. -.. method:: switch.callback(fun) +.. method:: Switch.callback(fun) Register the given function to be called when the switch is pressed down. If ``fun`` is ``None``, then it disables the callback. diff --git a/docs/library/pyb.Timer.rst b/docs/library/pyb.Timer.rst index d2a299bd29..ffb092caa3 100644 --- a/docs/library/pyb.Timer.rst +++ b/docs/library/pyb.Timer.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.Timer: class Timer -- control internal timers @@ -67,7 +68,7 @@ Methods .. only:: port_pyboard - .. method:: timer.init(\*, freq, prescaler, period) + .. method:: Timer.init(\*, freq, prescaler, period) Initialise the timer. Initialisation must be either by frequency (in Hz) or by prescaler and period:: @@ -114,7 +115,7 @@ Methods You must either specify freq or both of period and prescaler. -.. method:: timer.deinit() +.. method:: Timer.deinit() Deinitialises the timer. @@ -127,7 +128,7 @@ Methods .. only:: port_pyboard - .. method:: timer.callback(fun) + .. method:: Timer.callback(fun) Set the function to be called when the timer triggers. ``fun`` is passed 1 argument, the timer object. @@ -135,7 +136,7 @@ Methods .. only:: port_pyboard - .. method:: timer.channel(channel, mode, ...) + .. method:: Timer.channel(channel, mode, ...) If only a channel number is passed, then a previously initialized channel object is returned (or ``None`` if there is no previous channel). @@ -211,27 +212,27 @@ Methods .. only:: port_pyboard - .. method:: timer.counter([value]) + .. method:: Timer.counter([value]) Get or set the timer counter. .. only:: port_pyboard - .. method:: timer.freq([value]) + .. method:: Timer.freq([value]) Get or set the frequency for the timer (changes prescaler and period if set). .. only:: port_pyboard - .. method:: timer.period([value]) + .. method:: Timer.period([value]) Get or set the period of the timer. - .. method:: timer.prescaler([value]) + .. method:: Timer.prescaler([value]) Get or set the prescaler for the timer. - .. method:: timer.source_freq() + .. method:: Timer.source_freq() Get the frequency of the source of the timer. diff --git a/docs/library/pyb.UART.rst b/docs/library/pyb.UART.rst index 536b6f467d..4a692469f8 100644 --- a/docs/library/pyb.UART.rst +++ b/docs/library/pyb.UART.rst @@ -1,3 +1,4 @@ +.. currentmodule:: pyb .. _pyb.UART: class UART -- duplex serial communication bus @@ -76,7 +77,7 @@ Methods .. only:: port_pyboard - .. method:: uart.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=0, timeout_char=0, read_buf_len=64) + .. method:: UART.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=0, timeout_char=0, read_buf_len=64) Initialise the UART bus with the given parameters: @@ -100,22 +101,22 @@ Methods *Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported. -.. method:: uart.deinit() +.. method:: UART.deinit() Turn off the UART bus. .. only:: port_pyboard - .. method:: uart.any() + .. method:: UART.any() Returns the number of bytes waiting (may be 0). - .. method:: uart.writechar(char) + .. method:: UART.writechar(char) Write a single character on the bus. ``char`` is an integer to write. Return value: ``None``. See note below if CTS flow control is used. -.. method:: uart.read([nbytes]) +.. method:: UART.read([nbytes]) Read characters. If ``nbytes`` is specified then read at most that many bytes. If ``nbytes`` are available in the buffer, returns immediately, otherwise returns @@ -129,19 +130,19 @@ Methods Return value: a bytes object containing the bytes read in. Returns ``None`` on timeout. -.. method:: uart.readall() +.. method:: UART.readall() Read as much data as possible. Returns after the timeout has elapsed. Return value: a bytes object or ``None`` if timeout prevents any data being read. -.. method:: uart.readchar() +.. method:: UART.readchar() Receive a single character on the bus. Return value: The character read, as an integer. Returns -1 on timeout. -.. method:: uart.readinto(buf[, nbytes]) +.. 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. @@ -149,7 +150,7 @@ Methods Return value: number of bytes read and stored into ``buf`` or ``None`` on timeout. -.. method:: uart.readline() +.. method:: UART.readline() Read a line, ending in a newline character. If such a line exists, return is immediate. If the timeout elapses, all available data is returned regardless @@ -157,7 +158,7 @@ Methods Return value: the line read or ``None`` on timeout if no data is available. -.. method:: uart.write(buf) +.. method:: UART.write(buf) .. only:: port_pyboard @@ -169,7 +170,7 @@ Methods Return value: number of bytes written. If a timeout occurs and no bytes were written returns ``None``. -.. method:: uart.sendbreak() +.. method:: UART.sendbreak() Send a break condition on the bus. This drives the bus low for a duration of 13 bits. @@ -214,14 +215,14 @@ Flow Control If CTS flow control is enabled the write behaviour is as follows: - If the Pyboard's ``uart.write(buf)`` method is called, transmission will stall for + If the Pyboard's ``UART.write(buf)`` method is called, transmission will stall for any periods when ``nCTS`` is ``False``. This will result in a timeout if the entire buffer was not transmitted in the timeout period. The method returns the number of bytes written, enabling the user to write the remainder of the data if required. In the event of a timeout, a character will remain in the UART pending ``nCTS``. The number of bytes composing this character will be included in the return value. - If ``uart.writechar()`` is called when ``nCTS`` is ``False`` the method will time + If ``UART.writechar()`` is called when ``nCTS`` is ``False`` the method will time out unless the target asserts ``nCTS`` in time. If it times out ``OSError 116`` will be raised. The character will be transmitted as soon as the target asserts ``nCTS``. diff --git a/docs/library/pyb.USB_VCP.rst b/docs/library/pyb.USB_VCP.rst index cc4dbe5903..4e34af2586 100644 --- a/docs/library/pyb.USB_VCP.rst +++ b/docs/library/pyb.USB_VCP.rst @@ -1,3 +1,5 @@ +.. currentmodule:: pyb + class USB_VCP -- USB virtual comm port ====================================== @@ -17,7 +19,7 @@ Constructors Methods ------- -.. method:: usb_vcp.setinterrupt(chr) +.. method:: USB_VCP.setinterrupt(chr) Set the character which interrupts running Python code. This is set to 3 (CTRL-C) by default, and when a CTRL-C character is received over @@ -26,20 +28,20 @@ Methods Set to -1 to disable this interrupt feature. This is useful when you want to send raw bytes over the USB VCP port. -.. method:: usb_vcp.isconnected() +.. method:: USB_VCP.isconnected() Return ``True`` if USB is connected as a serial device, else ``False``. -.. method:: usb_vcp.any() +.. method:: USB_VCP.any() Return ``True`` if any characters waiting, else ``False``. -.. method:: usb_vcp.close() +.. method:: USB_VCP.close() This method does nothing. It exists so the USB_VCP object can act as a file. -.. method:: usb_vcp.read([nbytes]) +.. method:: USB_VCP.read([nbytes]) Read at most ``nbytes`` from the serial device and return them as a bytes object. If ``nbytes`` is not specified then the method acts as @@ -47,12 +49,12 @@ Methods so if no pending data available, this method will return immediately with ``None`` value. -.. method:: usb_vcp.readall() +.. method:: USB_VCP.readall() Read all available bytes from the serial device and return them as a bytes object, or ``None`` if no pending data available. -.. method:: usb_vcp.readinto(buf, [maxlen]) +.. method:: USB_VCP.readinto(buf, [maxlen]) Read bytes from the serial device and store them into ``buf``, which should be a buffer-like object. At most ``len(buf)`` bytes are read. @@ -62,14 +64,14 @@ Methods Returns the number of bytes read and stored into ``buf`` or ``None`` if no pending data available. -.. method:: usb_vcp.readline() +.. method:: USB_VCP.readline() Read a whole line from the serial device. Returns a bytes object containing the data, including the trailing newline character or ``None`` if no pending data available. -.. method:: usb_vcp.readlines() +.. method:: USB_VCP.readlines() Read as much data as possible from the serial device, breaking it into lines. @@ -77,13 +79,13 @@ Methods Returns a list of bytes objects, each object being one of the lines. Each line will include the newline character. -.. method:: usb_vcp.write(buf) +.. method:: USB_VCP.write(buf) Write the bytes from ``buf`` to the serial device. 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: @@ -94,7 +96,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: diff --git a/docs/library/select.rst b/docs/library/select.rst index c24f010e6b..8dcd4080f1 100644 --- a/docs/library/select.rst +++ b/docs/library/select.rst @@ -61,7 +61,7 @@ Methods list of (``obj``, ``event``, ...) tuples, ``event`` element specifies which events happened with a stream and is a combination of `select.POLL*` constants described above. There may be other elements in tuple, depending - on platform and version, so don't assume that its size is 2. In case of + on a platform and version, so don't assume that its size is 2. In case of timeout, an empty list is returned. Timeout is in milliseconds. diff --git a/docs/library/sys.rst b/docs/library/sys.rst index b5a9138c07..1d7579754f 100644 --- a/docs/library/sys.rst +++ b/docs/library/sys.rst @@ -21,7 +21,12 @@ Functions .. admonition:: Difference to CPython :class: attention - This function appears in the ``traceback`` module in CPython. + This is simplified version of a function which appears in the + ``traceback`` module in CPython. Unlike ``traceback.print_exception()``, + 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. Constants --------- diff --git a/docs/library/uctypes.rst b/docs/library/uctypes.rst index 9a7f85edcd..630a3a36fb 100644 --- a/docs/library/uctypes.rst +++ b/docs/library/uctypes.rst @@ -1,97 +1,106 @@ -:mod:`uctypes` -- access C structures -===================================== +:mod:`uctypes` -- access binary data in a structured way +======================================================== .. module:: uctypes - :synopsis: access C structures + :synopsis: access binary data in a structured way This module implements "foreign data interface" for MicroPython. The idea -behind it is similar to CPython's ``ctypes`` modules, but actual API is -different, streamlined and optimized for small size. +behind it is similar to CPython's ``ctypes`` modules, but the actual API is +different, streamlined and optimized for small size. The basic idea of the +module is to define data structure layout with about the same power as the +C language allows, and the access it using familiar dot-syntax to reference +sub-fields. + +.. seealso:: + + Module :mod:`ustruct` + Standard Python way to access binary data structures (doesn't scale + well to large and complex structures). Defining structure layout ------------------------- Structure layout is defined by a "descriptor" - a Python dictionary which encodes field names as keys and other properties required to access them as -an associated values. Currently, uctypes requires explicit specification of -offsets for each field. Offset are given in bytes from structure start. +associated values. Currently, uctypes requires explicit specification of +offsets for each field. Offset are given in bytes from a structure start. Following are encoding examples for various field types: - Scalar types:: +* Scalar types:: "field_name": uctypes.UINT32 | 0 - in other words, value is scalar type identifier ORed with field offset - (in bytes) from the start of the structure. + in other words, value is scalar type identifier ORed with field offset + (in bytes) from the start of the structure. - Recursive structures:: +* Recursive structures:: "sub": (2, { "b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1, }) - i.e. value is a 2-tuple, first element of which is offset, and second is - a structure descriptor dictionary (note: offsets in recursive descriptors - are relative to a structure it defines). + i.e. value is a 2-tuple, first element of which is offset, and second is + a structure descriptor dictionary (note: offsets in recursive descriptors + are relative to a structure it defines). - Arrays of primitive types:: +* Arrays of primitive types:: "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), - i.e. value is a 2-tuple, first element of which is ARRAY flag ORed - with offset, and second is scalar element type ORed number of elements - in array. + i.e. value is a 2-tuple, first element of which is ARRAY flag ORed + with offset, and second is scalar element type ORed number of elements + in array. - Arrays of aggregate types:: +* Arrays of aggregate types:: "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), - i.e. value is a 3-tuple, first element of which is ARRAY flag ORed - with offset, second is a number of elements in array, and third is - descriptor of element type. + i.e. value is a 3-tuple, first element of which is ARRAY flag ORed + with offset, second is a number of elements in array, and third is + descriptor of element type. - Pointer to a primitive type:: +* Pointer to a primitive type:: "ptr": (uctypes.PTR | 0, uctypes.UINT8), - i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, and second is scalar element type. + i.e. value is a 2-tuple, first element of which is PTR flag ORed + with offset, and second is scalar element type. - Pointer to aggregate type:: +* Pointer to an aggregate type:: "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), - i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, second is descriptor of type pointed to. + i.e. value is a 2-tuple, first element of which is PTR flag ORed + with offset, second is descriptor of type pointed to. - Bitfields:: +* Bitfields:: "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, - i.e. value is type of scalar value containing given bitfield (typenames are - similar to scalar types, but prefixes with "BF"), ORed with offset for - scalar value containing the bitfield, and further ORed with values for - bit offset and bit length of the bitfield within scalar value, shifted by - BF_POS and BF_LEN positions, respectively. Bitfield position is counted - from the least significant bit, and is the number of right-most bit of a - field (in other words, it's a number of bits a scalar needs to be shifted - right to extra the bitfield). - - In the example above, first UINT16 value will be extracted at offset 0 - (this detail may be important when accessing hardware registers, where - particular access size and alignment are required), and then bitfield - whose rightmost bit is least-significant bit of this UINT16, and length - is 8 bits, will be extracted - effectively, this will access - least-significant byte of UINT16. - - Note that bitfield operations are independent of target byte endianness, - in particular, example above will access least-significant byte of UINT16 - in both little- and big-endian structures. But it depends on the least - significant bit being numbered 0. Some targets may use different - numbering in their native ABI, but ``uctypes`` always uses normalized - numbering described above. + i.e. value is type of scalar value containing given bitfield (typenames are + similar to scalar types, but prefixes with "BF"), ORed with offset for + scalar value containing the bitfield, and further ORed with values for + bit offset and bit length of the bitfield within scalar value, shifted by + BF_POS and BF_LEN positions, respectively. Bitfield position is counted + from the least significant bit, and is the number of right-most bit of a + field (in other words, it's a number of bits a scalar needs to be shifted + right to extra the bitfield). + + In the example above, first UINT16 value will be extracted at offset 0 + (this detail may be important when accessing hardware registers, where + particular access size and alignment are required), and then bitfield + whose rightmost bit is least-significant bit of this UINT16, and length + is 8 bits, will be extracted - effectively, this will access + least-significant byte of UINT16. + + Note that bitfield operations are independent of target byte endianness, + in particular, example above will access least-significant byte of UINT16 + in both little- and big-endian structures. But it depends on the least + significant bit being numbered 0. Some targets may use different + numbering in their native ABI, but ``uctypes`` always uses normalized + numbering described above. Module contents --------------- @@ -103,17 +112,18 @@ Module contents .. data:: LITTLE_ENDIAN - Little-endian packed structure. (Packed means that every field occupies - exactly as many bytes as defined in the descriptor, i.e. alignment is 1). + Layout type for a little-endian packed structure. (Packed means that every + field occupies exactly as many bytes as defined in the descriptor, i.e. + the alignment is 1). .. data:: BIG_ENDIAN - Big-endian packed structure. + Layour type for a big-endian packed structure. .. data:: NATIVE - Native structure - with data endianness and alignment conforming to - the ABI of the system on which MicroPython runs. + 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) @@ -145,33 +155,55 @@ Structure descriptors and instantiating structure objects Given a structure descriptor dictionary and its layout type, you can instantiate a specific structure instance at a given memory address -using uctypes.struct() constructor. Memory address usually comes from +using :class:`uctypes.struct()` constructor. Memory address usually comes from following sources: * Predefined address, when accessing hardware registers on a baremetal system. Lookup these addresses in datasheet for a particular MCU/SoC. -* As return value from a call to some FFI (Foreign Function Interface) +* As a return value from a call to some FFI (Foreign Function Interface) function. -* From uctypes.addressof(), when you want to pass arguments to FFI +* From uctypes.addressof(), when you want to pass arguments to an FFI function, or alternatively, to access some data for I/O (for example, - data read from file or network socket). + data read from a file or network socket). Structure objects ----------------- Structure objects allow accessing individual fields using standard dot -notation: ``my_struct.field1``. If a field is of scalar type, getting -it will produce primitive value (Python integer or float) corresponding -to value contained in a field. Scalar field can also be assigned to. +notation: ``my_struct.substruct1.field1``. If a field is of scalar type, +getting it will produce a primitive value (Python integer or float) +corresponding to the value contained in a field. A scalar field can also +be assigned to. If a field is an array, its individual elements can be accessed with -standard subscript operator - both read and assigned to. +the standard subscript operator ``[]`` - both read and assigned to. If a field is a pointer, it can be dereferenced using ``[0]`` syntax (corresponding to C ``*`` operator, though ``[0]`` works in C too). -Subscripting pointer with other integer values but 0 are supported too, +Subscripting a pointer with other integer values but 0 are supported too, with the same semantics as in C. Summing up, accessing structure fields generally follows C syntax, -except for pointer derefence, you need to use ``[0]`` operator instead -of ``*``. +except for pointer derefence, when you need to use ``[0]`` operator +instead of ``*``. + +Limitations +----------- + +Accessing non-scalar fields leads to allocation of intermediate objects +to represent them. This means that special care should be taken to +layout a structure which needs to be accessed when memory allocation +is disabled (e.g. from an interrupt). The recommendations are: + +* Avoid nested structures. For example, instead of + ``mcu_registers.peripheral_a.register1``, define separate layout + descriptors for each peripheral, to be accessed as + ``peripheral_a.register1``. +* Avoid other non-scalar data, like array. For example, instead of + ``peripheral_a.register[0]`` use ``peripheral_a.register0``. + +Note that these recommendations will lead to decreased readability +and conciseness of layouts, so they should be used only if the need +to access structure fields without allocation is anticipated (it's +even possible to define 2 parallel layouts - one for normal usage, +and a restricted one to use when memory allocation is prohibited). diff --git a/docs/library/ure.rst b/docs/library/ure.rst index f20dff6f39..ee360bcc47 100644 --- a/docs/library/ure.rst +++ b/docs/library/ure.rst @@ -32,7 +32,7 @@ Supported operators are: ``'+?'`` -Counted repetitions (``{m,n}``), more advanced assertions, names groups, +Counted repetitions (``{m,n}``), more advanced assertions, named groups, etc. are not supported. diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst index d31e4d2fc9..9b279e5ba7 100644 --- a/docs/library/usocket.rst +++ b/docs/library/usocket.rst @@ -74,6 +74,7 @@ Constants .. data:: socket.IPPROTO_UDP .. data:: socket.IPPROTO_TCP .. only:: port_wipy + .. data:: socket.IPPROTO_SEC protocol numbers @@ -100,7 +101,7 @@ Methods Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it's lower, it will be set to 0); and specifies the number of unaccepted connections - tha the system will allow before refusing new connections. If not specified, a default + that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen. .. method:: socket.accept() diff --git a/docs/sphinx_selective_exclude/LICENSE b/docs/sphinx_selective_exclude/LICENSE new file mode 100644 index 0000000000..0b47ced8a1 --- /dev/null +++ b/docs/sphinx_selective_exclude/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2016 by the sphinx_selective_exclude authors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/sphinx_selective_exclude/README.md b/docs/sphinx_selective_exclude/README.md new file mode 100644 index 0000000000..cc9725c21c --- /dev/null +++ b/docs/sphinx_selective_exclude/README.md @@ -0,0 +1,138 @@ +Sphinx eager ".. only::" directive and other selective rendition extensions +=========================================================================== + +Project home page: https://github.com/pfalcon/sphinx_selective_exclude + +The implementation of ".. only::" directive in Sphinx documentation +generation tool is known to violate principles of least user surprise +and user expectations in general. Instead of excluding content early +in the pipeline (pre-processor style), Sphinx defers exclusion until +output phase, and what's the worst, various stages processing ignore +"only" blocks and their exclusion status, so they may leak unexpected +information into ToC, indexes, etc. + +There's multiple issues submitted upstream on this matter: + +* https://github.com/sphinx-doc/sphinx/issues/2150 +* https://github.com/sphinx-doc/sphinx/issues/1717 +* https://github.com/sphinx-doc/sphinx/issues/1488 +* etc. + +They are largely ignored by Sphinx maintainers. + +This projects tries to rectify situation on users' side. It actually +changes the way Sphinx processes "only" directive, but does this +without forking the project, and instead is made as a standard +Sphinx extension, which a user may add to their documentation config. +Unlike normal extensions, extensions provided in this package +monkey-patch Sphinx core to work in a way expected by users. + +eager_only +---------- + +The core extension provided by the package is called `eager_only` and +is based on the idea by Andrea Cassioli (see bugreports above) to +process "only" directive as soon as possible during parsing phase. +This approach has some drawbacks, like producing warnings like +"WARNING: document isn't included in any toctree" if "only" is used +to shape up a toctree, or the fact that changing a documentation +builder (html/latex/etc.) will almost certainly require complete +rebuild of documentation. But these are relatively minor issues +comparing to completely broken way "only" works in upstream Sphinx. + +modindex_exclude +---------------- + +"only" directive allows for fine-grained conditional exclusion, but +sometimes you may want to exclude entire module(s) at once. Even if +you wrap an entire module description in "only" directive, like: + + .. only: option1 + .. module:: my_module + + ... + +You will still have an HTML page generated, albeit empty. It may also +go into indexes, so will be discoverable by users, leading to less +than ideal experience. `modindex_exclude` extension is design to +resolve this issue, by making sure that any reference of a module +is excluded from Python module index ("modindex"), as well as +general cross-reference index ("genindex"). In the latter case, +any symbol belong to a module will be excluded. Unlike `eager_only` +extension which appear to have issued with "latexpdf" builder, +`modindex_exclude` is useful for PDF, and allows to get cleaner +index for PDF, just the same as for HTML. + +search_auto_exclude +------------------- + +Even if you exclude soem documents from toctree:: using only:: +directive, they will be indexed for full-text search, so user may +find them and get confused. This plugin follows very simple idea +that if you didn't include some documents in the toctree, then +you didn't want them to be accessible (e.g. for a particular +configuration), and so will make sure they aren't indexed either. + +This extension depends on `eager_only` and won't work without it. +Note that Sphinx will issue warnings, as usual, for any documents +not included in a toctree. This is considered a feature, and gives +you a chance to check that document exclusions are indeed right +for a particular configuration you build (and not that you forgot +to add something to a toctree). + +Summary +------- + +Based on the above, sphinx_selective_exclude offers extension to let +you: + +* Make "only::" directive work in an expected, intuitive manner, using + `eager_only` extension. +* However, if you apply only:: to toctree::, excluded documents will + still be available via full-text search, so you need to use + `search_auto_exclude` for that to work as expected. +* Similar to search, indexes may also require special treatment, hence + there's the `modindex_exclude` extension. + +Most likely, you will want to use all 3 extensions together - if you +really want build subsets of docimentation covering sufficiently different +configurations from a single doctree. However, if one of them is enough +to cover your usecase, that's OK to (and why they were separated into +3 extensions, to follow KISS and "least surprise" principles and to +not make people deal with things they aren't interested in). In this case, +however remember there're other extensions, if you later hit a usecase +when they're needed. + +Usage +----- + +To use these extensions, add https://github.com/pfalcon/sphinx_selective_exclude +as a git submodule to your project, in documentation folder (where +Sphinx conf.py is located). Alternatively, commit sphinx_selective_exclude +directory instead of making it a submodule (you will need to pick up +any project updates manually then). + +Add following lines to "extensions" settings in your conf.py (you +likely already have some standard Sphinx extensions enabled): + + extensions = [ + ... + 'sphinx_selective_exclude.eager_only', + 'sphinx_selective_exclude.search_auto_exclude', + 'sphinx_selective_exclude.modindex_exclude', + ] + +As discussed above, you may enable all extensions, or one by one. + +Please note that to make sure these extensions work well and avoid producing +output docs with artifacts, it is IMPERATIVE to remove cached doctree if +you rebuild documentation with another builder (i.e. with different output +format). Also, to stay on safe side, it's recommended to remove old doctree +anyway before generating production-ready documentation for publishing. To +do that, run something like: + + rm -rf _build/doctrees/ + +A typical artificat when not following these simple rules is that content +of some sections may be missing. If you face anything like that, just +remember what's written above and remove cached doctrees. diff --git a/docs/sphinx_selective_exclude/__init__.py b/docs/sphinx_selective_exclude/__init__.py new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/docs/sphinx_selective_exclude/__init__.py diff --git a/docs/sphinx_selective_exclude/eager_only.py b/docs/sphinx_selective_exclude/eager_only.py new file mode 100644 index 0000000000..82766c2e64 --- /dev/null +++ b/docs/sphinx_selective_exclude/eager_only.py @@ -0,0 +1,45 @@ +# +# This is a Sphinx documentation tool extension which makes .only:: +# directives be eagerly processed early in the parsing stage. This +# makes sure that content in .only:: blocks gets actually excluded +# as a typical user expects, instead of bits of information in +# these blocks leaking to documentation in various ways (e.g., +# indexes containing entries for functions which are actually in +# .only:: blocks and thus excluded from documentation, etc.) +# Note that with this extension, you may need to completely +# rebuild a doctree when switching builders (i.e. completely +# remove _build/doctree dir between generation of HTML vs PDF +# documentation). +# +# This extension works by monkey-patching Sphinx core, so potentially +# may not work with untested Sphinx versions. It tested to work with +# 1.2.2 and 1.4.2 +# +# Copyright (c) 2016 Paul Sokolovsky +# Based on idea by Andrea Cassioli: +# https://github.com/sphinx-doc/sphinx/issues/2150#issuecomment-171912290 +# Licensed under the terms of BSD license, see LICENSE file. +# +import sphinx +from docutils.parsers.rst import directives + + +class EagerOnly(sphinx.directives.other.Only): + + def run(self, *args): + # Evaluate the condition eagerly, and if false return no nodes right away + env = self.state.document.settings.env + env.app.builder.tags.add('TRUE') + #print(repr(self.arguments[0])) + if not env.app.builder.tags.eval_condition(self.arguments[0]): + return [] + + # Otherwise, do the usual processing + nodes = super(EagerOnly, self).run() + if len(nodes) == 1: + nodes[0]['expr'] = 'TRUE' + return nodes + + +def setup(app): + directives.register_directive('only', EagerOnly) diff --git a/docs/sphinx_selective_exclude/modindex_exclude.py b/docs/sphinx_selective_exclude/modindex_exclude.py new file mode 100644 index 0000000000..18b49cc80f --- /dev/null +++ b/docs/sphinx_selective_exclude/modindex_exclude.py @@ -0,0 +1,75 @@ +# +# This is a Sphinx documentation tool extension which allows to +# exclude some Python modules from the generated indexes. Modules +# are excluded both from "modindex" and "genindex" index tables +# (in the latter case, all members of a module are exlcuded). +# To control exclusion, set "modindex_exclude" variable in Sphinx +# conf.py to the list of modules to exclude. Note: these should be +# modules (as defined by py:module directive, not just raw filenames). +# This extension works by monkey-patching Sphinx core, so potentially +# may not work with untested Sphinx versions. It tested to work with +# 1.2.2 and 1.4.2 +# +# Copyright (c) 2016 Paul Sokolovsky +# Licensed under the terms of BSD license, see LICENSE file. +# +import sphinx + + +#org_PythonModuleIndex_generate = None +org_PyObject_add_target_and_index = None +org_PyModule_run = None + +EXCLUDES = {} + +# No longer used, PyModule_run() monkey-patch does all the job +def PythonModuleIndex_generate(self, docnames=None): + docnames = [] + excludes = self.domain.env.config['modindex_exclude'] + for modname, (docname, synopsis, platforms, deprecated) in self.domain.data['modules'].items(): + #print(docname) + if modname not in excludes: + docnames.append(docname) + + return org_PythonModuleIndex_generate(self, docnames) + + +def PyObject_add_target_and_index(self, name_cls, sig, signode): + if hasattr(self.env, "ref_context"): + # Sphinx 1.4 + ref_context = self.env.ref_context + else: + # Sphinx 1.2 + ref_context = self.env.temp_data + modname = self.options.get( + 'module', ref_context.get('py:module')) + #print("*", modname, name_cls) + if modname in self.env.config['modindex_exclude']: + return None + return org_PyObject_add_target_and_index(self, name_cls, sig, signode) + + +def PyModule_run(self): + env = self.state.document.settings.env + modname = self.arguments[0].strip() + excl = env.config['modindex_exclude'] + if modname in excl: + self.options['noindex'] = True + EXCLUDES.setdefault(modname, []).append(env.docname) + return org_PyModule_run(self) + + +def setup(app): + app.add_config_value('modindex_exclude', [], 'html') + +# global org_PythonModuleIndex_generate +# org_PythonModuleIndex_generate = sphinx.domains.python.PythonModuleIndex.generate +# sphinx.domains.python.PythonModuleIndex.generate = PythonModuleIndex_generate + + global org_PyObject_add_target_and_index + org_PyObject_add_target_and_index = sphinx.domains.python.PyObject.add_target_and_index + sphinx.domains.python.PyObject.add_target_and_index = PyObject_add_target_and_index + + global org_PyModule_run + org_PyModule_run = sphinx.domains.python.PyModule.run + sphinx.domains.python.PyModule.run = PyModule_run diff --git a/docs/sphinx_selective_exclude/search_auto_exclude.py b/docs/sphinx_selective_exclude/search_auto_exclude.py new file mode 100644 index 0000000000..b8b326dd2c --- /dev/null +++ b/docs/sphinx_selective_exclude/search_auto_exclude.py @@ -0,0 +1,34 @@ +# +# This is a Sphinx documentation tool extension which allows to +# automatically exclude from full-text search index document +# which are not referenced via toctree::. It's intended to be +# used with toctrees conditional on only:: directive, with the +# idea being that if you didn't include it in the ToC, you don't +# want the docs being findable by search either (for example, +# because these docs contain information not pertinent to a +# particular product configuration). +# +# This extension depends on "eager_only" extension and won't work +# without it. +# +# Copyright (c) 2016 Paul Sokolovsky +# Licensed under the terms of BSD license, see LICENSE file. +# +import sphinx + + +org_StandaloneHTMLBuilder_index_page = None + + +def StandaloneHTMLBuilder_index_page(self, pagename, doctree, title): + if pagename not in self.env.files_to_rebuild: + if pagename != self.env.config.master_doc and 'orphan' not in self.env.metadata[pagename]: + print("Excluding %s from full-text index because it's not referenced in ToC" % pagename) + return + return org_StandaloneHTMLBuilder_index_page(self, pagename, doctree, title) + + +def setup(app): + global org_StandaloneHTMLBuilder_index_page + org_StandaloneHTMLBuilder_index_page = sphinx.builders.html.StandaloneHTMLBuilder.index_page + sphinx.builders.html.StandaloneHTMLBuilder.index_page = StandaloneHTMLBuilder_index_page diff --git a/docs/templates/versions.html b/docs/templates/versions.html index 6323024ecb..198630dd77 100644 --- a/docs/templates/versions.html +++ b/docs/templates/versions.html @@ -17,14 +17,12 @@ <dd><a href="{{ url }}">{{ slug }}</a></dd> {% endfor %} </dl> - <!-- <dl> <dt>Downloads</dt> {% for type, url in downloads %} <dd><a href="{{ url }}">{{ type }}</a></dd> {% endfor %} </dl> - --> <hr/> <dl> <dt>External links</dt> |