API

exception AuthenticationError

Bases: BelayException

Invalid password or similar.

exception ConnectionLost

Bases: BelayException

Lost connection to device.

class Device(*args, **kwargs)

Bases: Registry

Belay interface into a micropython device.

implementation

Implementation details of device.

Type:

Implementation

MAX_CMD_HISTORY_LEN = 1000
clear: Callable[[], None] = <bound method _DictMixin.clear of <Device: []>>
close() None

Close the connection to device.

get: Callable[[...], Type] = <bound method _DictMixin.get of <Device: []>>
items: Callable = <bound method _DictMixin.items of <Device: []>>
keys: Callable[[], KeysView] = <bound method _DictMixin.keys of <Device: []>>
reconnect(attempts: int | None = None) None

Reconnect to the device and replay the command history.

Parameters:

attempts (int) -- Number of times to attempt to connect to board with a 1 second delay in-between. If None, defaults to whatever value was supplied to init. If init value is 0, then defaults to 1.

static setup(f, *, minify=True, register=True, record=True)

Decorator that executes function's body in a global-context on-device when called.

Function arguments are also set in the global context.

Can either be used as a staticmethod @Device.setup for marking methods in a subclass of Device, or as a standard method @device.setup for marking functions to a specific Device instance.

Parameters:
  • f (Callable) -- Function to decorate. Can only accept and return python literals.

  • minify (bool) -- Minify cmd code prior to sending. Defaults to True.

  • register (bool) -- Assign an attribute to self.setup with same name as f. Defaults to True.

  • record (bool) -- Each invocation of the executer is recorded for playback upon reconnect. Defaults to True.

  • autoinit (bool) -- Automatically invokes decorated functions at the end of object __init__. Methods will be executed in order-registered. Defaults to False.

sync(folder: str | Path, dst: str = '/', keep: None | list | str | bool = None, ignore: None | list | str = None, minify: bool = True, mpy_cross_binary: str | Path | None = None, progress_update=None) None

Sync a local directory to the remote filesystem.

For each local file, check the remote file's hash, and transfer if they differ. If a file/folder exists on the remote filesystem that doesn't exist in the local folder, then delete it (unless it's in keep).

Parameters:
  • folder (str, Path) -- Single file or directory of files to sync to the root of the board's filesystem.

  • dst (str) -- Destination directory on device. Defaults to unpacking folder to root.

  • keep (None | str | list | bool) -- Do NOT delete these file(s) on-device if not present in folder. If true, don't delete any files on device. If false, delete all unsynced files (same as passing []). If dst is None, defaults to ["boot.py", "webrepl_cfg.py", "lib"].

  • ignore (None | str | list) -- Git's wildmatch patterns to NOT sync to the device. Defaults to ["*.pyc", "__pycache__", ".DS_Store", ".pytest_cache"].

  • minify (bool) -- Minify python files prior to syncing. Defaults to True.

  • mpy_cross_binary (Union[str, Path, None]) -- Path to mpy-cross binary. If provided, .py will automatically be compiled. Takes precedence over minifying.

  • progress_update -- Partial for rich.progress.Progress.update(task_id,...) to update with sync status.

sync_dependencies(package: module | str, *subfolders: str | Path, dst='/lib', **kwargs)

Convenience method for syncing dependencies bundled with package.

If using Belay's package manager feature, set dependencies_path to a folder inside your python package (e.g. dependencies_path="mypackage/dependencies").

The following example will sync all the files/folders in mypackage/dependencies/main to device's /lib.

import mypackage

device.sync_package(mypackage, "dependencies/main")

For intended use, sync_dependencies should be only be called once. Multiple invocations overwrite/delete previous calls' contents.

# Good
device.sync_package(mypackage, "dependencies/main", "dependencies/dev")

# Bad (deletes on-device files from "dependencies/main")
device.sync_package(mypackage, "dependencies/main")
device.sync_package(mypackage, "dependencies/dev")
Parameters:
  • package (Union[ModuleType, str]) -- Either the imported package or the name of a package that contains the data we would like to sync.

  • *subfolders -- Subfolder(s) to combine and then sync to dst. Typically something like "dependencies/main"

  • dst (Union[str, Path]) -- On-device destination directory. Defaults to /lib.

  • **kwargs -- Passed along to Device.sync.

static task(f, *, minify=True, register=True, record=False)

Decorator that send code to device that executes when decorated function is called on-host.

Can either be used as a staticmethod @Device.task for marking methods in a subclass of Device, or as a standard method @device.task for marking functions to a specific Device instance.

Parameters:
  • f (Callable) -- Function to decorate. Can only accept and return python literals.

  • minify (bool) -- Minify cmd code prior to sending. Defaults to True.

  • register (bool) -- Assign an attribute to self.task with same name as f. Defaults to True.

  • record (bool) -- Each invocation of the executer is recorded for playback upon reconnect. Only recommended to be set to True for a setup-like function. Defaults to False.

static teardown(f, *, minify=True, register=True, record=True)

Decorator that executes function's body in a global-context on-device when device.close() is called.

Function arguments are also set in the global context.

Can either be used as a staticmethod @Device.teardown for marking methods in a subclass of Device, or as a standard method @device.teardown for marking functions to a specific Device instance.

Parameters:
  • f (Callable) -- Function to decorate. Can only accept and return python literals.

  • minify (bool) -- Minify cmd code prior to sending. Defaults to True.

  • register (bool) -- Assign an attribute to self.teardown with same name as f. Defaults to True.

  • record (bool) -- Each invocation of the executer is recorded for playback upon reconnect. Defaults to True.

static thread(f, *, minify=True, register=True, record=True)

Decorator that send code to device that spawns a thread when executed.

Can either be used as a staticmethod @Device.thread for marking methods in a subclass of Device, or as a standard method @device.thread for marking functions to a specific Device instance.

Parameters:
  • f (Callable) -- Function to decorate. Can only accept python literals as arguments.

  • minify (bool) -- Minify cmd code prior to sending. Defaults to True.

  • register (bool) -- Assign an attribute to self.thread with same name as f. Defaults to True.

  • record (bool) -- Each invocation of the executer is recorded for playback upon reconnect. Defaults to True.

values: Callable[[], ValuesView] = <bound method _DictMixin.values of <Device: []>>
exception FeatureUnavailableError

Bases: BelayException

Feature unavailable for your board's implementation.

class Implementation(name: str, version: Tuple[int, int, int], platform: str, emitters: Tuple[str])

Bases: object

Implementation dataclass detailing the device.

Parameters:
  • name (str) -- Type of python running on device. One of {"micropython", "circuitpython"}.

  • version (Tuple[int, int, int]) -- (major, minor, patch) Semantic versioning of device's firmware.

  • platform (str) -- Board identifier. May not be consistent from MicroPython to CircuitPython. e.g. The Pi Pico is "rp2" in MicroPython, but "RP2040" in CircuitPython.

  • emitters (tuple[str]) -- Tuple of available emitters on-device {"native", "viper"}.

emitters: Tuple[str]
name: str
platform: str
version: Tuple[int, int, int]
exception MaxHistoryLengthError

Bases: BelayException

Too many commands were given.

exception PyboardException

Bases: Exception

Uncaught exception from the device.

exception SpecialFunctionNameError

Bases: BelayException

Reserved function name that may impact Belay functionality.

Currently limited to:

  • Names that start and end with double underscore, __.

  • Names that start with _belay or __belay

list_devices() List[str]

Lists available device ports.

For example:

['/dev/cu.usbmodem1143401', '/dev/cu.usbmodem113101']
Returns:

Available devices identifiers.

Return type:

list[str]

minify(code: str) str

Minify python code.

Naive code minifying that preserves names and linenos. Performs the following:

  • Removes docstrings.

  • Removes comments.

  • Removes unnecessary whitespace.

Parameters:

code (str) -- Python code to minify.

Returns:

Minified code.

Return type:

str