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:
the environment variable (
OMNIPYTHON_DISPLAYorOMNIPYTHON_AUDIO), if set. It names one backend and nothing else is tried;the backends a config
require``d, in order, skipping any whose ``probe()says no;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:
ExceptionRaised 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 withpcm_outandpcm_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.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
ImportErrorthat 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
automodule 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
requirewould.
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.PERIPHERALSmaps toperipherals_mod.<name>. Names in optionalperipherals_mod.FACTORY_ROLES(a subset ofPERIPHERALS) are bound as the factory callable itself — first access does not invoke it. That is the audio pattern:board_config.audio_out(format=...)matchesaudiodev.auto.audio_out. Every other role stays construct-on-getattr: first access calls the zero-arg factory, caches the object intons[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 callsboard_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
PERIPHERALSandFACTORY_ROLES, so"audio_out" in board_config.PERIPHERALSis true andboard_config.audio_outis 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 assdcard.The board’s
AUDIO_OUTbecomesrole.capability, or None when role has none, once neitheraudio_outnorpcm_outis the board’s own;AUDIO_INthe same forpcm_in. A capability with awiredescribes the board’s codec, and an app that drives that wire itself would otherwise keep playing there. Replaceaudio_outandpcm_outtogether: the board’s own roles readAUDIO_OUT, so it stays while either is left.board_configgets the same changes when it’s already imported.
Call it in
main.pybefore the app is imported, and before anything has opened the old role.- Parameters:
peripherals_mod – The board’s
board_peripheralsmodule.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_peripheralswhen this machine has one, elseaudiodev.auto. A desktopboard_peripheralsforwards toaudiodev.autoitself, so preferring the board module is right in both cases.
- boarddev.pcm_out(format=None, **kwargs)[source]
Raw
PCMOutputfrom board or host, same call.Push bytes at it with
write(); no sample graph is pulled, so this needs no audiodsp in firmware.
- boarddev.env_set(name, value)[source]
Set an environment variable portably (CPython, MicroPython, CircuitPython).
Always records a process-local override so
env_boolsees the value even when the hostosmodule has noenviron. When available, also updatesos.environor callsos.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_setoverrides).
- boarddev.env_int(name, default=0)[source]
Read an integer environment variable portably (honors
env_setoverrides).
- boarddev.NAME_KEY = 'OMNIPYTHON_BOARD_NAME'
The environment variable (a desktop, a browser) and the
settings.tomlkey (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(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_managersets 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 isomnipython-plus six random hex digits, new on each page load.A new name is saved where
wifi_managerkeeps networks:esp32.NVSon an ESP32,OMNIPYTHON_BOARD_NAMEinsettings.tomlon CircuitPython,/omnipython.jsonon other boards (/flashon an STM32). On a desktop or in a browser it sets theOMNIPYTHON_BOARD_NAMEenvironment 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.tomlwhile a computer has the CIRCUITPY drive mounted.
- boarddev.check_name(text)[source]
Raise
ValueErrorunlesstextcan be a board’s name (seename).
SDL2/PyGame-style event types and namedtuple event classes.
Import as import events and use events.QUIT, events.Button(...).
- 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.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.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
xis not a known key name.
- 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
xis 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_CTRLis satisfied by either left or right Ctrl. Extra modifiers beyond those required are ignored.
- 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). Bitiis usage0xE0 + i.
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:
- 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:
objectThe screen rotation for a stream of readings, with the hysteresis above.
- Parameters:
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:
Join the access point named after the board (
omnipython-a1b2c3, or the name given withboarddev.name()) with the password shown. A phone camera can join from the QR code.The phone opens the setup page by itself. If it doesn’t, browse to http://192.168.4.1.
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.
FalsereturnsNoneinstead.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_drvwhen there is one.timeout (int) – Seconds to wait for each network.
wait (bool) –
Falsestarts joining the first known network and returnsNoneat once, without a scan or setup mode; pollwifi.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_SSIDandWIFI_PASSWORD(orssidandpassword). Defaultsecrets.
- Returns:
str | None – The IPv4 address, or
Nonewhen no network was joined (or, withwait=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.hostnameanddisplay_drvare as inconnect.- Returns:
str | None – The IPv4 address of the network joined, or
Nonewhencancel()ended it.