Other modules

The modules that are a single file rather than a package. display_driver sets up LVGL as it is imported, so it is described in LVGL instead.

A registry of backends, so AutoDisplay and audiodev.auto can pick one you wrote.

A backend registers a name and a lazy "module:Class" string, so registering imports nothing:

import backends
backends.register("display", "hls", "castdisplay.hls_display:HlsDisplay", probe=have_ffmpeg)

A board config says which registered backends it wants, in order:

backends.require("display", "hls", module="castdisplay.hls_display")
display_drv = AutoDisplay(1280, 720, tv=TV)   # extra keywords go to the winner

A display backend’s constructor takes width and height, optionally rotation (passed only when the caller asks for one), and any keywords of its own. AutoDisplay’s window hints (scale, title, quiet, maximized) stay with the built-in window backends.

kind is "display" or "audio". The search order is:

  1. the environment variable (OMNIPYTHON_DISPLAY or OMNIPYTHON_AUDIO), if set. It names one backend and nothing else is tried;

  2. the backends a config require``d, in order, skipping any whose ``probe() says no;

  3. the backends that ship in the box, in their fixed order, on the host that can run them.

A backend registered by someone else is never picked in step 3. Something has to require it, or the user has to name it, so a backend that streams to a TV never chooses itself.

There is no scanning. On MicroPython, require imports the module by name and importing registers it; a frozen module imports like any other.

exception backends.Decline[source]

Bases: Exception

Raised by a backend’s factory to say “not on this machine”; the next one is tried.

backends.register(kind, name, spec, probe=None, _builtin=False)[source]

Make name a backend of kind; imports nothing.

spec is "module:Class" ("module" alone for an audio backend, which is a module with pcm_out and pcm_in). probe, if given, is called with no arguments and returns false when this machine can’t run the backend. Registering a name again replaces it in place.

_builtin is for the backends that ship in the box; the underscore says it isn’t yours to pass. A backend with it is picked unasked by the third step of the search order, and a display backend with it is called with positional arguments instead of keywords.

backends.names(kind)[source]

The registered backend names of kind, in registration order.

backends.spec(kind, name)[source]

The spec string name was registered with, or None.

backends.require(kind, name, module=None)[source]

Ask for backend name to be tried by auto, ahead of the built-in ones.

If name isn’t registered yet, imports module (default: name), which registers it. Raises ImportError that names the module when it isn’t installed, or when importing it didn’t register the backend.

backends.candidates(kind, override=None)[source]

Yield (name, spec, builtin) for each backend to try, in search order.

name and spec are what the backend registered with. builtin is true for a backend that ships in the box. A consumer auto module unpacks all three, so the tuple keeps this shape.

override is a name the user gave (usually from the environment). It is the only candidate, its probe is not consulted, and an unregistered name is imported as a module, the way require would.

backends.load(spec)[source]

Import and return what spec names: "module:Class", or a module.

Lazy end-device binding for board_peripherals -> board_config.

board_peripherals.load_peripherals(globals()) typically calls bind_lazy(ns, this_module). Apps normally use board_config.PERIPHERALS and attribute access instead of importing this module.

It also carries the one thing neither audiodev nor a board can answer on its own: whether this machine’s audio comes from a board or from a host backend. See pcm_out.

And it is where the portable environment helpers live – env_get, env_int, env_float, env_bool and env_set – because a board config, an app and every OmniPython package read their OMNIPYTHON_* settings through them, on interpreters where os.environ may not exist:

from boarddev import env_int, env_set

env_set("OMNIPYTHON_WIDTH", 800)   # before board_config is imported
period = env_int("OMNIPYTHON_REFRESH_MS", 0)

This module imports nothing at module scope, so any package – displaydev included – can import from it without a cycle. Keep it that way.

boarddev.bind_lazy(ns, peripherals_mod)[source]

Install module __getattr__ / __dir__ on ns for lazy roles.

Each name in peripherals_mod.PERIPHERALS maps to peripherals_mod.<name>. Names in optional peripherals_mod.FACTORY_ROLES (a subset of PERIPHERALS) are bound as the factory callable itself — first access does not invoke it. That is the audio pattern: board_config.audio_out(format=...) matches audiodev.auto.audio_out. Every other role stays construct-on-getattr: first access calls the zero-arg factory, caches the object into ns[name], and further access hits the module dict (no __getattr__).

boarddev.replace_role(peripherals_mod, name, role)[source]

Put role in place of the board’s name role, for every caller.

Assigning board_peripherals.audio_out = ... already reaches code that calls board_peripherals.audio_out(). This does that and keeps the rest of the board’s story true, so code that discovers roles or reads a capability sees the replacement too:

  • name joins PERIPHERALS and FACTORY_ROLES, so "audio_out" in board_config.PERIPHERALS is true and board_config.audio_out is role itself, never a call of it. Pass what callers should get: the factory for an audio role, the object for a constructed one such as sdcard.

  • The board’s AUDIO_OUT becomes role.capability, or None when role has none, once neither audio_out nor pcm_out is the board’s own; AUDIO_IN the same for pcm_in. A capability with a wire describes the board’s codec, and an app that drives that wire itself would otherwise keep playing there. Replace audio_out and pcm_out together: the board’s own roles read AUDIO_OUT, so it stays while either is left.

  • board_config gets the same changes when it’s already imported.

Call it in main.py before the app is imported, and before anything has opened the old role.

Parameters:
  • peripherals_mod – The board’s board_peripherals module.

  • name – The role’s name, such as "audio_out".

  • role – What callers get in its place.

Example

import board_peripherals import boarddev from usb.host import audio

boarddev.replace_role(board_peripherals, “audio_out”, audio.audio_out)

boarddev.audio_provider()[source]

Return the module supplying this machine’s audio factories.

board_peripherals when this machine has one, else audiodev.auto. A desktop board_peripherals forwards to audiodev.auto itself, so preferring the board module is right in both cases.

boarddev.pcm_out(format=None, **kwargs)[source]

Raw PCMOutput from board or host, same call.

Push bytes at it with write(); no sample graph is pulled, so this needs no audiodsp in firmware.

boarddev.pcm_in(format=None, **kwargs)[source]

Raw PCMInput from board or host, same call.

boarddev.audio_out(format=None, **kwargs)[source]

AudioOut sample player, board or host.

boarddev.env_set(name, value)[source]

Set an environment variable portably (CPython, MicroPython, CircuitPython).

Always records a process-local override so env_bool sees the value even when the host os module has no environ. When available, also updates os.environ or calls os.putenv.

boarddev.env_bool(name, default=False)[source]

Read a truthy/falsey environment variable with a portable fallback chain.

boarddev.env_get(name, default=None)[source]

Read a string environment variable portably (honors env_set overrides).

boarddev.env_int(name, default=0)[source]

Read an integer environment variable portably (honors env_set overrides).

boarddev.env_float(name, default=0.0)[source]

Read a floating-point environment variable portably.

boarddev.NAME_KEY = 'OMNIPYTHON_BOARD_NAME'

The environment variable (a desktop, a browser) and the settings.toml key (CircuitPython) that hold a saved name.

boarddev.NAME_PREFIX = 'omnipython-'

What a board’s default name starts with, before the last three bytes of its unique ID in hex.

boarddev.NAME_MAX = 20

The longest name name takes.

boarddev.name(new=<object object>)[source]

The board’s name, or give it a new one.

Every stack that shows a name and is given none uses this one: the hostname wifi_manager sets before it joins (so DHCP, mDNS and Bluetooth Classic see it), the setup access point, bledev’s services, medialink and hmilink.

With no saved name, a board is omnipython- plus the last three bytes of its unique ID in hex (omnipython-a1b2c3), a desktop is the computer’s name, and a browser is omnipython- plus six random hex digits, new on each page load.

A new name is saved where wifi_manager keeps networks: esp32.NVS on an ESP32, OMNIPYTHON_BOARD_NAME in settings.toml on CircuitPython, /omnipython.json on other boards (/flash on an STM32). On a desktop or in a browser it sets the OMNIPYTHON_BOARD_NAME environment variable for this process only; it never renames the computer. Stacks that already started keep the old name until the next start.

Example:

import boarddev

boarddev.name()            # "omnipython-a1b2c3"
boarddev.name("kitchen")   # saved; the board is "kitchen" from the next start
boarddev.name(None)        # back to the default
Parameters:

new (str) – The new name: one label of letters, digits and hyphens, not starting or ending with a hyphen, 1 to 20 characters, so it works unchanged as a hostname and as a BLE name. None forgets a saved name.

Returns:

str – The name, when called with no argument. Otherwise None.

Raises:
  • ValueError – The new name breaks one of the rules above.

  • OSError – CircuitPython can’t write settings.toml while a computer has the CIRCUITPY drive mounted.

boarddev.check_name(text)[source]

Raise ValueError unless text can be a board’s name (see name).

SDL2/PyGame-style event types and namedtuple event classes.

Import as import events and use events.QUIT, events.Button(...).

class events.Unknown(type)

Bases: tuple

type

Alias for field number 0

class events.Motion(type, pos, rel, buttons, touch, window)

Bases: tuple

buttons

Alias for field number 3

pos

Alias for field number 1

rel

Alias for field number 2

touch

Alias for field number 4

type

Alias for field number 0

window

Alias for field number 5

class events.Button(type, pos, button, touch, window)

Bases: tuple

button

Alias for field number 2

pos

Alias for field number 1

touch

Alias for field number 3

type

Alias for field number 0

window

Alias for field number 4

class events.Wheel(type, flipped, x, y, precise_x, precise_y, touch, window)

Bases: tuple

flipped

Alias for field number 1

precise_x

Alias for field number 4

precise_y

Alias for field number 5

touch

Alias for field number 6

type

Alias for field number 0

window

Alias for field number 7

x

Alias for field number 2

y

Alias for field number 3

class events.Key(type, name, key, mod, scancode, window)

Bases: tuple

key

Alias for field number 2

mod

Alias for field number 3

name

Alias for field number 1

scancode

Alias for field number 4

type

Alias for field number 0

window

Alias for field number 5

class events.Quit(type)

Bases: tuple

type

Alias for field number 0

class events.Any(type)

Bases: tuple

type

Alias for field number 0

class events.JoyAxisMotion(type, instance_id, axis, value)

Bases: tuple

axis

Alias for field number 2

instance_id

Alias for field number 1

type

Alias for field number 0

value

Alias for field number 3

class events.JoyButtonUp(type, instance_id, button)

Bases: tuple

button

Alias for field number 2

instance_id

Alias for field number 1

type

Alias for field number 0

class events.JoyButtonDown(type, instance_id, button)

Bases: tuple

button

Alias for field number 2

instance_id

Alias for field number 1

type

Alias for field number 0

class events.JoyHatMotion(type, instance_id, hat, value)

Bases: tuple

hat

Alias for field number 2

instance_id

Alias for field number 1

type

Alias for field number 0

value

Alias for field number 3

class events.JoyBallMotion(type, instance_id, ball, rel)

Bases: tuple

ball

Alias for field number 2

instance_id

Alias for field number 1

rel

Alias for field number 3

type

Alias for field number 0

class events.Finger(type, pos, finger_id, window)

Bases: tuple

finger_id

Alias for field number 2

pos

Alias for field number 1

type

Alias for field number 0

window

Alias for field number 3

events.register_event(name=None, value=None, *, fields=None, types=None, classes=None)[source]

Register custom event type(s) and optional namedtuple class(es).

Single type:

register_event("MINE", 0x801)
register_event("MINE")  # auto-allocated value

Bulk types (dict or list of tuples) and classes (dict of field strings):

register_event(types=[("FOO", 0x900)], classes={"Foo": "type a b"})

SDL-style key codes, names, and modifier masks.

Import as import keys and use keys.K_a, keys.KMOD_CTRL, keys.keyname(code), keys.chord_matches(...).

keys.keyname(x)[source]

Return the human-readable name for key code x.

keys.key(x)[source]

Return the key code whose name is x.

Parameters:

x – A name from keyname (e.g. "Return").

Returns:

int – Matching K_* code.

Raises:

ValueError – When x is not a known key name.

keys.modname(x)[source]

Return the human-readable name for modifier mask x.

keys.mod(x)[source]

Return the modifier mask whose name is x.

Parameters:

x – A name from modname (e.g. "Ctrl").

Returns:

int – Matching KMOD_* mask.

Raises:

ValueError – When x is not a known modifier name.

keys.chord_matches(chord, keycode, mod)[source]

Return True if (keycode, mod) satisfies a (key, mod_mask) chord.

Modifier matching is group-aware: a required KMOD_CTRL is satisfied by either left or right Ctrl. Extra modifiers beyond those required are ignored.

Parameters:
  • chord (tuple | None) – A (key_code, modifier_mask) tuple, or None.

  • keycode (int) – The pressed key code.

  • mod (int) – The active modifier mask.

Returns:

bool – Whether the chord is satisfied.

keys.hid_keycode(usage)[source]

The K_* code for a HID keyboard-page usage (0x04 is ‘a’), or None.

keys.HID_MODIFIERS = ((64, 1073742048), (1, 1073742049), (256, 1073742050), (1024, 1073742051), (128, 1073742052), (2, 1073742053), (512, 1073742054), (2048, 1073742055))

The eight modifier bits of a HID keyboard report, in bit order (bit 0 is left Ctrl), as (KMOD_* mask, K_* code). Bit i is usage 0xE0 + i.

keys.hid_modifiers(bits)[source]

The KMOD_* mask for a HID report’s modifier byte.

Turn accelerometer readings into a screen rotation of 0, 90, 180 or 270.

Feed it readings every few hundred milliseconds and set the rotation it returns:

from orientation import Orientation

turn = Orientation()
rotation = turn.update(*accel.acceleration)
if rotation is not None:
    display.rotation = rotation

The rule: gravity’s direction in the screen’s plane, atan2(-x, y), falls in one of four 90-degree sectors centred on 0, 90, 180 and 270. A new rotation takes two agreeing readings in a row (stable), so a knock doesn’t turn the screen. A reading taken lying flat, where more than upright of gravity is on Z, says nothing about which way is up: it is ignored and starts the count again.

Readings are in the board’s frame, with Y up when the screen shows unrotated; a board config’s accelerometer gives them that way.

orientation.sector(x, y, z, *, upright=0.9)[source]

The sector gravity points into, 0, 90, 180 or 270, or None.

Parameters:
  • x (float) – One reading, in any unit (g, counts).

  • y (float) – One reading, in any unit (g, counts).

  • z (float) – One reading, in any unit (g, counts).

  • upright (float) – The share of gravity on Z, 0 to 1, from which the board counts as lying flat.

Returns:

int or None – The sector, or None for a flat board or a zero reading.

class orientation.Orientation(*, offset=0, stable=2, upright=0.9, rotation=0)[source]

Bases: object

The screen rotation for a stream of readings, with the hysteresis above.

Parameters:
  • offset (int) – Degrees added to every sector, for a board whose accelerometer is mounted turned.

  • stable (int) – Agreeing readings in a row before the rotation changes.

  • upright (float) – See sector.

  • rotation (int) – The rotation to start from.

update(x, y, z)[source]

Take one reading.

Returns:

int or None – The new rotation when it changes, else None. rotation always holds the current one.

wifi_manager.py - join a known Wi-Fi network, or ask for a new one on the screen.

Call it once near the top of main.py, before the app touches the network:

import wifi_manager
ip = wifi_manager.connect()

connect() joins the strongest network it already knows, scanning first when it knows more than one. It knows the network in secrets.py (WIFI_SSID / WIFI_PASSWORD), the one in CircuitPython’s settings.toml (CIRCUITPY_WIFI_SSID / CIRCUITPY_WIFI_PASSWORD), and every network it has joined before. Every network that works is remembered, so once a board has joined, secrets.py can be deleted.

When none of those is in range, the board starts its own access point and says how to reach it, on the display from board_config.display_drv when there is one and always on the REPL:

  1. Join the access point named after the board (omnipython-a1b2c3, or the name given with boarddev.name()) with the password shown. A phone camera can join from the QR code.

  2. The phone opens the setup page by itself. If it doesn’t, browse to http://192.168.4.1.

  3. Pick your network, type its password, press Join.

The board remembers the network and carries on. While it waits it rescans every minute, so a board that booted before the router came back joins on its own. To move to a new network on purpose, call wifi_manager.run(), which waits for one. cancel(), from a timer or another app, ends setup mode without a network.

Before it joins, connect() and run() make the board’s name (boarddev.name()) its hostname, so DHCP, mDNS and Bluetooth Classic see it, unless they’re given hostname=.

connect(ntp=True) sets the clock from NTP once a network is joined. connect(wait=False) starts the join and returns at once, for an app that can’t stall: poll wifi.radio.connected, or call it again after the link drops. A board with a fixed address (ifconfig() set before the join) counts as connected only once the station has a link, so it joins at boot and rejoins after a drop. connect(module="mysecrets") reads the credentials from another module than secrets.

networks() lists the remembered SSIDs, forget(ssid) drops one and forget() drops them all. A network that is still in secrets.py comes back the next time it is joined.

Hidden networks: type the name into “Other” on the setup page. The board then tries it at every boot even though scans can’t see it.

Install

It is part of the omnipython package, so a firmware that freezes OmniPython already has it. Otherwise, on MicroPython:

import omip
omip.install("omnipython")

CircuitPython: copy this file to /lib.

docs/guides/wifi.md shows it in three kinds of app: one that needs the network, one that works without it, and one that turns Wi-Fi on only for maintenance.

The screen

With LVGL compiled in (lvgl and display_driver), the page is drawn in LVGL with an lv.qrcode. Otherwise it is drawn with pygraphics straight onto display_drv, text scaled to the panel, and the QR code comes from adafruit_miniqr when that is installed (optional):

mip.install("github:adafruit/Adafruit_CircuitPython_miniQR/adafruit_miniqr.py")
circup install adafruit_miniqr          # CircuitPython

With neither, the REPL is the only screen.

Where remembered networks live

CircuitPython keeps them in microcontroller.nvm, which code can write even while USB has CIRCUITPY mounted. The record starts at NVM_OFFSET behind a magic header; move NVM_OFFSET if your app keeps its own data in nvm.

MicroPython on ESP32 keeps them in esp32.NVS namespace "wifi_manager". That survives a filesystem wipe, but not esptool erase_flash. Other MicroPython ports use wifi_networks.json on the board’s writable drive: /wifi_networks.json, or /flash/wifi_networks.json on an STM32 board such as the Arduino GIGA, whose / only holds the mounts.

Passwords are stored in plain text, as they are in secrets.py.

wifi_manager.connect(*, setup=True, hostname=None, display_drv=None, timeout=20, wait=True, ntp=False, module='secrets')[source]

Join a known network, or run setup mode when none is in range.

Parameters:
  • setup (bool) – Start setup mode when no known network is in range. False returns None instead.

  • hostname (str) – Set before joining, so DHCP and mDNS see it. Default: the board’s name, boarddev.name().

  • display_drv – Display for setup mode. Default: board_config.display_drv when there is one.

  • timeout (int) – Seconds to wait for each network.

  • wait (bool) – False starts joining the first known network and returns None at once, without a scan or setup mode; poll wifi.radio.connected (or call again after a drop). For an app that can’t stall. On CircuitPython a join can’t run in the background, so it waits as usual.

  • ntp (bool) – Set the clock from NTP once a network is joined. Skipped when the board was already connected.

  • module (str) – The module holding WIFI_SSID and WIFI_PASSWORD (or ssid and password). Default secrets.

Returns:

str | None – The IPv4 address, or None when no network was joined (or, with wait=False, when one was started).

wifi_manager.run(*, hostname=None, display_drv=None, timeout=20)[source]

Start setup mode now, even when a known network is in range. It waits for a new network (or cancel()) rather than going back to a known one. hostname and display_drv are as in connect.

Returns:

str | None – The IPv4 address of the network joined, or None when cancel() ended it.

wifi_manager.cancel()[source]

End setup mode without a network: connect() or run() returns None. For a timer or event callback while setup mode waits.

wifi_manager.networks()[source]

The SSIDs of the remembered networks.

wifi_manager.forget(ssid=None)[source]

Forget one remembered network, or all of them when ssid is None.