Architecture
Better ScooterFlasher is layered so the CLI and the GUI can only reach hardware through one safe path. Nothing above the backend layer touches a subprocess, the filesystem for hardware I/O, or the network directly.
CLI (src/scooterflasher/cli/) GUI (src/scooterflasher/gui/)
\ /
-> flashops (state machine, plan, backup, restore)
-> backend (ProgrammingBackend: FakeBackend | OpenOCDBackend)
-> registry (DeviceRegistry -> ScooterProfile)
-> catalog (CatalogService -> ModelFirmwareCatalog)
-> userdata (esc / nrf51_ble codecs)
-> domain (pure typed models, no I/O)
-> config (paths, settings)
Domain layer (domain/)
Pure, side-effect-free typed models: MemoryRegion, MCUVariant,
Target, ScooterProfile, UserDataLayout, SemanticVersion. Every
model validates itself on construction —
overlapping regions, duplicate target ids, a SerialNumberRule pointing at
a target/region that doesn't exist, an artifact with a malformed sha256 —
all fail at construction time, not deep inside a flash operation. This is
also why SerialNumberRule and ArtifactConstraint carry an explicit
target_id: a profile with both an ESC and a BLE target commonly has a
userdata region on both targets, so a bare region name is ambiguous.
Device registry (registry/)
DeviceRegistry loads ScooterProfile YAML files from a directory (or the
package's bundled registry/profiles/ via importlib.resources, so
resolution never depends on the process's current working directory).
Construction rejects a duplicate model_id or an alias colliding with
another profile's model_id/alias. Adding a model means adding a YAML
file under registry/profiles/ — no application code changes. See
device-profiles.md.
Backend abstraction (backend/)
ProgrammingBackend is an ABC: probe, identify, is_protected, halt,
read_memory, unlock, erase, write_memory, verify_memory, reset,
disconnect. Two implementations exist:
FakeBackend— deterministic, in-memory, with fault injection (fail_on,verify_mismatch_regions,mismatched_targets,disconnect). Used to exercise the entire flash state machine in tests without hardware.OpenOCDBackend(backend/openocd/) — spawns one OpenOCD subprocess per operation (the same one-shot model the original used) rather than holding a persistent session.runner.pyreads the complete merged stdout+stderr stream viaPopen.communicate()and only reports success when the exit code is zero and no critical log pattern matched — this is the direct fix for the original's false-success bug (seemigration-from-scooterflasher.md).log_patterns.py's pattern table is immutable (frozen dataclasses withtuplealternatives) so it cannot decay while being used to parse output, fixing a second bug present in both the original repo and its corrected fork. This backend is unit-tested against a fake subprocess and has had very little hardware testing — seesupport-matrix.md.
Adapter selection (backend/openocd/adapters.py) is data (AdapterConfig)
plus a pure function building the OpenOCD -c/-f argv fragment for it;
ST-Link, CMSIS-DAP, J-Link, a user-supplied custom interface config, and
Raspberry Pi GPIO (linuxgpiod, ported from
better-scooterflasher-fork commit 10e16e2) are all equally first-class —
none of them replaces another.
Catalog subsystem (catalog/)
Separates where firmware comes from from how it's flashed. The catalog
is one bundled, version-controlled tree (catalog/entries/<brand>/ <model>.yaml, one file per model, kind: drv|ble|bms + versions + mirror
URLs) — there is no user-configurable source, no local/remote precedence
to merge, nothing to add outside a pull request to this repository (see
firmware-catalogs.md for why and for the
schema). CatalogService.download() tries a version's mirrors in order,
verifying sha256 when the entry declares one. transport.py is the only
module in the whole codebase allowed to make a network request, and only
from an explicit catalogs download / --artifact flag / interactive
firmware pick — never from import, and never from catalogs list/
validate or an ordinary plan.
User-data codecs (userdata/)
Target/family-specific parsers for the persisted configuration block:
esc.py (STM32F1x-family ESC, 1023-byte blob) and nrf51_ble.py (nRF51
BLE dashboard, 23-byte blob). Both validate exact size, reject a missing
signature rather than defaulting to offset 0, and serialize() only ever
touches the specific bytes of the fields being changed — everything else
in the input buffer is preserved.
Flash operation state machine (flashops/)
build_plan() turns a profile/target/FlashOptions into a FlashPlan
with zero hardware access: it validates every write against its region and
any ArtifactConstraint, and derives which confirmation tokens
(mass_erase, skip_backup, serial_number_change,
unverified_artifact:<id>, experimental_profile:<status>, ...) the
caller must acknowledge.
FlashOperation then runs the actual stage sequence — discover, identify,
validate, backup, confirm, plan, unlock-if-needed, erase, write, verify,
restore-user-data, reset, report — against any ProgrammingBackend.
Read/write protection detected at the validate stage adds its own
unlock_protected_target confirmation on top of whatever the plan already
required. Any stage failure stops the operation immediately (fail closed);
every stage's outcome, success or failure, is recorded in the returned
OperationReport. restore is not a separate, less-audited code path —
flashops/restore.py just turns a backup manifest into the same
FlashOptions/FlashOperation pipeline flash uses.
Configuration (config/)
paths.py resolves config/cache/data/backup/log directories via
platformdirs (overridable in one shot via SCOOTERFLASHER_HOME, which
the test suite uses to stay hermetic). settings.py is a schema-validated,
atomically-written settings.json (catalog sources, default adapter and
GPIO pins).
CLI (cli/)
Every command is a thin wrapper: resolve --device/--target against the
registry, resolve an AdapterConfig from flags + settings, call into
flashops/catalog, and map the result through _errors.wrap_exception
onto a stable exit code. No command
duplicates safety logic that belongs in flashops/backend — the GUI
calls the same flashops/registry/catalog functions rather than
reimplementing any of this (see the GUI section below).
cli/_wizard.py (InquirerPy) provides the interactive fallback: fuzzy
search for --device, arrow-key select for an ambiguous --target/
adapter kind/firmware pick, y/n confirm per required confirmation token.
resolve_or_pick_* helpers in _resolve.py/_backend.py are the only
callers — they use a flag or a configured setting when one exists, launch
the picker only when a real value is genuinely missing and
sys.stdin/stdout.isatty(), and otherwise raise the exact same clear
error a non-interactive shell always got. The CLI's actual command bodies
never talk to InquirerPy directly, and no destructive logic lives in
_wizard.py — it only ever produces the same FlashOptions/
AdapterConfig/etc. values a flag would have.
GUI (gui/, optional [gui] extra)
A PySide6 desktop app that is a peer of the CLI, not a layer on top of it:
both call straight into flashops/registry/catalog/backend, and
neither imports the other's private modules (gui/state.py builds its own
CatalogService/DeviceRegistry/Settings rather than importing
cli._catalog.build_catalog_service; diagnostics.py was factored out of
cli/commands/doctor.py specifically so both surfaces share run_checks()
without one depending on the other).
state.py—AppState(QObject): the one instance shared by every widget, holding the currentScooterProfile/Target/AdapterConfigselection plus the registry/settings/catalog service. Widgets read and mutate this instead of keeping their own copy, so selecting a device in the sidebar is instantly visible everywhere via Qt signals (profile_changed/target_changed/adapter_config_changed).workers.py— every operation that touches hardware or the network (probe, backup, catalog download, verify, flash, restore) runs on aQThreadviarun_callable_in_thread/run_flash_operation_in_thread, so the UI stays responsive.FlashWorkerforwardsFlashOperation'son_stagecallback as a Qt signal for live per-stage progress — the same optional, additive hookflashops/state_machine.pyadded for exactly this, without changing the CLI's synchronous contract.formatting.py/write_resolution.py— plain functions with no Qt import, so the phrasing (plan summaries, report summaries, confirmation descriptions) and firmware-selection resolution (local file vs. cataloged artifact, sameartifact_id/support-status conventions ascli/_writes.py) are unit-testable without aQApplication.widgets/— one file per tab/panel (device_panel,adapter_panel,doctor_tab,probe_tab,catalog_tab,backup_tab,write_selector,verify_tab,plan_flash_tab,restore_tab) plusmain_window.py, which assembles them behind a sharedAppState.plan_flash_tab.pyandrestore_tab.pydrive the exact samebuild_plan()/FlashOperationthe CLI'sflash/restorecommands drive, including requiring every confirmation token the plan asks for before running — no confirmation or plan-building logic is reimplemented for the GUI.
Tests run headless (QT_QPA_PLATFORM=offscreen) via pytest-qt; hardware
operations are tested against FakeBackend through an injectable
backend_factory, the same fake used by the CLI/flashops test suite.
Attribution
Better ScooterFlasher is a from-scratch implementation. Hardware knowledge
(memory-map addresses, userdata layouts, protocol quirks) was
reverse-engineered by the original ScooterFlasher project and its
origin/pyqt6 branch (GPL-3.0-or-later; "ScooterFlasher is mostly inspired
by ReFlasher, created by ScooterHacking.org") and by
better-scooterflasher-fork's Raspberry Pi GPIO port (commit 10e16e2).
See migration-from-scooterflasher.md for exactly what was
ported and what was independently re-derived.