Skip to content

API reference

Everything below is importable from the package itself, e.g. from arena_interface import Device, Pattern, TrialMode. The modules are listed here only to group the reference by topic.

Connecting and controlling

device

High-level interface to a G6 arena controller.

from arena_interface import Device, TrialMode

with Device.open() as dev:                # auto-detect
    print(dev.firmware_version)
    dev.start_trial(1, TrialMode.OPEN_LOOP, frame_rate=60, duration=5)

Thread safety: a Device may be shared between threads. Each method is atomic (the wire protocol allows only one request at a time and the device serialises them), and multi-step methods such as PatternLibrary.upload hold a lock for their whole sequence. Sequences of calls made by your own code are not atomic; use your own lock if another thread must not interleave.

Device

Device(
    transport: Transport,
    *,
    all_off_on_close: bool = True,
    arena_shape: tuple[int, int] | None = None,
    simulator: FakeController | None = None,
)

A connection to one G6 arena controller.

Create it with Device.open and use it as a context manager, or call close yourself. Closing blanks the arena (ALL_OFF) unless all_off_on_close is False.

Feature groups are attributes: patterns (SD card), io (analog and digital BNCs), telemetry (event log), diagnostics and panel_firmware.

Wrap an open transport; most code should use Device.open.

Parameters:

Name Type Description Default
transport Transport

Connected transport.

required
all_off_on_close bool

Send ALL_OFF when closing.

True
arena_shape tuple[int, int] | None

Panel rows and columns of the firmware build, for firmware that cannot report them.

None
simulator FakeController | None

The simulated controller, when transport is a fake.

None

Raises:

Type Description
ProtocolError

If the device does not identify as a G6 controller.

patterns instance-attribute

patterns = PatternLibrary(self)

SD-card pattern library.

io instance-attribute

io = IO(self)

Analog and digital I/O.

diagnostics instance-attribute

diagnostics = Diagnostics(self)

Health and bench diagnostics.

telemetry instance-attribute

telemetry = Telemetry(self)

The controller's event log (commands, frame changes, state changes).

panel_firmware instance-attribute

panel_firmware = PanelFirmware(self)

Panel firmware update.

is_open property

is_open: bool

True while connected.

port_name property

port_name: str

Name of the serial port (fake://arena when simulated).

simulator property

simulator: FakeController | None

The simulated controller, or None when connected to hardware.

firmware_version property

firmware_version: str

One-line firmware description, e.g. "06a6f25 2x10 2026-09-12 main".

capabilities property

capabilities: Capability

Capability bits advertised by the controller.

firmware_flags property

firmware_flags: FirmwareFlag

Firmware feature flags (empty if the firmware cannot report them).

arena_shape property

arena_shape: tuple[int, int] | None

(rows, cols) of panels the firmware drives, if known.

panel_count property

panel_count: int | None

Number of panels the firmware drives, if known.

arena property

arena: Arena

The full panel grid the controller drives, as an Arena.

Use it to size images and patterns for this controller. It is the matching full-grid preset when there is one (e.g. G6_2x10, whose id is then written to pattern headers), otherwise a plain Arena. Panels removed from the arena do not change it.

Raises:

Type Description
DeviceError

If the firmware does not report its grid and no arena_shape was given to Device.open().

Example

with Device.open(simulate=True) as dev: ... print(dev.arena.name, dev.arena.pixel_shape) G6_2x10 (40, 200)

frame_position property

frame_position: FramePosition

Current frame index and frame count of the loaded pattern.

refresh_rate property writable

refresh_rate: int

Rate (Hz) at which the current frame is re-sent to the panels.

Once set, it stays in force until the controller restarts.

panel_display_mode property writable

panel_display_mode: PanelDisplayMode

How panels present frames: oneshot, persist, triggered or gated.

frames_sent property

frames_sent: int

Frames pushed to the panels since boot or the last reset of the counter.

open classmethod

open(
    port: str | None = None,
    *,
    simulate: bool | FakeController = False,
    probe: bool = True,
    all_off_on_close: bool = True,
    arena_shape: tuple[int, int] | None = None,
    cache_patterns: bool = False,
) -> Device

Connect to a controller.

Parameters:

Name Type Description Default
port str | None

Serial port name. If omitted, the controller is found by its USB ids (see find_ports).

None
simulate bool | FakeController

Connect to a simulated controller instead of hardware: True for a new default one, or a FakeController.

False
probe bool

When several candidate ports are found, ask each one for its controller info to pick the controller. Without probing, more than one candidate is an error.

True
all_off_on_close bool

Blank the arena when the connection is closed.

True
arena_shape tuple[int, int] | None

(rows, cols) of the firmware build, for firmware too old to report it.

None
cache_patterns bool

Read the SD card's pattern names now and keep them, so choosing a pattern by name is fast (see PatternLibrary.cache).

False

Returns:

Type Description
Device

The connected device.

Raises:

Type Description
DeviceNotFound

If no controller is found, the choice is ambiguous, or the port cannot be opened.

DeviceTimeout

If the device does not answer.

ProtocolError

If the device does not identify as a G6 controller.

Example

with Device.open(simulate=True) as dev: ... print(dev.arena_shape) (2, 10)

close

close() -> None

Blank the arena (unless disabled) and release the port.

Safe to call more than once and after the device has disappeared.

reset

reset() -> None

Reboot the controller (SYSTEM_RESET).

The USB connection drops, so the device is closed afterwards; call reconnect to continue.

reconnect

reconnect(
    timeout: float = 10.0, poll_interval: float = 0.25
) -> None

Re-open the same controller after a reset or an unplug.

Polls the port until the controller answers again. If the MAC address was known, it must match, so a different controller on the same port is not picked up by mistake.

Parameters:

Name Type Description Default
timeout float

Seconds to keep trying.

10.0
poll_interval float

Seconds between attempts.

0.25

Raises:

Type Description
DeviceNotFound

If the controller does not come back in time, or a different controller answers.

supports

supports(requirement: Capability | FirmwareFlag) -> bool

True if the controller advertises a capability or firmware flag.

all_off

all_off() -> None

Blank the arena and stop any display.

all_on

all_on() -> None

Light every pixel at full brightness.

stop

stop() -> None

Stop the display and blank the arena.

start_trial

start_trial(
    pattern: int | str,
    mode: TrialMode = OPEN_LOOP,
    *,
    frame_rate: int = 0,
    initial_frame: int = 0,
    gain: int = 0,
    duration: float = 0.0,
    duty_cycle: int | None = None,
) -> None

Start displaying an SD-card pattern.

Parameters:

Name Type Description Default
pattern int | str

The SD-card pattern: its file name (.pat optional, case ignored) or its id, its number in the alphabetical list of file names starting at 1 (see device.patterns). Ids change when patterns are added, renamed or deleted; names do not.

required
mode TrialMode

Open loop (auto-advance), show frame (you choose the frame) or closed loop (frame rate follows Analog In 1).

OPEN_LOOP
frame_rate int

Frames per second in open loop; negative plays backwards.

0
initial_frame int

Frame to start on (the first frame is 0).

0
gain int

Closed-loop gain in tenths of frames per second per volt.

0
duration float

Seconds until the controller stops by itself; 0 = never.

0.0
duty_cycle int | None

Brightness 1-255 for this trial, or None for the pattern's own.

None

Raises:

Type Description
KeyError

If no pattern has that name.

CommandError

If the pattern cannot be loaded (the arena shows an error code briefly and goes dark).

Example

with Device.open(simulate=True) as dev: ... dev.start_trial("demo_gs2", frame_rate=30) # demo_gs2.pat ... dev.start_trial(1, frame_rate=30) # the first pattern

show_pattern

show_pattern(pattern: int | str) -> None

Load a pattern and show its first frame, without advancing.

Parameters:

Name Type Description Default
pattern int | str

File name (.pat optional, case ignored) or id (the first pattern is 1), as for start_trial.

required

Raises:

Type Description
KeyError

If no pattern has that name.

show_frame

show_frame(index: int) -> None

Show one frame of the loaded pattern (the first frame is 0).

Raises:

Type Description
ValueError

If the index is beyond the loaded pattern (checked locally, because the controller would stop the display).

CommandError

If no pattern is loaded.

stream_frame

stream_frame(payload: bytes) -> None

Display a frame sent from the host.

Parameters:

Name Type Description Default
payload bytes

One frame: "FR", a frame index (u16) and one panel block per panel. Its size selects GS2 or GS16.

required

Raises:

Type Description
ValueError

If the size does not match the arena.

stream_image

stream_image(
    image: Any,
    *,
    gray_level: GrayLevel = GS16,
    origin: Origin = "upper",
    duty_cycle: int = DEFAULT_DUTY_CYCLE,
    arena: Arena | None = None,
) -> None

Display one image sent from the host.

Parameters:

Name Type Description Default
image Any

Pixel rows (nested lists or a 2-D numpy array) covering the whole arena: 0/1 for GS2, 0-15 for GS16.

required
gray_level GrayLevel

GS2 or GS16.

GS16
origin Origin

"upper" if row 0 is the top of the arena, "lower" if it is the bottom.

'upper'
duty_cycle int

Brightness 1-255.

DEFAULT_DUTY_CYCLE
arena Arena | None

The rig's arena, if it differs from the controller's grid; the image is then fitted to the grid. If omitted, the image size gives the arena.

None

Raises:

Type Description
ValueError

If the image does not match or fit the controller's grid.

show_panel_frame

show_panel_frame(index: int) -> None

Show a frame stored in the panels' own memory (PSRAM).

play_panel_frames

play_panel_frames(start: int, count: int, fps: int) -> None

Play frames start .. start+count-1 from the panels' own memory.

reset_frames_sent

reset_frames_sent() -> None

Zero the frames-sent counter.

play_frames

play_frames(
    frames: Iterable[int],
    fps: float,
    *,
    pattern: int | str | None = None,
    late: LatePolicy = "skip",
    refresh_rate: int | None = None,
    verify: bool = False,
) -> PlaybackReport

Show frames of the loaded SD pattern at a fixed rate, paced by the computer.

Parameters:

Name Type Description Default
frames Iterable[int]

Frame numbers (the first frame is 0), in the order to show them.

required
fps float

Frames per second.

required
pattern int | str | None

Load this pattern first (file name or id, as for show_pattern); by default the pattern already loaded is used.

None
late LatePolicy

"skip" drops frames whose time has passed, keeping the schedule; "send" sends every frame, possibly late.

'skip'
refresh_rate int | None

Set the controller's refresh rate first. It stays in force until the controller restarts (see refresh_rate).

None
verify bool

Afterwards, read the controller's log to count the frame changes actually displayed (needs telemetry); the report's displayed then equals changes if none was lost.

False

Returns:

Type Description
PlaybackReport

What happened: a

PlaybackReport

Raises:

Type Description
ValueError

If no pattern is loaded or an index is out of range.

Example

with Device.open(simulate=True) as dev: ... report = dev.play_frames(range(16), fps=100, pattern=1) report.sent 16

start_frames

start_frames(
    frames: Iterable[int],
    fps: float,
    *,
    pattern: int | str | None = None,
    late: LatePolicy = "skip",
    refresh_rate: int | None = None,
    verify: bool = False,
) -> Playback

Like play_frames, but in a background thread.

Returns:

Type Description
Playback

A running Playback; call

Playback

wait() for the report or stop() to end early.

play_images

play_images(
    images: Pattern | Sequence[Any],
    fps: float,
    *,
    gray_level: GrayLevel = GS16,
    origin: Origin = "upper",
    arena: Arena | None = None,
    duty_cycle: int = DEFAULT_DUTY_CYCLE,
    late: LatePolicy = "skip",
    refresh_rate: int | None = None,
) -> PlaybackReport

Stream images to the arena at a fixed rate, paced by the computer.

All frames are encoded before playback starts, so encoding does not affect the timing. The first frame is sent once while preparing, to put the controller in the right refresh rate for the gray level.

Parameters:

Name Type Description Default
images Pattern | Sequence[Any]

A Pattern, or images as for Pattern.from_frames (nested lists or numpy arrays).

required
fps float

Frames per second.

required
gray_level GrayLevel

GS2 or GS16 (ignored for a Pattern).

GS16
origin Origin

"upper" or "lower" (ignored for a Pattern).

'upper'
arena Arena | None

The rig's arena, if the images are drawn for a rig other than the controller's grid (ignored for a Pattern).

None
duty_cycle int

Brightness 1-255 (ignored for a Pattern).

DEFAULT_DUTY_CYCLE
late LatePolicy

"skip" or "send", as for play_frames.

'skip'
refresh_rate int | None

Set the controller's refresh rate first.

None

Returns:

Type Description
PlaybackReport

What happened: a

PlaybackReport

start_images

start_images(
    images: Pattern | Sequence[Any],
    fps: float,
    *,
    gray_level: GrayLevel = GS16,
    origin: Origin = "upper",
    arena: Arena | None = None,
    duty_cycle: int = DEFAULT_DUTY_CYCLE,
    late: LatePolicy = "skip",
    refresh_rate: int | None = None,
) -> Playback

Like play_images, but in a background thread.

Returns:

Type Description
Playback

A running Playback.

pace

pace(
    rate_hz: float,
    *,
    duration: float | None = None,
    count: int | None = None,
    late: LatePolicy = "skip",
    refresh_rate: int | None = None,
) -> Pacer

A fixed-rate clock for live (closed-loop) playback.

Iterate over it and send one frame per tick, chosen as you go:

pacer = dev.pace(200, duration=10)
for tick in pacer:
    dev.show_frame(choose_frame())
print(pacer.report)

Parameters:

Name Type Description Default
rate_hz float

Ticks per second.

required
duration float | None

Stop after this many seconds (None: until you break).

None
count int | None

Stop after this many ticks.

None
late LatePolicy

"skip" jumps over ticks whose time has passed (the next tick says how many); "send" delivers every tick, late.

'skip'
refresh_rate int | None

Set the controller's refresh rate first.

None

Returns:

Type Description
Pacer

An iterable Pacer.

sample

sample(
    read: Callable[[], _T],
    rate_hz: float,
    *,
    duration: float | None = None,
    count: int | None = None,
) -> Sampler[_T]

Call read at a fixed rate and yield timestamped results.

Parameters:

Name Type Description Default
read Callable[[], _T]

Any function without arguments, typically a read method such as device.io.read_analog_in or lambda: device.frame_position.

required
rate_hz float

Readings per second. Each reading is one USB round trip (about 1 ms), so a few hundred Hz is the practical limit.

required
duration float | None

Stop after this many seconds.

None
count int | None

Stop after this many samples.

None

Returns:

Type Description
Sampler[_T]

An iterable Sampler; its

Sampler[_T]

skipped attribute counts readings dropped because one was late.

Example

with Device.open(simulate=True) as dev: ... samples = list(dev.sample(dev.io.read_digital, 50, count=3)) len(samples) 3

PatternLibrary

PatternLibrary(device: Device)

Patterns stored on the controller's SD card (device.patterns).

Patterns are addressed by an id: their number in the alphabetical list of file names, starting at 1 for the first. Uploading, renaming and deleting re-sort the list, so ids can change; the methods that change the library return the new id.

Downloading, uploading, formatting and archiving need the display to be off (call device.stop() first); otherwise the controller refuses with a CommandError.

Looking a pattern up by name reads every name from the card, one request per pattern. Turn on cache to keep the names instead.

Bind to a device.

cache property writable

cache: bool

Keep the pattern names, so name lookups are fast (default off).

Setting it to True reads the names from the card at once; setting it to False drops them, and every lookup reads the card again.

While it is on:

  • a name lookup (find and the pattern argument of start_trial and friends) takes one request instead of one per pattern on the card: the card's name at the cached id is checked, so a stale cache never selects the wrong pattern. If the check fails, or the name is not cached, the names are read again before giving up;
  • upload, rename, delete and format_card re-read the names, as does Device.reconnect;
  • listing the patterns (len, iteration, entries) still reads the card.
Example

with Device.open(simulate=True) as dev: ... dev.patterns.cache = True # reads the names now ... dev.start_trial("demo_gs2", frame_rate=30)

refresh

refresh() -> None

Re-read the cached names from the card (nothing to do if the cache is off).

Only needed if the card was changed by something other than this Device and you want the next lookup to skip the check.

entries

entries() -> list[PatternEntry]

All patterns, in id order.

name

name(pattern: int | str) -> str

File name of a pattern, as stored on the card.

Parameters:

Name Type Description Default
pattern int | str

Id, or a name to look up (.pat optional, case ignored): name("grating") gives e.g. "Grating.pat".

required

Raises:

Type Description
KeyError

If no pattern has that name.

find

find(name: str) -> int | None

Id of the pattern with this file name, or None.

The match ignores case (as the SD card's file system does), and the .pat extension may be left out: "Grating" finds grating.pat. Each call reads the names from the controller, one request per pattern.

info

info(pattern: int | str) -> PatternInfo

Header metadata of a pattern (works while the display is running).

Parameters:

Name Type Description Default
pattern int | str

File name (.pat optional, case ignored) or id.

required

Raises:

Type Description
KeyError

If no pattern has that name.

download

download(pattern: int | str) -> bytes

Contents of a pattern file.

Parameters:

Name Type Description Default
pattern int | str

File name (.pat optional, case ignored) or id.

required

Raises:

Type Description
KeyError

If no pattern has that name.

upload

upload(
    name: str,
    data: bytes | Pattern,
    *,
    overwrite: bool = False,
) -> int

Store a pattern on the card.

Parameters:

Name Type Description Default
name str

File name, ending in .pat (1-63 ASCII characters).

required
data bytes | Pattern

A Pattern, or complete .pat file contents. A Pattern drawn for a rig smaller than the controller's grid is fitted to the grid first (see Pattern.fit_to).

required
overwrite bool

Replace an existing pattern with the same name.

False

Returns:

Type Description
int

The pattern's id after the upload.

Raises:

Type Description
FileExistsError

If the name exists and overwrite is False.

ValueError

If the name is invalid or the pattern does not match (or fit) the controller's panel grid.

rename

rename(pattern: int | str, name: str) -> int

Rename a pattern and return its new id.

If the name is taken, the controller adds an X001_-style prefix; check name afterwards.

Parameters:

Name Type Description Default
pattern int | str

The pattern to rename: file name (.pat optional, case ignored) or id.

required
name str

Its new file name, ending in .pat.

required

Raises:

Type Description
KeyError

If no pattern has the old name.

delete

delete(pattern: int | str) -> None

Delete a pattern; ids of later patterns move down by one.

Parameters:

Name Type Description Default
pattern int | str

File name (.pat optional, case ignored) or id. A name is the safer choice: an id can point at a different file after the card changes.

required

Raises:

Type Description
KeyError

If no pattern has that name.

Example

with Device.open(simulate=True) as dev: ... dev.patterns.delete("demo_gs2") ... print(dev.patterns.find("demo_gs2"), len(dev.patterns)) None 1

format_card

format_card() -> None

Erase the whole SD card: patterns, panel firmware and manifests.

archive

archive() -> bytes

The SD card contents as a ZIP file.

PatternEntry dataclass

PatternEntry(pattern_id: int, name: str)

A pattern on the SD card.

Attributes:

Name Type Description
pattern_id int

Number in the alphabetical list of patterns, starting at 1 (it changes when patterns are added, renamed or deleted).

name str

File name.

IO

IO(device: Device)

Analog and digital BNC connections (device.io).

Bind to a device.

analog_out property writable

analog_out: int

Analog output in millivolts (0-5000), as read back from the DAC.

Setting it stops any lookup table.

set_analog_out_mode

set_analog_out_mode(mode: AoMode) -> None

Choose whether the analog output is programmable or tracks the frame.

load_analog_table

load_analog_table(
    values_mv: list[int] | tuple[int, ...],
    mode: AoLutMode = FRAME_LOCKED,
    step_hz: int = 0,
) -> None

Load and start an analog-output lookup table (1-21 levels).

read_analog_in

read_analog_in() -> AnalogInputs

Read both analog inputs (±10 V, uncalibrated).

set_digital_out

set_digital_out(port: int, high: bool) -> None

Drive Digital IO port 1 or 2 high or low.

A port in role OFF becomes OUT_PROGRAMMABLE; a port in an input or frame-scan role is refused.

read_digital

read_digital() -> tuple[bool, bool]

Levels of Digital IO ports 1 and 2.

set_dio_role

set_dio_role(port: int, role: DioRole) -> None

Configure the role of Digital IO port 1 or 2.

dio_roles

dio_roles() -> tuple[DioPort, DioPort]

Roles and levels of Digital IO ports 1 and 2.

Diagnostics

Diagnostics(device: Device)

Health and bench diagnostics (device.diagnostics).

Bind to a device.

debug_output property writable

debug_output: bool

Debug text output on the USB link (effective on debug builds only).

spi_clock_mhz property writable

spi_clock_mhz: int

Panel SPI clock in MHz (1-30).

health

health() -> Health

Controller health counters and previous-boot breadcrumbs.

crash_report

crash_report() -> CrashReport

The last CPU fault recorded by the controller, if any.

sd_info

sd_info() -> SdInfo

SD card identity and geometry (mounted is False without a card).

set_sd_diag

set_sd_diag(
    *,
    legacy_seek: bool = False,
    no_same_index_skip: bool = False,
) -> tuple[bool, bool]

Set the SD bench switches and return the flags now in force.

ip_address

ip_address() -> str

Ethernet IP address (empty while Ethernet is not running).

PanelFirmware

PanelFirmware(device: Device)

Update the panels' own firmware (device.panel_firmware).

The controller keeps one panel image on its SD card; upload it, then program and verify panels one at a time, by panel number (the first panel is 1). The display must be off.

Bind to a device.

upload

upload(image: bytes) -> int

Store a panel firmware image and return its CRC-32.

Raises:

Type Description
ProtocolError

If the controller's CRC differs from the local one.

info

info() -> FirmwareImageInfo | None

Footer of the stored image, or None if no image is stored.

program

program(panel_number: int) -> str

Flash one panel from the stored image and return the controller's report.

verify

verify(panel_number: int) -> PanelCheck

Check whether a panel runs the stored image.

PanelCheck dataclass

PanelCheck(matches: bool, message: str)

Result of verifying a panel's firmware.

Attributes:

Name Type Description
matches bool

The panel runs the stored image.

message str

The controller's report.

discovery

Finding controllers among the computer's serial ports.

TEENSY_VID module-attribute

TEENSY_VID = 5824

TEENSY_PID module-attribute

TEENSY_PID = 1155

PortInfo dataclass

PortInfo(
    device: str,
    description: str,
    vid: int | None,
    pid: int | None,
    serial_number: str | None,
)

A serial port found on this computer.

Attributes:

Name Type Description
device str

Name to open, e.g. "/dev/ttyACM0" or "COM5".

description str

Human-readable description from the OS.

vid int | None

USB vendor id, or None for non-USB ports.

pid int | None

USB product id, or None for non-USB ports.

serial_number str | None

USB serial number, if reported.

is_teensy property

is_teensy: bool

True if the USB ids are those of a Teensy in serial mode.

find_ports

find_ports(*, all_ports: bool = False) -> list[PortInfo]

List serial ports that may be a G6 arena controller.

Nothing is sent to any port. A Teensy-based device that is not a controller has the same USB ids, so a match is a candidate, not a guarantee; Device.open() can confirm candidates by probing them.

Parameters:

Name Type Description Default
all_ports bool

List every serial port, not only Teensy ones.

False

Returns:

Type Description
list[PortInfo]

Matching ports, sorted by device name.

Example

for port in find_ports(): # doctest: +SKIP ... print(port.device, port.description) /dev/ttyACM0 Teensyduino Serial

Patterns and arenas

pattern

Patterns from pixel arrays: build and read .pat files and stream frames.

A Pattern holds one image per frame for a whole arena: rows * 20 pixels high and cols * 20 wide, with values 0/1 (GS2) or 0-15 (GS16). Images may be numpy arrays or nested lists; frames come back as numpy arrays.

import numpy as np
from arena_interface import Arena, GrayLevel, Pattern

h, w = Arena.preset("G6_2x10").pixel_shape
x = np.arange(w)
stripes = [np.tile(np.where((x + f) % 20 < 10, 15, 0), (h, 1)) for f in range(20)]
pattern = Pattern.from_frames(stripes, gray_level=GrayLevel.GS16)
data = pattern.to_bytes()               # a .pat file

Orientation: by default row 0 of an image is the top of the arena (origin="upper", as in numpy and matplotlib's imshow). Pass origin="lower" for row 0 at the bottom, the convention of the MATLAB and JavaScript tools. Columns run left to right either way.

The library converts to the on-wire layout: panels in row-major order from the bottom row of panels, and within each panel block the first 20 pixels are the panel's top row (as the panel firmware reads them; see docs/PROTOCOL.md).

Origin module-attribute

Origin = Literal['upper', 'lower']

Pattern

Pattern(
    frames: Frames,
    *,
    arena: Arena,
    gray_level: GrayLevel,
    duty_cycles: Sequence[int],
    observer_id: int = 0,
)

A sequence of arena images, convertible to a .pat file.

Build one with from_frames or read a file with from_bytes. Patterns are immutable.

Create from validated internal frames; use the class methods instead.

arena instance-attribute

arena = arena

Arena the images are drawn for.

gray_level instance-attribute

gray_level = GrayLevel(gray_level)

GS2 (on/off) or GS16 (16 levels).

duty_cycles instance-attribute

duty_cycles = tuple(duty_cycles)

Brightness byte (1-255) of each frame.

observer_id instance-attribute

observer_id = observer_id

Observer id stored in the file header (0-63, host metadata).

frame_count property

frame_count: int

Number of frames.

pixel_shape property

pixel_shape: tuple[int, int]

(height, width) of each image.

from_frames classmethod

from_frames(
    frames: Sequence[Any] | Any,
    *,
    gray_level: GrayLevel = GS16,
    arena: Arena | tuple[int, int] | None = None,
    origin: Origin = "upper",
    duty_cycle: int | Sequence[int] = DEFAULT_DUTY_CYCLE,
    observer_id: int = 0,
) -> Pattern

Build a pattern from one image per frame.

Parameters:

Name Type Description Default
frames Sequence[Any] | Any

Images, each rows * 20 by cols * 20 pixels, as 2-D numpy arrays or nested lists; or one 3-D array (frames, height, width). Values may be any integer or boolean type.

required
gray_level GrayLevel

GS2 (values 0/1) or GS16 (values 0-15).

GS16
arena Arena | tuple[int, int] | None

The arena the images are drawn for: an Arena, (rows, cols), or None to infer a full arena from the image size.

None
origin Origin

"upper" if row 0 is the top of the arena, "lower" if it is the bottom.

'upper'
duty_cycle int | Sequence[int]

Brightness 1-255, for all frames or one per frame.

DEFAULT_DUTY_CYCLE
observer_id int

Observer id for the file header (0-63).

0

Returns:

Type Description
Pattern

The pattern.

Raises:

Type Description
ValueError

If the images have the wrong shape or values.

TypeError

If the pixel values are not integers or booleans.

Example

blank = np.zeros((1, 40, 200), dtype=np.uint8) Pattern.from_frames(blank, gray_level=GrayLevel.GS2).arena Arena(rows=2, cols=10, installed_columns=None, name='', arena_id=0)

from_bytes classmethod

from_bytes(data: bytes) -> Pattern

Read a .pat file (G6, header version 2).

Raises:

Type Description
ProtocolError

If the file is malformed or a checksum is wrong.

frame

frame(index: int, *, origin: Origin = 'upper') -> Frames

One frame as a (height, width) uint8 array (a copy).

frame(i)[0, 0] is the top-left pixel (origin="upper").

to_numpy

to_numpy(*, origin: Origin = 'upper') -> Frames

All frames as a (frames, height, width) uint8 array (a copy).

fit_to

fit_to(rows: int, cols: int) -> Pattern

Place the pattern on a controller's panel grid.

Used when the rig is smaller than the grid the firmware is built for (e.g. a 3x10 rig on 4x10 firmware, or G6_3x12of18 on 4x12). Grid column c goes to firmware column c; columns beyond the firmware's are dropped, so every installed column must fit. Rows are repeated up the frame from the bottom, so the panels light whichever row connector they are on (the JS tools' rule).

Raises:

Type Description
ValueError

If the rig does not fit the grid.

stream_payload

stream_payload(index: int) -> bytes

One frame as a STREAM_FRAME payload ("FR", index, panel blocks).

to_bytes

to_bytes() -> bytes

Encode as a .pat file (G6, header version 2, full panel mask).

Raises:

Type Description
ValueError

If the grid has more than 48 panels (fit it to the controller's grid first with fit_to).

arena

Arena geometry: how many panels, and which of them are installed.

An Arena is a grid of rows x cols G6 panels (20 x 20 pixels each). Partial arenas leave some columns empty; their patterns are still drawn on the full grid, with the missing columns blank.

The rig's arena can differ from the grid the controller firmware is built for (e.g. a G6_3x12of18 rig on 4 x 12 firmware). Images are drawn for the rig and fitted to the firmware's grid when sent; see Pattern.fit_to.

The G6 arenas registered in maDisplayTools are built in as presets:

from arena_interface import Arena

walking = Arena.preset("G6_2x8of10")
print(walking.pixel_shape)      # (40, 200)

PRESETS module-attribute

PRESETS: dict[str, Arena] = {
    a.name: a
    for a in (
        _preset("G6_2x10", 1, 2, 10),
        _preset("G6_2x8of10", 2, 2, 10, range(1, 9)),
        _preset("G6_3x12of18", 3, 3, 18, range(0, 12)),
        _preset("G6_3x16_full", 4, 3, 16),
        _preset("G6_3x10", 5, 3, 10),
        _preset("G6_4x10", 6, 4, 10),
        _preset("G6_1x12of18", 7, 1, 18, range(0, 12)),
        _preset("G6_3x10of14", 8, 3, 14, range(0, 10)),
    )
}

Arena dataclass

Arena(
    rows: int,
    cols: int,
    installed_columns: tuple[int, ...] | None = None,
    name: str = "",
    arena_id: int = 0,
)

Geometry of a G6 arena.

Attributes:

Name Type Description
rows int

Panel rows.

cols int

Panel columns of the full grid (including uninstalled ones).

installed_columns tuple[int, ...] | None

Grid columns that hold panels, numbered from 0 at the left, or None if every column does.

name str

Registry name, e.g. "G6_2x10" (empty for custom arenas).

arena_id int

Registry id stored in pattern headers (0 = unspecified).

panel_count property

panel_count: int

Panels in the full grid.

pixel_shape property

pixel_shape: tuple[int, int]

(height, width) in pixels of a full-grid image.

columns property

columns: tuple[int, ...]

Installed columns (all of them for a full arena).

is_partial property

is_partial: bool

True if some grid columns have no panels.

preset classmethod

preset(name: str) -> Arena

A registered arena by name.

Raises:

Type Description
KeyError

If the name is unknown; the message lists the presets.

from_id classmethod

from_id(arena_id: int) -> Arena | None

The preset with this registry id, or None.

Host-paced playback

playback

Host-paced playback: the computer decides when each frame is shown.

Three ways to use it, all on a Device:

dev.show_pattern(4)
report = dev.play_frames(range(200), fps=200)        # frames of an SD pattern
report = dev.play_images(images, fps=120)            # streamed images

player = dev.start_frames(range(200), fps=200)       # same, in the background
report = player.wait()

for tick in dev.pace(rate_hz=200, duration=10):      # live: you choose each frame
    dev.show_frame(choose_frame())

Timing: frames are scheduled against a fixed clock (no drift). The scheduler sleeps until just before each slot and then busy-waits for sub-millisecond accuracy. When a frame cannot be sent on time, late="skip" drops frames whose slot has passed so the sequence keeps its schedule, and late="send" sends every frame, so the sequence runs long. Either way the PlaybackReport says what happened, and falling behind is logged on arena_interface.playback.

A frame is only displayed if it stays in place for at least one refresh of the controller, so fps should not exceed the refresh rate (dev.refresh_rate); a PerformanceWarning is issued if it does. Frames of an SD pattern also wait for the controller's SD read, which occasionally stalls, so at fps close to the refresh rate a frame can now and then be replaced unseen; play_frames(..., verify=True) reports it.

LatePolicy module-attribute

LatePolicy = Literal['skip', 'send']

PlaybackReport dataclass

PlaybackReport(
    rate_hz: float,
    planned: int,
    sent: int,
    skipped: int,
    late: int,
    median_late_s: float,
    p99_late_s: float,
    max_late_s: float,
    duration_s: float,
    stopped: bool = False,
    refresh_rate: int | None = None,
    changes: int | None = None,
    displayed: int | None = None,
    superseded: int | None = None,
)

What happened during a playback.

Attributes:

Name Type Description
rate_hz float

Requested frames (or ticks) per second.

planned int

Frames in the sequence (ticks for an open-ended pacer: those that came due).

sent int

Frames actually sent.

skipped int

Frames dropped because their slot had passed.

late int

Frames sent more than half a frame period after their slot.

median_late_s float

Median lateness of the frames sent.

p99_late_s float

99th-percentile lateness of the frames sent.

max_late_s float

Largest lateness of a frame sent.

duration_s float

Time from the first slot to the end.

stopped bool

Playback was stopped before the end.

refresh_rate int | None

The controller's refresh rate during playback, if read.

changes int | None

Frame changes the sequence asked for, counting from the frame on show when playback started (verify=True; a frame equal to the one before it is not a change). None if frames were skipped.

displayed int | None

Frame changes the controller logged as reaching the panels (verify=True). Equal to changes when every frame was displayed.

superseded int | None

Frames replaced before they reached the panels (verify=True).

on_schedule property

on_schedule: bool

True if no frame was skipped or late.

Playback

Playback(
    target: Callable[
        [Event, Callable[[int], None]], PlaybackReport
    ],
    total: int,
)

A playback running in a background thread.

Returned by Device.start_frames and Device.start_images. Your thread may keep using the device; each of its commands delays the next frame slightly (the report shows the effect).

Use wait to block until it ends, or stop to end it early. As a context manager, leaving the block stops playback if it is still running.

Start target in a thread; total is the number of frames.

total instance-attribute

total = total

Frames in the sequence.

running property

running: bool

True until playback finishes, is stopped, or fails.

progress property

progress: int

Frames of the sequence passed so far (sent or skipped).

report property

report: PlaybackReport | None

The report once playback has ended without error, else None.

stop

stop() -> PlaybackReport

Stop playback (the current frame stays displayed) and return the report.

wait

wait(timeout: float | None = None) -> PlaybackReport

Block until playback ends and return its report.

Raises:

Type Description
TimeoutError

If timeout seconds pass first.

DeviceError

Any error the playback thread hit, re-raised here.

Pacer

Pacer(
    rate_hz: float,
    *,
    duration: float | None = None,
    count: int | None = None,
    late: LatePolicy = "skip",
    refresh_rate: int | None = None,
)

A fixed-rate clock for live playback; see Device.pace.

Iterate to receive one Tick per slot and send your frame in the loop body. After the loop, report summarises the timing.

Validate the schedule; timing starts when iteration starts.

report property

Timing of the ticks so far ("sent" counts ticks yielded).

stop

stop() -> None

End the iteration at the next slot (e.g. from another thread).

Tick dataclass

Tick(index: int, time: float, late_by: float, skipped: int)

One slot of a Pacer schedule.

Attributes:

Name Type Description
index int

Slot number, counting from 0 (skipped slots are counted).

time float

Wall-clock time (time.time()) the slot was due.

late_by float

Seconds between the slot's due time and this tick.

skipped int

Slots skipped just before this one (late="skip" only).

Streaming

streaming

Continuous data from the controller: telemetry events and periodic samples.

The controller never sends data on its own, so both are polling loops exposed as blocking iterators:

with Device.open() as dev:
    for event in dev.telemetry.events(duration=10):
        print(event.time, event.record)

    for s in dev.sample(dev.io.read_analog_in, rate_hz=100, duration=5):
        print(s.time, s.value.ain1_mv)

Times are wall-clock seconds (time.time()).

Telemetry

Telemetry(device: Device)

The controller's telemetry ring (device.telemetry).

The controller logs every command it receives, every change of the displayed frame and every state change, with microsecond timestamps. The ring survives software resets. Recording is on by default.

Records read from the controller are kept until they have been returned to you, so breaking out of an events loop and starting a new one (or calling drain) neither loses nor repeats events.

Attributes:

Name Type Description
lost

Records lost to ring overflow, as seen by this connection.

Bind to a device.

configure

configure(
    events: bool = True,
    *,
    synthetic: bool = False,
    synthetic_rate: int | None = None,
) -> None

Turn event recording and the synthetic test producer on or off.

read_block

read_block(ack_seq: int | None = None) -> TelemetryBlock

Low level: acknowledge records up to ack_seq and read the next block.

Mixing this with events() or drain() on the same device can acknowledge records those have not returned yet.

drain

drain() -> list[TelemetryEvent]

Return every waiting event and acknowledge them all.

events

events(
    *,
    poll_interval: float = 0.05,
    duration: float | None = None,
) -> EventStream

Stream events as the controller records them.

Parameters:

Name Type Description Default
poll_interval float

Seconds between polls when no records are waiting.

0.05
duration float | None

Stop after this many seconds; None runs until you break out of the loop.

None

Returns:

Type Description
EventStream

An iterable EventStream.

EventStream

EventStream(
    telemetry: Telemetry,
    poll_interval: float,
    duration: float | None,
)

Iterator over telemetry events; see device.telemetry.events().

Attributes:

Name Type Description
lost

Records lost to ring overflow during this stream.

Create the stream; nothing is read until iteration starts.

TelemetryEvent dataclass

TelemetryEvent(time: float | None, record: TelemetryRecord)

One telemetry record with its host time.

Attributes:

Name Type Description
time float | None

Wall-clock time (time.time() seconds) at which the controller recorded the event, or None for records written before the controller's last reset.

record TelemetryRecord

The decoded record (FrameRecord, StateRecord, CommandRecord or UnknownRecord); record.t_us is the raw controller time.

seq property

seq: int

Record sequence number.

Sampler

Sampler(
    read: Callable[[], _T],
    rate_hz: float,
    duration: float | None,
    count: int | None,
)

Bases: Generic[_T]

Iterator calling a read function at a fixed rate; see device.sample().

Attributes:

Name Type Description
skipped

Samples skipped because a read finished too late.

Validate the schedule; nothing is read until iteration starts.

Sample dataclass

Sample(time: float, value: _T)

Bases: Generic[_T]

One reading taken by Sampler.

Attributes:

Name Type Description
time float

Wall-clock time of the reading (midpoint of the request).

value _T

What the read function returned.

telemetry

Decoding of the controller's telemetry ring (GET_TELEMETRY_BLOCK).

The controller logs every command, every displayed frame change and every state change into a ring buffer that survives software resets. A host drains it with GET_TELEMETRY_BLOCK, acknowledging records once stored. Record layout follows Telemetry.h (ring layout version 2).

CommandRecord dataclass

CommandRecord(
    seq: int,
    t_us: int,
    opcode: int,
    status: int,
    params: bytes,
)

Bases: _RecordBase

A command the controller received.

Attributes:

Name Type Description
seq int

Record sequence number.

t_us int

Receipt time (controller microseconds; wraps every ~71.6 min).

opcode int

Command opcode (0xFE for synthetic test records).

status int

Status of the reply (0xFF if none was sent).

params bytes

Up to the first 8 parameter bytes of the request.

FrameRecord dataclass

FrameRecord(
    seq: int,
    t_us: int,
    index: int,
    pattern_id: int,
    sd_load_us: int,
    spi_us: int,
    request_age_us: int,
    superseded: int,
    from_sd: bool,
    contiguous: bool,
)

Bases: _RecordBase

A change of the displayed frame.

Attributes:

Name Type Description
seq int

Record sequence number.

t_us int

Start of the SPI transfer to the panels.

index int

Frame index shown.

pattern_id int

Pattern shown.

sd_load_us int

Duration of the SD read that produced the frame.

spi_us int

Duration of the SPI transfer.

request_age_us int

Time from the request (or decision) to the transfer.

superseded int

Frames loaded but replaced before being shown.

from_sd bool

The frame was read from the SD card.

contiguous bool

The pattern file is stored contiguously.

StateRecord dataclass

StateRecord(
    seq: int,
    t_us: int,
    kind: StateKind | int,
    code: int,
    arg: int,
)

Bases: _RecordBase

A state transition or other controller event.

Attributes:

Name Type Description
seq int

Record sequence number.

t_us int

Event time.

kind StateKind | int

Event kind (raw int for kinds unknown to this library).

code int

Kind-specific code byte.

arg int

Kind-specific argument.

new_state property

new_state: ArenaState | None

For STATE_CHANGE records, the state entered; otherwise None.

UnknownRecord dataclass

UnknownRecord(seq: int, t_us: int, type: int, raw: bytes)

Bases: _RecordBase

A record of a type this library does not know.

Attributes:

Name Type Description
seq int

Record sequence number.

t_us int

Record time.

type int

Record type byte.

raw bytes

The complete record bytes.

StateKind

Bases: IntEnum

Kinds of STATE telemetry records.

TelemetryBlock dataclass

TelemetryBlock(
    t_now_us: int,
    first_seq: int,
    dropped: int,
    more: bool,
    events_enabled: bool,
    survived_reboot: bool,
    heap_collision: bool,
    synthetic: bool,
    boot_count: int,
    records: tuple[TelemetryRecord, ...],
)

One GET_TELEMETRY_BLOCK reply.

Attributes:

Name Type Description
t_now_us int

Controller time when the reply was built.

first_seq int

Sequence number of the first record (0 if none).

dropped int

Records lost to ring overflow since the ring was created.

more bool

More unread records are waiting.

events_enabled bool

Event recording is on.

survived_reboot bool

The ring contents were kept across a reset.

heap_collision bool

The ring was disabled to protect memory.

synthetic bool

The synthetic test producer is running.

boot_count int

Resets the ring has survived.

records tuple[TelemetryRecord, ...]

Decoded records, oldest first.

last_seq property

last_seq: int | None

Sequence number of the last record, to acknowledge next; None if empty.

Values returned by the device

Request builders and response decoders for every controller command.

Each command has a builder that validates its arguments and returns a Request: the bytes to send, the opcode the reply will echo, a suitable timeout, the kind of exchange, and the capability or firmware flag the device must advertise. Replies are turned into dataclasses by the decode_* functions.

Arguments are validated against the ranges the firmware accepts, because several invalid commands make the firmware show an error glyph and stop the display rather than just returning an error.

ControllerInfo dataclass

ControllerInfo(
    protocol_version: int,
    capabilities: Capability,
    mac: str | None,
)

Reply to GET_CONTROLLER_INFO.

Attributes:

Name Type Description
protocol_version int

Controller protocol version (1).

capabilities Capability

Advertised capability bits.

mac str | None

Controller MAC address "AA:BB:...", or None if not reported.

FirmwareVersion dataclass

FirmwareVersion(
    rows: int,
    cols: int,
    flags: FirmwareFlag,
    git_sha: str,
    build_date: str,
    branch: str,
)

Reply to GET_FIRMWARE_VERSION: which firmware build is running.

Attributes:

Name Type Description
rows int

Panel rows of the arena this build drives.

cols int

Panel columns of the arena this build drives.

flags FirmwareFlag

Build flags (features present, debug build, dirty tree).

git_sha str

Short git commit of the build.

build_date str

Build date "YYYY-MM-DD".

branch str

Git branch of the build.

panel_count property

panel_count: int

Number of panels in the arena.

FramePosition dataclass

FramePosition(index: int, frame_count: int)

Current frame of the open pattern.

Attributes:

Name Type Description
index int

0-based frame index.

frame_count int

Frames in the open pattern (0 if none is open).

PatternInfo dataclass

PatternInfo(
    frame_count: int,
    gray_level: GrayLevel,
    rows: int,
    cols: int,
    arena_id: int,
    observer_id: int,
    file_size: int,
    duty_cycle: int,
)

Header metadata of a pattern on the SD card.

Attributes:

Name Type Description
frame_count int

Number of frames.

gray_level GrayLevel

GS2 (on/off) or GS16 (16 levels).

rows int

Panel rows the pattern was made for.

cols int

Panel columns the pattern was made for.

arena_id int

Arena id stored in the header (host metadata).

observer_id int

Observer id stored in the header (host metadata).

file_size int

File size in bytes.

duty_cycle int

Brightness byte of frame 0, panel 0.

AnalogInputs dataclass

AnalogInputs(ain1_mv: int, ain2_mv: int)

Analog input readings (±10 V inputs, uncalibrated).

Attributes:

Name Type Description
ain1_mv int

Analog In 1 in millivolts.

ain2_mv int

Analog In 2 in millivolts.

DioPort dataclass

DioPort(role: DioRole, high: bool)

Role and live level of one Digital IO port.

Attributes:

Name Type Description
role DioRole

Configured role.

high bool

Pin level (the BNC level when the port is an input).

Health dataclass

Health(
    version: int,
    sd_mounted: bool,
    pattern_open: bool,
    display_active: bool,
    breadcrumb_valid: bool,
    uptime_ms: int,
    loop_count: int,
    loop_max_us: int,
    loop_max_1s_us: int,
    sd_reads: int,
    sd_read_max_us: int,
    sd_error: int,
    sd_error_data: int,
    frames_sent: int,
    refresh_isr_count: int,
    frame_position_commands: int,
    state: ArenaState | int,
    current_frame: int,
    reset_cause: int,
    previous_op: HealthOp | int,
    previous_op_us: int,
    previous_op_arg: int | None = None,
    previous_slow_op: HealthOp | int | None = None,
    previous_slow_us: int | None = None,
    slow_op: HealthOp | int | None = None,
    slow_us: int | None = None,
    watchdog: WatchdogStatus | None = None,
    raw: bytes = b"",
)

Controller health counters (GET_HEALTH).

Counters are cumulative since boot; nothing is cleared by reading. The "previous" fields describe the boot before the last reset (they survive a software or watchdog reset, not a power cycle).

Attributes:

Name Type Description
version int

Payload schema version.

sd_mounted bool

An SD card is mounted.

pattern_open bool

A pattern file is open.

display_active bool

The display is running (state is not ALL_OFF).

breadcrumb_valid bool

The previous_* fields are meaningful.

uptime_ms int

Milliseconds since boot (wraps after ~49.7 days).

loop_count int

Main-loop iterations since boot.

loop_max_us int

Longest main-loop iteration since boot.

loop_max_1s_us int

Longest iteration in the last full second.

sd_reads int

Frame reads from the SD card since boot.

sd_read_max_us int

Longest frame read since boot.

sd_error int

SD driver error code (0 = none).

sd_error_data int

SD driver error data.

frames_sent int

Frames pushed to the panels (same as GET_FRAMES_SENT).

refresh_isr_count int

Refresh-timer interrupts since boot.

frame_position_commands int

SET_FRAME_POSITION commands received.

state ArenaState | int

Current controller state.

current_frame int

Current frame index.

reset_cause int

Raw reset-cause register captured at boot.

previous_op HealthOp | int

What the previous boot was doing last.

previous_op_us int

Timestamp of that operation (µs).

previous_op_arg int | None

Opcode, when previous_op is a command.

previous_slow_op HealthOp | int | None

Slowest operation of the previous boot.

previous_slow_us int | None

Its duration (µs).

slow_op HealthOp | int | None

Slowest operation of this boot.

slow_us int | None

Its duration (µs).

watchdog WatchdogStatus | None

Watchdog section (payload version 2+), else None.

raw bytes

The complete payload, for fields added in later versions.

WatchdogStatus dataclass

WatchdogStatus(
    prev_isr_last: IsrId | int,
    prev_isr_count: int,
    prev_pc: int,
    prev_lr: int,
    flags: int,
    isr_last: IsrId | int,
    isr_count: int,
    kicks: int,
)

Watchdog and interrupt section of GET_HEALTH (payload version 2 and later).

Attributes:

Name Type Description
prev_isr_last IsrId | int

Interrupt the previous boot was inside when it died.

prev_isr_count int

Interrupt entries in the previous boot.

prev_pc int

Program counter captured by the watchdog (if captured).

prev_lr int

Link register captured by the watchdog (if captured).

flags int

Raw watchdog flag bits.

isr_last IsrId | int

Interrupt currently executing.

isr_count int

Interrupt entries this boot.

kicks int

Watchdog refreshes this boot.

armed property

armed: bool

The watchdog is running.

previous_reset_was_watchdog property

previous_reset_was_watchdog: bool

The last reset was caused by the watchdog.

previous_pc_captured property

previous_pc_captured: bool

prev_pc and prev_lr are valid.

HealthOp

Bases: IntEnum

What the controller was doing (GET_HEALTH breadcrumb / slow-op codes).

IsrId

Bases: IntEnum

Interrupt handlers tracked by GET_HEALTH.

CrashReport dataclass

CrashReport(
    raw: bytes,
    length: int,
    ipsr: int,
    cfsr: int,
    hfsr: int,
    mmfar: int,
    bfar: int,
    return_address: int,
    xpsr: int,
    temperature_c: float,
    time: int,
)

Last CPU fault recorded by the Teensy core (GET_CRASHREPORT).

Attributes:

Name Type Description
raw bytes

The full 128-byte record.

length int

Record length word (11 words when a fault was recorded).

ipsr int

Exception number of the fault.

cfsr int

Configurable fault status register.

hfsr int

Hard fault status register.

mmfar int

MemManage fault address.

bfar int

Bus fault address.

return_address int

Address of the faulting instruction.

xpsr int

Program status register.

temperature_c float

CPU temperature at the fault.

time int

RTC time of the fault.

present property

present: bool

A fault has been recorded.

fault_name property

fault_name: str | None

Name of the fault type, or None if no fault is recorded.

SdInfo dataclass

SdInfo(
    mounted: bool,
    cid_valid: bool,
    csd_valid: bool,
    card_type: int,
    fat_type: int,
    sectors: int,
    bytes_per_cluster: int,
    cid: bytes,
    legacy_seek: bool,
    no_same_index_skip: bool,
    legacy_seek_applied: bool,
)

SD card identity and geometry (GET_SD_INFO).

Attributes:

Name Type Description
mounted bool

A card is mounted (other fields are zero otherwise).

cid_valid bool

cid was read.

csd_valid bool

sectors was read.

card_type int

0 none, 1 SD1, 2 SD2, 3 SDHC/SDXC.

fat_type int

12, 16 or 32 for FAT, 64 for exFAT, 0 unknown.

sectors int

Capacity in 512-byte sectors.

bytes_per_cluster int

Cluster size.

cid bytes

Raw 16-byte card identification register.

legacy_seek bool

SD diagnostic switch: legacy seek requested.

no_same_index_skip bool

SD diagnostic switch: same-index skip disabled.

legacy_seek_applied bool

Legacy seek is in force for the open file.

capacity_bytes property

capacity_bytes: int

Card capacity in bytes.

manufacturer_id property

manufacturer_id: int

Manufacturer id from the CID register.

product_name property

product_name: str

Product name from the CID register.

serial_number property

serial_number: int

Product serial number from the CID register.

FirmwareImageInfo dataclass

FirmwareImageInfo(
    magic: str, version: str, crc32: int, size: int
)

Footer of the panel firmware image stored on the SD card.

Attributes:

Name Type Description
magic str

Image magic string.

version str

Panel firmware version string.

crc32 int

CRC-32 of the image.

size int

Image size in bytes.

Enumerations and flags

Protocol constants and enumerations for the G6 arena controller.

Values come from the firmware sources (commands.h, constants.h, Version.h, CommandProcessor.h); see docs/PROTOCOL.md.

TrialMode

Bases: IntEnum

Display modes selectable with TRIAL_PARAMS.

OPEN_LOOP class-attribute instance-attribute

OPEN_LOOP = 2

Frames advance automatically at the frame rate.

SHOW_FRAME class-attribute instance-attribute

SHOW_FRAME = 3

The host chooses the frame (SET_FRAME_POSITION).

CLOSED_LOOP class-attribute instance-attribute

CLOSED_LOOP = 4

Frame rate follows Analog In 1 times the gain.

PanelDisplayMode

Bases: IntEnum

How panels present each frame (SET_PANEL_DISPLAY_MODE).

GrayLevel

Bases: IntEnum

Brightness levels per pixel; the value is the number of levels.

ArenaState

Bases: IntEnum

What the controller is doing (GET_HEALTH state field).

DioRole

Bases: IntEnum

Role of a "Digital IO (5V)" BNC port.

AoMode

Bases: IntEnum

What drives the analog output.

PROGRAMMABLE class-attribute instance-attribute

PROGRAMMABLE = 0

Set by SET_AO_VOLTAGE or a lookup table.

FRAME_NUMBER class-attribute instance-attribute

FRAME_NUMBER = 1

Tracks the pattern frame index, 0 V (first) to 5 V (last).

AoLutMode

Bases: IntEnum

How an analog-output lookup table advances.

FRAME_LOCKED class-attribute instance-attribute

FRAME_LOCKED = 0

One entry per displayed frame index.

TIME_BASED class-attribute instance-attribute

TIME_BASED = 1

Steps at a fixed rate.

Capability

Bases: IntFlag

GET_CONTROLLER_INFO capability bitmap.

IO_EXT class-attribute instance-attribute

IO_EXT = 32

SET_AO_MODE, GET_ANALOG_IN, SET_DIO_ROLE, GET_DIO_ROLE.

HEALTH class-attribute instance-attribute

HEALTH = 128

GET_HEALTH and GET_FIRMWARE_VERSION.

FirmwareFlag

Bases: IntFlag

GET_FIRMWARE_VERSION flags byte.

TELEMETRY class-attribute instance-attribute

TELEMETRY = 4

SET_TELEMETRY and GET_TELEMETRY_BLOCK.

CRASH_REPORT class-attribute instance-attribute

CRASH_REPORT = 8

GET_CRASHREPORT.

SD_FAST_PATH class-attribute instance-attribute

SD_FAST_PATH = 32

GET_SD_INFO.

SD_DIAG class-attribute instance-attribute

SD_DIAG = 64

SET_SD_DIAG.

ErrorCode

Bases: IntEnum

Controller error codes (CE_*), used as status bytes and error glyphs.

Status 1 is also used for generic validation failures, so a status of 1 does not necessarily mean an unknown command.

Exceptions

errors

Exceptions raised by arena_interface.

Every exception the library raises on purpose derives from DeviceError, so a caller can catch them all with one except clause:

from arena_interface import DeviceError

try:
    ...
except DeviceError as exc:
    print(f"arena problem: {exc}")

Invalid arguments (a frame index out of range, a payload of the wrong size) are programming errors and raise the built-in ValueError / TypeError instead.

DeviceError

Bases: Exception

Base class for all errors raised by arena_interface.

DeviceNotFound

Bases: DeviceError

No device could be found or the serial port could not be opened.

DeviceDisconnected

Bases: DeviceError

The serial connection was lost (device unplugged or reset).

The connection is closed when this is raised; open a new one to continue.

DeviceTimeout

Bases: DeviceError, TimeoutError

The device did not answer, or a bulk transfer stalled, within the timeout.

Also a subclass of the built-in TimeoutError.

ProtocolError

Bases: DeviceError

The device sent data that does not follow the wire protocol.

CommandError

CommandError(opcode: int, status: int, message: str = '')

Bases: DeviceError

The device rejected a command (non-zero status).

Attributes:

Name Type Description
opcode

Opcode of the rejected command.

status

Status byte returned by the device.

message

The device's explanation (may be empty).

Create the error from a response's opcode, status and message.

UnsupportedCommand

Bases: DeviceError

The connected firmware does not advertise support for this command.

Raised before anything is sent, because the firmware reacts to an unknown command by showing an error glyph and stopping the display.

PerformanceWarning

Bases: UserWarning

A setting that will not perform as intended.

Issued (with :mod:warnings, not raised) for example when frames are requested faster than the controller's refresh rate can display them, or when the refresh rate is above what the panels or the SPI link can use.

Simulated controller

testing

A simulated G6 arena controller for tests, examples and development.

FakePort behaves like a pyserial port connected to a controller. Behind it, a FakeController parses the bytes written to the port the way the firmware does and answers with the same replies: status codes, messages, payload layouts and side effects (error glyphs that stop the display, commands refused while the display runs, index shifts after deleting a pattern, and so on). It keeps an in-memory SD card, the telemetry ring and the I/O state.

from arena_interface.testing import FakePort
from arena_interface.transport import Transport

with Transport(FakePort()) as link:
    ...

The controller can also inject faults: unplugging the device, going silent, delaying replies, or emitting debug text. A controller outlives its ports, so a test can unplug, then connect a new FakePort(controller) to simulate a reconnect.

What is not emulated: panel pixels (frames are accepted, not rendered), the precise wording of panel-programming messages, and refresh timing beyond a simple frames-sent estimate.

FakeController

FakeController(
    *,
    rows: int = 2,
    cols: int = 10,
    patterns: Mapping[str, bytes] | None = None,
    sd_card: bool = True,
    capabilities: Capability = _DEFAULT_CAPS,
    firmware_flags: FirmwareFlag = _DEFAULT_FLAGS,
    mac: bytes = fromhex("04e9e5000001"),
    git_sha: str = "fake0001",
    branch: str = "simulated",
    build_date: str = "2026-01-01",
)

Simulated controller state and command handling.

Parameters:

Name Type Description Default
rows int

Panel rows of the arena this "firmware build" drives.

2
cols int

Panel columns.

10
patterns Mapping[str, bytes] | None

Initial SD-card patterns, {file name: contents}. By default two small demo patterns matching the arena are created.

None
sd_card bool

Whether an SD card is inserted.

True
capabilities Capability

GET_CONTROLLER_INFO capability bits. Commands gated by a missing bit behave as unknown commands, like older firmware.

_DEFAULT_CAPS
firmware_flags FirmwareFlag

GET_FIRMWARE_VERSION flags (gating as above).

_DEFAULT_FLAGS
mac bytes

Controller MAC address bytes.

fromhex('04e9e5000001')
git_sha str

Reported firmware commit.

'fake0001'
branch str

Reported firmware branch.

'simulated'
build_date str

Reported build date.

'2026-01-01'

Attributes:

Name Type Description
analog_in tuple[int, int]

Millivolts reported on Analog In 1 and 2.

analog_loopback tuple[float, float] | None

(gain, offset_mv) to simulate a cable from the analog output to Analog In 1 (ain1 = gain * out + offset), or None.

dio_inputs list[bool]

BNC levels seen on Digital IO ports in an input role.

response_delay

Seconds before each reply becomes readable.

muted

When True, commands are processed but no reply is sent.

received list[bytes]

Every complete message received, in order (for assertions).

Create a controller in its power-on state.

panel_count property

panel_count: int

Panels in the arena.

state property

state: ArenaState

Current controller state (time-based transitions applied).

pattern_names property

pattern_names: list[str]

Pattern file names in index order (index = position + 1).

unplug

unplug() -> None

Disconnect every open port, as if the USB cable were pulled.

inject

inject(data: bytes) -> None

Send unsolicited bytes to every connected port (e.g. line noise).

feed

feed(data: bytes) -> bytes

Process bytes from the host and return the bytes sent back.

FakePort

FakePort(
    controller: FakeController | None = None,
    **controller_options: object,
)

A pyserial-compatible port connected to a simulated controller.

Parameters:

Name Type Description Default
controller FakeController | None

Controller to connect to; a new default one if omitted.

None
**controller_options object

Passed to FakeController when no controller is given (e.g. rows=4, cols=12).

{}
Example

from arena_interface.transport import Transport from arena_interface import messages port = FakePort() with Transport(port) as link: ... reply = link.request(messages.get_file_count().frame, expect=0x80) messages.decode_u16(reply.payload) 2

Connect a new port to controller.

in_waiting property

in_waiting: int

Bytes ready to read.

read

read(size: int = 1) -> bytes

Read up to size bytes, waiting up to timeout for the first.

write

write(data: bytes) -> int

Send bytes to the simulated controller.

reset_input_buffer

reset_input_buffer() -> None

Discard unread bytes.

close

close() -> None

Close the port; the controller keeps its state.

make_test_pattern

make_test_pattern(
    rows: int = 2,
    cols: int = 10,
    frame_count: int = 4,
    gray_level: GrayLevel = GS16,
    *,
    duty_cycle: int = 128,
    arena_id: int = 0,
) -> bytes

Build a valid .pat file whose panels light up uniformly.

Frame f, panel p has every pixel at (f + p) % levels. The pattern is meant for tests: it exercises the file format, not the pixel layout.

Parameters:

Name Type Description Default
rows int

Panel rows.

2
cols int

Panel columns.

10
frame_count int

Number of frames (at least 1).

4
gray_level GrayLevel

GS2 or GS16.

GS16
duty_cycle int

Brightness byte of every panel block.

128
arena_id int

6-bit arena id for the header.

0

Returns:

Type Description
bytes

The file contents.