GitBook: [master] 331 pages modified

This commit is contained in:
Daniel Spindelbauer
2018-09-04 10:13:29 +00:00
committed by gitbook-bot
parent f179b56b33
commit 514f62ebce
169 changed files with 289 additions and 289 deletions

View File

@@ -1,10 +0,0 @@
# MicroPython Modules
The following list contains the standard Python libraries, MicroPython-specific libraries and Pycom specific modules that are available on the Pycom devices.
The standard Python libraries have been "micro-ified" to fit in with the philosophy of MicroPython. They provide the core functionality of that module and are intended to be a drop-in replacement for the standard Python library.
{% hint style="info" %}
Some modules are available by an u-name, and also by their non-u-name. The non-u-name can be overridden by a file of that name in your package path. For example, `import json` will first search for a file `json.py` or directory `json` and load that package if it's found. If nothing is found, it will fallback to loading the built-in `ujson` module.
{% endhint %}

View File

@@ -1,86 +0,0 @@
# \_thread
This module provides low-level primitives for working with multiple threads \(also called light-weight processes or tasks\) — multiple threads of control sharing their global data space. For synchronisation, simple locks \(also called mutexes or binary semaphores\) are provided.
When a thread specific error occurs a `RuntimeError` exception is raised.
## Quick Usage Example
```python
import _thread
import time
def th_func(delay, id):
while True:
time.sleep(delay)
print('Running thread %d' % id)
for i in range(2):
_thread.start_new_thread(th_func, (i + 1, i))
```
## Methods
#### \_thread.start\_new\_thread\(function, args\[, kwargs\]\)
Start a new thread and return its identifier. The thread executes the function with the argument list args \(which must be a tuple\). The optional `kwargs` argument specifies a dictionary of keyword arguments. When the function returns, the thread silently exits. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits \(but other threads continue to run\).
#### \_thread.exit\(\)
Raise the `SystemExit` exception. When not caught, this will cause the thread to exit silently.
#### \_thread.allocate\_lock\(\)
Return a new lock object. Methods of locks are described below. The lock is initially unlocked.
#### \_thread.get\_ident\(\)
Return the `thread identifier` of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.
#### \_thread.stack\_size\(\[size\]\)
Return the thread stack size \(in bytes\) used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be `0` \(use platform or configured default\) or a positive integer value of at least `4096` \(4KiB\). 4KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself.
## Objects
#### \_thread.LockType
This is the type of lock objects.
## class Lock
Used for synchronisation between threads
### Methods
Lock objects have the following methods:
#### lock.acquire\(waitflag=1, timeout=-1\)
Without any optional argument, this method acquires the lock unconditionally, if necessary waiting until it is released by another thread \(only one thread at a time can acquire a lock — thats their reason for existence\).
If the integer `waitflag` argument is present, the action depends on its value: if it is zero, the lock is only acquired if it can be acquired immediately without waiting, while if it is nonzero, the lock is acquired unconditionally as above.
If the floating-point timeout argument is present and positive, it specifies the maximum wait time in seconds before returning. A negative timeout argument specifies an unbounded wait. You cannot specify a timeout if `waitflag` is zero.
The return value is `True` if the lock is acquired successfully, `False` if not.
#### lock.release\(\)
Releases the lock. The lock must have been acquired earlier, but not necessarily by the same thread.
#### lock.locked\(\)
Return the status of the lock: `True` if it has been acquired by some thread, `False` if not.
In addition to these methods, lock objects can also be used via the with statement, e.g.:
```python
import _thread
a_lock = _thread.allocate_lock()
with a_lock:
print("a_lock is locked while this executes")
```

View File

@@ -1,22 +0,0 @@
# array
See [Python array](https://docs.python.org/3/library/array.html) for more information.
Supported format codes: `b, B, h, H, i, I, l, L, q, Q, f, d` \(the latter 2 depending on the floating-point support\).
## Classes
#### class array.array\(typecode\[, iterable\]\)
Create array with elements of given type. Initial contents of the array are given by an iterable. If it is not provided, an empty array is created.
## Methods
#### array.append\(val\)
Append new element to the end of array, growing it.
#### array.extend\(iterable\)
Append new elements as contained in an iterable to the end of array, growing it.

View File

@@ -1,126 +0,0 @@
# Builtin
All builtin functions are described here. They are also available via [builtins](builtin.md) module.
abs\(\)
all\(\)
any\(\)
bin\(\)
class bool
class bytearray
class bytes
callable\(\)
chr\(\)
class method\(\)
compile\(\)
class complex
class dict
dir\(\)
divmod\(\)
enumerate\(\)
eval\(\)
exec\(\)
filter\(\)
class float
class frozenset
getattr\(\)
globals\(\)
hasattr\(\)
hash\(\)
hex\(\)
id\(\)
input\(\)
class int
isinstance\(\)
issubclass\(\)
iter\(\)
len\(\)
class list
locals\(\)
map\(\)
max\(\)
class memoryview
min\(\)
next\(\)
class object
oct\(\)
open\(\)
ord\(\)
pow\(\)
print\(\)
property\(\)
range\(\)
repr\(\)
reversed\(\)
round\(\)
class set
setattr\(\)
sorted\(\)
staticmethod\(\)
class str
sum\(\)
super\(\)
class tuple
type\(\)
zip\(\)

View File

@@ -1,47 +0,0 @@
# cmath
The `cmath` module provides some basic mathematical functions for working with complex numbers. Floating point support required for this module.
## Methods
#### cmath.cos\(z\)
Return the cosine of `z`.
#### cmath.exp\(z\)
Return the exponential of `z`.
#### cmath.log\(z\)
Return the natural logarithm of `z`. The branch cut is along the negative real axis.
#### cmath.log10\(z\)
Return the base-10 logarithm of `z`. The branch cut is along the negative real axis.
#### cmath.phase\(z\)
Returns the phase of the number `z`, in the range \(-pi, +pi\).
#### cmath.polar\(z\)
Returns, as a tuple, the polar form of `z`.
#### cmath.rect\(r, phi\)
Returns the complex number with modulus `r` and phase `phi`.
#### cmath.sin\(z\)
Return the sine of `z`.
#### cmath.sqrt\(z\)
Return the square-root of `z`.
## Constants
* `cmath.e`: Base of the natural logarithm
* `cmath.pi`: The ratio of a circles circumference to its diameter

View File

@@ -1,24 +0,0 @@
# gc
## Methods
#### gc.enable\(\)
Enable automatic garbage collection.
#### gc.disable\(\)
Disable automatic garbage collection. Heap memory can still be allocated, and garbage collection can still be initiated manually using `gc.collect()`.
#### gc.collect\(\)
Run a garbage collection.
#### gc.mem\_alloc\(\)
Return the number of bytes of heap RAM that are allocated.
#### gc.mem\_free\(\)
Return the number of bytes of available heap RAM.

View File

@@ -1,163 +0,0 @@
# math
The math module provides some basic mathematical functions for working with floating-point numbers. Floating point support required for this module.
## Methods
#### math.acos\(x\)
Return the inverse cosine of `x`.
#### math.acosh\(x\)
Return the inverse hyperbolic cosine of `x`.
#### math.asin\(x\)
Return the inverse sine of `x`.
#### math.asinh\(x\)
Return the inverse hyperbolic sine of `x`.
#### math.atan\(x\)
Return the inverse tangent of `x`.
#### math.atan2\(y, x\)
Return the principal value of the inverse tangent of `y/x`.
#### math.atanh\(x\)
Return the inverse hyperbolic tangent of `x`.
#### math.ceil\(x\)
Return an integer, being x rounded towards positive infinity.
#### math.copysign\(x, y\)
Return x with the sign of `y`.
#### math.cos\(x\)
Return the cosine of `x`.
#### math.cosh\(x\)
Return the hyperbolic cosine of `x`.
#### math.degrees\(x\)
Return radians `x` converted to degrees.
#### math.erf\(x\)
Return the error function of `x`.
#### math.erfc\(x\)
Return the complementary error function of `x`.
#### math.exp\(x\)
Return the exponential of `x`.
#### math.expm1\(x\)
Return `exp(x) - 1`.
#### math.fabs\(x\)
Return the absolute value of `x`.
#### math.floor\(x\)
Return an integer, being `x` rounded towards negative infinity.
#### math.fmod\(x, y\)
Return the remainder of `x/y`.
#### math.frexp\(x\)
Decomposes a floating-point number into its mantissa and exponent. The returned value is the tuple `(m, e)` such that `x == m * 2**e` exactly. If `x == 0` then the function returns `(0.0, 0)`, otherwise the relation `0.5 <= abs(m) < 1` holds.
#### math.gamma\(x\)
Return the gamma function of `x`.
#### math.isfinite\(x\)
Return `True` if `x` is finite.
#### math.isinf\(x\)
Return `True` if `x` is infinite.
#### math.isnan\(x\)
Return `True` if `x` is not-a-number
#### math.ldexp\(x, exp\)
Return `x * (2**exp)`.
#### math.lgamma\(x\)
Return the natural logarithm of the gamma function of `x`.
#### math.log\(x\)
Return the natural logarithm of `x`.
#### math.log10\(x\)
Return the base-10 logarithm of `x`.
#### math.log2\(x\)
Return the base-2 logarithm of `x`.
#### math.modf\(x\)
Return a tuple of two floats, being the fractional and integral parts of `x`. Both return values have the same sign as `x`.
#### math.pow\(x, y\)
Returns `x` to the power of `y`.
#### math.radians\(x\)
Return degrees `x` converted to radians.
#### math.sin\(x\)
Return the sine of `x`.
#### math.sinh\(x\)
Return the hyperbolic sine of `x`.
#### math.sqrt\(x\)
Return the square root of `x`.
#### math.tan\(x\)
Return the tangent of `x`.
#### math.tanh\(x\)
Return the hyperbolic tangent of `x`.
#### math.trunc\(x\)
Return an integer, being `x` rounded towards `0`.
## Constants
* `math.e`: Base of the natural logarithm
* `math.pi`: The ratio of a circles circumference to its diameter

View File

@@ -1,59 +0,0 @@
# micropython
## Methods
#### micropython.alloc\_emergency\_exception\_buf\(size\)
Allocate size bytes of RAM for the emergency exception buffer \(a good size is around 100 bytes\). The buffer is used to create exceptions in cases when normal RAM allocation would fail \(eg within an interrupt handler\) and therefore give useful traceback information in these situations.
A good way to use this function is to place it at the start of a main script \(e.g. `boot.py` or `main.py`\) and then the emergency exception buffer will be active for all the code following it.
#### micropython.const\(expr\)
Used to declare that the expression is a constant so that the compile can optimise it. The use of this function should be as follows:
```python
from micropython import const
CONST_X = const(123)
CONST_Y = const(2 * CONST_X + 1)
```
Constants declared this way are still accessible as global variables from outside the module they are declared in. On the other hand, if a constant begins with an underscore then it is hidden, it is not available as a global variable, and does not take up any memory during execution.
This const function is recognised directly by the MicroPython parser and is provided as part of the `micropython` module mainly so that scripts can be written which run under both CPython and MicroPython, by following the above pattern.
#### micropython.opt\_level\(\[level\]\)
If `level` is given then this function sets the optimisation level for subsequent compilation of scripts, and returns `None`. Otherwise it returns the current optimisation level.
#### micropython.mem\_info\(\[verbose\]\)
Print information about currently used memory. If the `verbose` argument is given then extra information is printed.
The information that is printed is implementation dependent, but currently includes the amount of stack and heap used. In verbose mode it prints out the entire heap indicating which blocks are used and which are free.
#### micropython.qstr\_info\(\[verbose\]\)
Print information about currently interned strings. If the `verbose` argument is given then extra information is printed.
The information that is printed is implementation dependent, but currently includes the number of interned strings and the amount of RAM they use. In verbose mode it prints out the names of all RAM-interned strings.
#### micropython.stack\_use\(\)
Return an integer representing the current amount of stack that is being used. The absolute value of this is not particularly useful, rather it should be used to compute differences in stack usage at different points.
#### micropython.heap\_lock\(\)
#### micropython.heap\_unlock\(\)
Lock or unlock the heap. When locked no memory allocation can occur and a `MemoryError` will be raised if any heap allocation is attempted.
These functions can be nested, i.e. `heap_lock()` can be called multiple times in a row and the lock-depth will increase, and then `heap_unlock()` must be called the same number of times to make the heap available again.
#### micropython.kbd\_intr\(chr\)
Set the character that will raise a `KeyboardInterrupt` exception. By default this is set to 3 during script execution, corresponding to `Ctrl-C`. Passing `-1` to this function will disable capture of `Ctrl-C`, and passing `3` will restore it.
This function can be used to prevent the capturing of `Ctrl-C` on the incoming stream of characters that is usually used for the REPL, in case that stream is used for other purposes.

View File

@@ -1,49 +0,0 @@
# select
This module provides functions to wait for events on streams \(select streams which are ready for operations\).
## Pyboard specifics
Polling is an efficient way of waiting for read/write activity on multiple objects. Current objects that support polling are: `pyb.UART`, `pyb.USB_VCP`.
## Methods
#### select.poll\(\)
Create an instance of the `Poll` class.
#### select.select\(rlist, wlist, xlist\[, timeout\]\)
Wait for activity on a set of objects.
This function is provided for compatibility and is not efficient. Usage of `Poll` is recommended instead.
## class Poll
### Methods
#### poll.register\(obj\[, eventmask\]\)
Register `obj` for polling. `eventmask` is logical OR of:
* `select.POLLIN` - data available for reading
* `select.POLLOUT` - more data can be written
* `select.POLLERR` - error occurred
* `select.POLLHUP` - end of stream/connection termination detected
`eventmask` defaults to `select.POLLIN | select.POLLOUT`.
#### poll.unregister\(obj\)
Unregister `obj` from polling.
#### poll.modify\(obj, eventmask\)
Modify the `eventmask` for `obj`.
#### poll.poll\(\[timeout\]\)
Wait for at least one of the registered objects to become ready. Returns 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 a platform and version, so dont assume that its size is 2. In case of timeout, an empty list is returned.
Timeout is in milliseconds.

View File

@@ -1,62 +0,0 @@
# sys
## Methods
#### sys.exit\(retval=0\)
Terminate current program with a given exit code. Underlyingly, this function raise as `SystemExit` exception. If an argument is given, its value given as an argument to `SystemExit`.
#### sys.print\_exception\(exc, file=sys.stdout\)
Print exception with a traceback to a file-like object file \(or `sys.stdout` by default\).
{% hint style="info" %}
**Difference to 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`.
{% endhint %}
## Constants
* `sys.argv`: A mutable list of arguments the current program was started with.
* `sys.byteorder`: The byte order of the system \("little" or "big"\).
* `sys.implementation`: Object with information about the current Python implementation. For MicroPython, it has following attributes:
* _name_ - string "micropython"
* _version_ - tuple \(major, minor, micro\), e.g. \(1, 7, 0\)
This object is the recommended way to distinguish MicroPython from other Python implementations \(note that it still may not exist in the very minimal ports\).
{% hint style="info" %}
**Difference to CPython**
CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython.
{% endhint %}
* `sys.maxsize`: Maximum value which a native integer type can hold on the current platform, or maximum value representable by MicroPython integer type, if its smaller than platform max value \(that is the case for MicroPython ports without long int support\).
This attribute is useful for detecting "bitness" of a platform \(32-bit vs 64-bit, etc.\). Its recommended to not compare this attribute to some value directly, but instead count number of bits in it:
```python
bits = 0
v = sys.maxsize
while v:
bits += 1
v >>= 1
if bits > 32:
# 64-bit (or more) platform
else:
# 32-bit (or less) platform
# Note that on 32-bit platform, value of bits may be less than 32
# (e.g. 31) due to peculiarities described above, so use "> 16",
# "> 32", "> 64" style of comparisons.
```
* `sys.modules`: Dictionary of loaded modules. On some ports, it may not include builtin modules.
* `sys.path`: A mutable list of directories to search for imported modules.
* `sys.platform`: The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. `linux`. For baremetal ports, it is an identifier of a board, e.g. `pyboard` for the original MicroPython reference board. It thus can be used to distinguish one board from another. If you need to check whether your program runs on MicroPython \(vs other Python implementation\), use `sys.implementation` instead.
* `sys.stderr`: Standard error stream.
* `sys.stdin`: Standard input stream.
* `sys.stdout`: Standard output stream.
* `sys.version`: Python language version that this implementation conforms to, as a string.
* `sys.version_info`: Python language version that this implementation conforms to, as a tuple of ints.

View File

@@ -1,28 +0,0 @@
# ubinascii
This module implements conversions between binary data and various encodings of it in ASCII form \(in both directions\).
## Methods
#### ubinascii.hexlify\(data\[, sep\]\)
Convert binary data to hexadecimal representation. Returns bytes string.
{% hint style="info" %}
**Difference to CPython**
If additional argument, `sep` is supplied, it is used as a separator between hexadecimal values.
{% endhint %}
#### ubinascii.unhexlify\(data\)
Convert hexadecimal data to binary representation. Returns bytes string. \(i.e. inverse of `hexlify`\)
#### ubinascii.a2b\_base64\(data\)
Convert Base64-encoded data to binary representation. Returns bytes string.
#### ubinascii.b2a\_base64\(data\)
Encode binary data in Base64 format. Returns string.

View File

@@ -1,22 +0,0 @@
# ucrypto
This module provides native support for cryptographic algorithms. Its loosely based on PyCrypto.
## Classes
* [class AES](../pycom/aes.md) - Advanced Encryption Standard
## **Methods**
#### crypto.getrandbits\(bits\)
Returns a bytes object filled with random bits obtained from the hardware random number generator.
According to the **ESP32 Technical Reference Manual**, such bits "... can be used as the basis for cryptographical operations". "These true random numbers are generated based on the noise in the Wi-Fi/BT RF system. When Wi-Fi and BT are disabled, the random number generator will give out pseudo-random numbers."
The parameter `bits` is rounded upwards to the nearest multiple of 32 bits.
{% hint style="danger" %}
Cryptography is not a trivial business. Doing things the wrong way could quickly result in decreased or no security. Please document yourself in the subject if you are depending on encryption to secure important information.
{% endhint %}

View File

@@ -1,138 +0,0 @@
# uctypes
This module implements "foreign data interface" for MicroPython. The idea behind it is similar to CPythons `ctypes` modules, but the actual API is different, streamlined and optimised 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.
{% hint style="info" %}
Module ustruct Standard Python way to access binary data structures \(doesnt scale well to large and complex structures\).
{% endhint %}
## 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 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:
```python
"field_name": uctypes.UINT32 | 0
```
In other words, value is scalar type identifier OR-ed with field offset \(in bytes\) from the start of the structure.
* Recursive structures:
```python
"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\).
* Arrays of Primitive Types:
```python
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
```
I.e. value is a 2-tuple, first element of which is ARRAY flag OR-ed with offset, and second is scalar element type OR-ed number of elements in array.
* Arrays of Aggregate Types:
```python
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}),
```
I.e. value is a 3-tuple, first element of which is ARRAY flag OR-ed with offset, second is a number of elements in array, and third is descriptor of element type.
* Pointer to a primitive type:
```python
"ptr": (uctypes.PTR | 0, uctypes.UINT8),
```
I.e. value is a 2-tuple, first element of which is PTR flag OR-ed with offset, and second is scalar element type.
* Pointer to an aggregate type:
```python
"ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}),
```
I.e. value is a 2-tuple, first element of which is PTR flag OR-ed with offset, second is descriptor of type pointed to.
* Bitfields:
```python
"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"\), OR-ed with offset for scalar value containing the bitfield, and further OR-ed 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, its 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 normalised numbering described above.
## Module Contents
#### class uctypes.struct\(addr, descriptor, layout\_type=NATIVE\)
Instantiate a "foreign data structure" object based on structure address in memory, descriptor \(encoded as a dictionary\), and layout type \(see below\).
#### uctypes.LITTLE\_ENDIAN
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\).
#### uctypes.BIG\_ENDIAN
Layout type for a big-endian packed structure.
#### uctypes.NATIVE
Layout type for a native structure - with data endianness and alignment conforming to the ABI of the system on which MicroPython runs.
#### uctypes.sizeof\(struct\)
Return size of data structure in bytes. Argument can be either structure class or specific instantiated structure object \(or its aggregate field\).
#### uctypes.addressof\(obj\)
Return address of an object. Argument should be bytes, `bytearray` or other object supporting buffer protocol \(and address of this buffer is what actually returned\).
#### uctypes.bytes\_at\(addr, size\)
Capture memory at the given address and size as bytes object. As bytes object is immutable, memory is actually duplicated and copied into bytes object, so if memory contents change later, created object retains original value.
#### uctypes.bytearray\_at\(addr, size\)
Capture memory at the given address and size as `bytearray` object. Unlike `bytes_at()` function above, memory is captured by reference, so it can be both written too, and you will access current value at the given memory address.
## 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 following sources:
* Predefined address, when accessing hardware registers on a baremetal system. Lookup these addresses in datasheet for a particular MCU/SoC.
* As a return value from a call to some FFI \(Foreign Function Interface\) function.
* 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 a file or network socket\).
## Structure objects
Structure objects allow accessing individual fields using standard dot 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 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 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 dereference, 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 \(its even possible to define 2 parallel layouts - one for normal usage, and a restricted one to use when memory allocation is prohibited\).

View File

@@ -1,44 +0,0 @@
# uhashlib
This module implements binary data hashing algorithms. MD5 and SHA are supported. By limitations in the hardware, only one active hashing operation is supported at a time.
## Constructors
#### class uhashlib.md5\(\[data\]\)
Create a MD5 hasher object and optionally feed data into it.
#### class uhashlib.sha1\(\[data\]\)
Create a SHA-1 hasher object and optionally feed data into it.
#### class uhashlib.sha224\(\[data\]\)
Create a SHA-224 hasher object and optionally feed data into it.
#### class uhashlib.sha256\(\[data\]\)
Create a SHA-256 hasher object and optionally feed data into it.
#### class uhashlib.sha384\(\[data\]\)
Create a SHA-384 hasher object and optionally feed data into it.
#### class uhashlib.sha512\(\[data\]\)
Create a SHA-512 hasher object and optionally feed data into it.
## Methods
#### hash.update\(data\)
Feed more binary data into hash.
#### hash.digest\(\)
Return hash for all data passed through hash, as a bytes object. After this method is called, more data cannot be fed into hash any longer.
#### hash.hexdigest\(\)
This method is NOT implemented. Use `ubinascii.hexlify(hash.digest())` to achieve a similar effect.

View File

@@ -1,18 +0,0 @@
# ujson
This modules allows to convert between Python objects and the JSON data format.
## Methods
#### ujson.dumps\(obj\)
Return `obj` represented as a JSON string.
#### ujson.loads\(str\)
Parse the JSON `str` and return an object. Raises `ValueError` if the string is not correctly formed.
#### ujson.load\(fp\)
Parse contents of `fp` \(a `.read()`-supporting file-like object containing a JSON document\). Raises `ValueError` if the content is not correctly formed.

View File

@@ -1,101 +0,0 @@
# uos
The `uos` module contains functions for filesystem access and `urandom` function.
## Port Specifics
The filesystem has `/` as the root directory and the available physical drives are accessible from here. They are currently:
* `/flash` the internal flash filesystem
* `/sd` the SD card \(if it exists\)
## Methods
#### uos.uname\(\)
Return information about the system, firmware release version, and MicroPython interpreter version.
#### uos.chdir\(path\)
Change current directory.
#### uos.getcwd\(\)
Get the current directory.
#### uos.listdir\(\[dir\]\)
With no argument, list the current directory. Otherwise list the given directory.
#### uos.mkdir\(path\)
Create a new directory.
#### uos.remove\(path\)
Remove a file.
#### uos.rmdir\(path\)
Remove a directory.
#### uos.rename\(old\_path, new\_path\)
Rename a file.
#### uos.stat\(path\)
Get the status of a file or directory.
The return value is a tuple with the following 10 values, in order:
* `st_mode`: protection bits.
* `st_ino`: `inode` number. \(not implemented, returns 0\)
* `st_dev`: device. \(not implemented, returns 0\)
* `st_nlink`: number of hard links. \(not implemented, returns 0\)
* `st_uid`: user id of owner. \(not implemented, returns 0\)
* `st_gid`: group id of owner. \(not implemented, returns 0\)
* `st_size`: size of file in bytes.
* `st_atime`: time of most recent access.
* `st_mtime`: time of most recent content modification.
* `st_ctime`: time of most recent metadata change.
#### uos.getfree\(path\)
Returns the free space \(in KiB\) in the drive specified by path.
#### uos.sync\(\)
Sync all filesystems.
#### uos.urandom\(n\)
Return a bytes object with n random bytes.
#### uos.unlink\(path\)
Alias for the `remove()` method.
#### uos.mount\(block\_device, mount\_point, \* , readonly=False\)
Mounts a block device \(like an SD object\) in the specified mount point. Example:
```python
os.mount(sd, '/sd')
uos.unmount(path)
```
Unmounts a previously mounted block device from the given path.
#### uos.mkfs\(block\_device or path\)
Formats the specified path, must be either `/flash` or `/sd`. A block device can also be passed like an SD object before being mounted.
#### uos.dupterm\(stream\_object\)
Duplicate the terminal \(the REPL\) on the passed stream-like object. The given object must at least implement the `read()` and `write()` methods.
## Constants
* `uos.sep`: Separation character used in paths

View File

@@ -1,57 +0,0 @@
# ure
This module implements regular expression operations. Regular expression syntax supported is a subset of CPython re module \(and actually is a subset of POSIX extended regular expressions\).
Supported operators are:
`.` Match any character. `[]` Match set of characters. Individual characters and ranges are supported.
```text
^
$
?
*
+
??
*?
+?
```
Counted repetitions `({m,n})`, more advanced assertions, named groups, etc. are not supported.
## Methods
#### ure.compile\(regex\)
Compile regular expression, return `regex object`.
#### ure.match\(regex, string\)
Match regex against `string`. Match always happens from starting position in a string.
#### ure.search\(regex, string\)
Search regex in a string. Unlike match, this will search string for first position which matches regex \(which still may be 0 if regex is anchored\).
#### ure.DEBUG
Flag value, display debug information about compiled expression.
## Regex objects
Compiled regular expression. Instances of this class are created using `ure.compile()`.
#### regex.match\(string\)
#### regex.search\(string\)
#### regex.split\(string, max\_split=-1\)
## Match objects
Match objects as returned by `match()` and `search()` methods.
#### match.group\(\[index\]\)
Only numeric groups are supported.

View File

@@ -1,148 +0,0 @@
# usocket
This module provides access to the BSD socket interface.
See corresponding CPython module for comparison.
## Socket Address Format\(s\)
Functions below which expect a network address, accept it in the format of `(ipv4_address, port)`, where `ipv4_address` is a string with dot-notation numeric IPv4 address, e.g. `8.8.8.8`, and port is integer port number in the range 1-65535. Note the domain names are not accepted as `ipv4_address`, they should be resolved first using `socket.getaddrinfo()`.
## Methods
#### socket.socket\(socket.AF\_INET, socket.SOCK\_STREAM, socket.IPPROTO\_TCP\)
Create a new socket using the given address family, socket type and protocol number.
#### socket.getaddrinfo\(host, port\)
Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. The list of 5-tuples has following structure:
`(family, type, proto, canonname, sockaddr)` The following example shows how to connect to a given url:
```python
s = socket.socket()
s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][-1])
```
## Exceptions
`socket.error`, `socket.timeout`
## Constants
* Family types: `socket.AF_INET`, `socket.AF_LORA`
* Socket types: `socket.SOCK_STREAM`, `socket.SOCK_DGRAM`, `socket.SOCK_RAW`
* Socket protocols: `socket.IPPROTO_UDP`, `socket.IPPROTO_TCP`
* Socket options layers: `socket.SOL_SOCKET`, `socket.SOL_LORA`, `socket.SOL_SIGFOX`
* IP socket options: `socket.SO_REUSEADDR`
* LoRa socket options: `socket.SO_CONFIRMED`, `socket.SO_DR`
* Sigfox socket options: `socket.SO_RX`, `socket.SO_TX_REPEAT`, `socket.SO_OOB`, `socket.SO_BIT`
## class Socket
### Methods
#### socket.close\(\)
Mark the socket closed. Once that happens, all future operations on the socket object will fail. The remote end will receive no more data \(after queued data is flushed\).
Sockets are automatically closed when they are garbage-collected, but it is recommended to `close()` them explicitly, or to use a with statement around them.
#### socket.bind\(address\)
Bind the `socket` to `address`. The socket must not already be bound. The `address` parameter must be a tuple containing the IP address and the port.
{% hint style="info" %}
In the case of LoRa sockets, the address parameter is simply an integer with the port number, for instance: `s.bind(1)`
{% endhint %}
#### socket.listen\(\[backlog\]\)
Enable a server to accept connections. If backlog is specified, it must be at least 0 \(if its lower, it will be set to 0\); and specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.
#### socket.accept\(\)
Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair `(conn, address)` where `conn` is a new socket object usable to send and receive data on the connection, and `address` is the address bound to the socket on the other end of the connection.
#### socket.connect\(address\)
Connect to a remote socket at `address`.
#### socket.send\(bytes\)
Send data to the socket. The socket must be connected to a remote socket.
#### socket.sendall\(bytes\)
Alias of `socket.send(bytes)`.
#### socket.recv\(bufsize\)
Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by `bufsize`.
#### socket.sendto\(bytes, address\)
Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address.
#### socket.recvfrom\(bufsize\)
Receive data from the socket. The return value is a pair `(bytes, address)` where `bytes` is a bytes object representing the data received and `address` is the address of the socket sending the data.
#### socket.setsockopt\(level, optname, value\)
Set the value of the given socket option. The needed symbolic constants are defined in the socket module \(`SO_*` etc.\). The value can be an integer or a bytes-like object representing a buffer.
#### socket.settimeout\(value\)
Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or `None`. If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.
#### socket.setblocking\(flag\)
Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode.
This method is a shorthand for certain `settimeout()` calls:
```python
sock.setblocking(True) is equivalent to sock.settimeout(None)
sock.setblocking(False) is equivalent to sock.settimeout(0.0)
```
#### socket.makefile\(mode='rb'\)
Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile\(\). The support is limited to binary modes only \(`rb` and `wb`\). CPythons arguments: `encoding`, `errors`, and `newline` are not supported.
The socket must be in blocking mode; it can have a timeout, but the file objects internal buffer may end up in a inconsistent state if a timeout occurs.
{% hint style="info" %}
**Difference to CPython**
Closing the file object returned by `makefile()` **WILL** close the original socket as well.
{% endhint %}
#### socket.read\(size\)
Read up to size bytes from the socket. Return a bytes object. If `size` is not given, it behaves just like [`socket.readall()`](usocket.md#socket-readall), see below.
#### socket.readall\(\)
Read all data available from the socket until EOF. This function will not return until the socket is closed.
#### socket.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.
Return value: number of bytes read and stored into `buf`.
#### socket.readline\(\)
Read a line, ending in a newline character.
Return value: the line read.
#### socket.write\(buf\)
Write the buffer of bytes to the socket.
Return value: number of bytes written.

View File

@@ -1,40 +0,0 @@
# ussl
This module provides access to Transport Layer Security \(often known as "Secure Sockets Layer"\) encryption and peer authentication facilities for network sockets, both client-side and server-side.
## Methods
#### ssl.wrap\_socket\(sock, keyfile=None, certfile=None, server\_side=False, cert\_reqs=CERT\_NONE, ca\_certs=None\)
Takes an instance `sock` of `socket.socket`, and returns an instance of ssl.SSLSocket, a subtype of `socket.socket`, which wraps the underlying socket in an SSL context. Example:
```python
import socket
import ssl
s = socket.socket()
ss = ssl.wrap_socket(s)
ss.connect(socket.getaddrinfo('www.google.com', 443)[0][-1])
```
Certificates must be used in order to validate the other side of the connection, and also to authenticate ourselves with the other end. Such certificates must be stored as files using the FTP server, and they must be placed in specific paths with specific names.
For instance, to connect to the Blynk servers using certificates, take the file `ca.pem` located in the `blynk` examples folder and put it in `/flash/cert/`. Then do:
```python
import socket
import ssl
s = socket.socket()
ss = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='/flash/cert/ca.pem')
ss.connect(socket.getaddrinfo('cloud.blynk.cc', 8441)[0][-1])
```
SSL sockets inherit all methods and from the standard sockets, see the `usocket` module.
## Exceptions
* `ssl.SSLError`
## Constants
* `ssl.CERT_NONE`, `ssl.CERT_OPTIONAL`, `ssl.CERT_REQUIRED`: Supported values in `cert_reqs`

View File

@@ -1,30 +0,0 @@
# ustruct
See Python [struct](https://docs.python.org/3/library/struct.html) for more information.
Supported size/byte order prefixes: `@, <, >, !`.
Supported format codes: `b, B, h, H, i, I, l, L, q, Q, s, P, f, d` \(the latter 2 depending on the floating-point support\).
## Methods
#### ustruct.calcsize\(fmt\)
Return the number of bytes needed to store the given `fmt`.
#### ustruct.pack\(fmt, v1, v2, ...\)
Pack the values `v1, v2, ...` according to the format string `fmt`. The return value is a bytes object encoding the values.
#### ustruct.pack\_into\(fmt, buffer, offset, v1, v2, ...\)
Pack the values `v1, v2, ...` according to the format string `fmt` into a buffer starting at `offset`. `offset` may be negative to count from the end of buffer.
#### ustruct.unpack\(fmt, data\)
Unpack from the `data` according to the format string `fmt`. The return value is a tuple of the unpacked values.
#### ustruct.unpack\_from\(fmt, data, offset=0\)
Unpack from the `data` starting at `offset` according to the format string `fmt`. `offset` may be negative to count from the end of buffer. The return value is a tuple of the unpacked values.

View File

@@ -1,87 +0,0 @@
# utime
The `utime` module provides functions for getting the current time and date, measuring time intervals, and for delays.
**Time Epoch**: Pycoms ESP32 port uses standard for POSIX systems epoch of `1970-01-01 00:00:00 UTC`.
## Maintaining actual calendar date/time
This requires a Real Time Clock \(RTC\). On systems with underlying OS \(including some RTOS\), an RTC may be implicit. Setting and maintaining actual calendar time is responsibility of OS/RTOS and is done outside of MicroPython, it just uses OS API to query date/time. On baremetal ports however system time depends on `machine.RTC()` object. The current calendar time may be set using `machine.RTC().datetime(tuple)` function, and maintained by following means:
* By a backup battery \(which may be an additional, optional component for a particular board\).
* Using networked time protocol \(requires setup by a port/user\).
* Set manually by a user on each power-up \(many boards then maintain RTC time across hard resets, though some may require setting it again in such case\).
If actual calendar time is not maintained with a system/MicroPython RTC, functions below which require reference to current absolute time may behave not as expected.
## Methods
#### utime.gmtime\(\[secs\]\)
Convert a time expressed in seconds since the Epoch \(see above\) into an 8-tuple which contains: `(year, month, mday, hour, minute, second, weekday, yearday)` If `secs` is not provided or `None`, then the current time from the RTC is used.
* `year` includes the century \(for example 2014\).
* `month` is 1-12
* `mday` is 1-31
* `hour` is 0-23
* `minute` is 0-59
* `second` is 0-59
* `weekday` is 0-6 for Mon-Sun
* `yearday` is 1-366
#### utime.localtime\(\[secs\]\)
Like `gmtime()` but converts to local time. If `secs` is not provided or `None`, the current time from the RTC is used.
#### utime.mktime\(\)
This is inverse function of `localtime`. Its argument is a full 8-tuple which expresses a time as per `localtime`. It returns an integer which is the number of seconds since `Jan 1, 2000`.
#### utime.sleep\(seconds\)
Sleep for the given number of `seconds`. `seconds` can be a floating-point number to sleep for a fractional number of seconds. Note that other MicroPython ports may not accept floating-point argument, for compatibility with them use `sleep_ms()` and `sleep_us()` functions.
#### utime.sleep\_ms\(ms\)
Delay for given number of milliseconds, should be positive or 0.
#### utime.sleep\_us\(us\)
Delay for given number of microseconds, should be positive or 0
#### utime.ticks\_ms\(\)
Returns uptime, in milliseconds.
#### utime.ticks\_us\(\)
Just like `ticks_ms` above, but in microseconds.
#### utime.ticks\_cpu\(\)
Same as `ticks_us`, but faster.
#### utime.ticks\_diff\(old, new\)
Measure period between consecutive calls to `ticks_ms()`, `ticks_us()`, or `ticks_cpu()`. The value returned by these functions may wrap around at any time, so directly subtracting them is not supported. `ticks_diff()` should be used instead. "old" value should actually precede "new" value in time, or result is undefined. This function should not be used to measure arbitrarily long periods of time \(because `ticks_*()` functions wrap around and usually would have short period\). The expected usage pattern is implementing event polling with timeout:
```python
# Wait for GPIO pin to be asserted, but at most 500us
start = time.ticks_us()
while pin.value() == 0:
if time.ticks_diff(start, time.ticks_us()) > 500:
raise TimeoutError
```
#### utime.time\(\)
Returns the number of seconds, as an integer, since the Epoch, assuming that underlying RTC is set. If an RTC is not set, this function returns number of seconds since power up or reset\). If you want to develop portable MicroPython application, you should not rely on this function to provide higher than second precision. If you need higher precision, use `ticks_ms()` and `ticks_us()` functions, if you need calendar time, `localtime()` without an argument is a better choice.
#### utime.timezone\(\[secs\]\)
Set or get the timezone offset, in seconds. If `secs` is not provided, it returns the current value.
{% hint style="info" %}
In MicroPython, `time.timezone` works the opposite way to Python. In [Python](https://docs.python.org/3/library/time.html#time.timezone), to get the local time, you write `local_time = utc - timezone`, while in MicroPython it is `local_time = utc + timezone`.
{% endhint %}