Migration from ScooterFlasher

Better ScooterFlasher is a from-scratch reimplementation, not a refactor of the original scooterflasher repository or of better-scooterflasher-fork. Both were used as read-only, behavioral/reverse-engineering references. This document records what was found in them, what was carried forward, what was independently fixed, and what changed for the user.

Architectural differences

ScooterFlasherBetter ScooterFlasher
Model dataScattered module-level lists (XIAOMI_DEV, NINEBOT_DEV, XIAOMI_V2_DEV, DEFAULT_ESC_SN, ...) and repeated if self.device in ... chains across 5+ functions in core.pyOne schema-validated YAML profile per model under registry/profiles/
PackagingNo setup.py/pyproject.toml, no console entry point, python -m scooterflasherInstallable package, scooterflasher console script
Config locationHardcoded ~/.scooterflasher/config.json, non-atomic writePlatform-appropriate dirs via platformdirs, atomic write, schema-validated
Success/failureOpenOCD exit code never checked; success inferred from stderr text matching aloneExit code and critical-log-pattern classification, both explicit and always defined
AdapterST-Link only (ScooterFlasher) / Raspberry Pi GPIO only (fork)ST-Link, CMSIS-DAP, J-Link, Raspberry Pi GPIO, custom — all configurable, none replacing another
Firmware sourceBundled binaries with undocumented provenance + an abandoned firmware APIBundled catalog tree (catalog/entries/, one YAML per model) with per-version sha256, imported from scooterhacking/firmware with hashes computed locally at import time, not carried over from the original
TestsNone~290 tests: domain validation, registry golden tests, fake-backend state-machine coverage, OpenOCD command/log-parsing regression tests, catalog/userdata codec tests

The false-success bug (fixed)

scooterflasher/oocd.py's OpenOCD.run():

def run(self, command) -> bool:
    _process = subprocess.Popen(self.base_args + command, shell=False, stderr=subprocess.PIPE)
    while True:
        output = _process.stderr.readline().strip()
        return_code = _process.poll()
        if return_code is not None:
            break
        if output:
            failed = self.parse_logs(output.decode("utf-8"))
    return not failed

Three compounding defects, confirmed by inspecting the full commit history of both reference repos:

  1. return_code was fetched but never inspected — not failed is the entire return value; a non-zero exit with no matching stderr text was reported as success.
  2. failed was only assigned inside if output: — a process that exited non-zero without printing any matching line left it undefined (ScooterFlasher: UnboundLocalError; the risk this project's audit flagged is the same defect manifesting as either a crash or, in variants where a stale failed from a prior line could linger, a false positive).
  3. readline() then poll(), in that order — the last line written right as the process exited could be read but the loop would break before ever classifying it.

better-scooterflasher-fork commit 10e16e2 fixed all three (initializing failed = False, accumulating with or across the whole run, and checking _process.wait()'s return code explicitly) as part of its GPIO migration. Better ScooterFlasher ports this fix's intent independently: see scooterflasher.backend.openocd.runner.run_openocd, which reads the complete merged stdout+stderr via Popen.communicate() (no read/poll race at all) and requires exit_code == 0 and not has_critical — both always explicitly computed. Regression tests for the exact scenarios of the original live in tests/unit/backend/openocd/test_runner.py.

The log-pattern mutation bug (fixed — present in both the original and the fork)

scooterflasher/utils.py's parse_logs:

for error in utils.OPENOCD_ERRORS:
    if isinstance(error["error"], list):
        for text in error['error']:
            error['error'] = text   # overwrites the list with the last string checked
            log, failed = self.parse_error(error, output)

Any OPENOCD_ERRORS entry whose "error" was a list of alternatives (e.g. ["Mass erase complete", "mass erase complete"]) got permanently collapsed to whichever alternative was checked last, the first time any line was parsed — for the rest of the process, that pattern could then only match the one leftover string. This bug is present unmodified in the original's master, in origin/pyqt6, and in better-scooterflasher-fork — none of the reference repos fix it.

Better ScooterFlasher's scooterflasher.backend.openocd.log_patterns fixes it structurally: LogPattern is a frozen dataclass with a tuple[str, ...] of alternatives, so there is no attribute to reassign. A regression test (test_repeated_classification_of_multi_alternative_pattern_does_not_degrade) classifies dozens of lines before checking that every alternative of a multi-alternative pattern still matches.

ESC addresses: bank offsets vs absolute addresses

The original wrote the ESC with flash write_bank 0 <file> [offset], so 0x1000, 0xF800 and 0x1C000 in core.py are offsets into the flash bank, which starts at 0x08000000. Better ScooterFlasher issues program and flash erase_address, which take absolute addresses, so its ESC profiles store 0x08000000 + offset. nRF51 flash starts at 0, so BLE addresses need no such translation. One ESC flash over Raspberry Pi GPIO was reported working on a real scooter; nothing else has been verified on hardware.

Corrected nRF51 BLE addresses (ported from origin/pyqt6@6db108e)

origin/pyqt6 is master plus exactly one commit, 6db108e ("Fix flashing BLE (thx @BastelPichi)"), absent from both master and the fork. Master's addresses were wrong (bootloader hardcoded at 0x000000 for every model, colliding with reasonable layouts near the top of a 256KB part); 6db108e corrected them:

RegionDefault groupV2_BLE_PREFIX group (pro2/1s/lite/mi3)
Firmware0x180000x1B000
Userdata0x3B4000x3B800
Bootloader0x3C0000x3D000
UICR0x10001000 (both groups; 1024 bytes)

6db108e also renamed binaries/UICR/UICR_32K to UICR.bin/ UICR_32K.bin (matching filenames the code already expected but that didn't exist on disk on master) and widened the BLE-unsupported check from just g2 to g2, f2, f2plus, f2pro, 4pro, 4proplus, 4promax.

Better ScooterFlasher's registry profiles (registry/profiles/*.yaml) use these corrected addresses directly; profiles for the seven now-unsupported models simply omit a BLE target rather than exposing one, and golden tests (tests/unit/registry/test_builtin_profiles.py) pin the exact addresses per brand group so they can't silently drift.

Caveat, not resolved by this migration: the known BLE bootloader binaries (mi_BLE.bin/nb_BLE.bin, 92440 bytes; mi_BLE_V2.bin, 110784 bytes) are larger than the bootloader region as modeled here (derived from the gap between the bootloader address and the end of a 256KB flash — 16384 or 12288 bytes depending on group). This discrepancy is flagged directly in the affected profiles' region descriptions and is unresolved pending hardware-in-the-loop investigation; Better ScooterFlasher intentionally models the smaller, address-derived region size so an oversized write is rejected rather than silently overflowing into the firmware region.

Raspberry Pi GPIO (ported from better-scooterflasher-fork commit 10e16e2)

The fork replaced ST-Link with linuxgpiod (chip 0, SWDIO=GPIO22, SWCLK=GPIO23, no SRST wired, reset_config none) and fixed two OpenOCD Tcl compatibility issues in mem_helper.tcl (mem2array → read_memory; unbraced expr $x → braced expr {$x}), needed because mem2array was removed from modern OpenOCD and is used by stm32f1x.cfg/at32.cfg's examine-end debug-register hook.

Better ScooterFlasher ports the GPIO pin configuration (backend/openocd/adapters.py) as one configurable adapter kind alongside ST-Link/CMSIS-DAP/J-Link, not a replacement for them. It does not vendor mem_helper.tcl (or any other OpenOCD Tcl script) at all: OpenOCDBackend uses OpenOCD's own stock target/nrf51.cfg/target/stm32f1x.cfg and generic, modern commands (dump_image, program ... verify, flash erase_address) instead of the vendored/patched scripts the original shipped. This sidesteps the whole class of "vendored Tcl using a removed command" bug structurally, at the cost of depending on whatever target scripts ship with the system's OpenOCD.

The Xiaomi 4 Pro Plus / AT32 bug: inferred, not confirmed

The specification of the rebuild called out "the exact failure pattern from the archived Xiaomi 4 Pro Plus issue, including target not halted and obsolete Tcl mem2array/expr errors" as something to cover. The audit searched the full history and working tree of both reference repos for this and found no commit message, code comment, or README text connecting "4 Pro Plus" to "target not halted" — that specific bug report is not present in the local repository history. What is confirmed: 4ProPlus/4ProMax support (added in scooterflasher commit 9443a50) routes through the same AT32 target config (at32.cfg → mem_helper.tcl) that commit 10e16e2 fixed the mem2array bug for, generically, across all STM32F1x/AT32 targets. It is plausible a 4ProPlus flash against a modern OpenOCD build hit this same failure class, but that connection is inferred, not documented — Better ScooterFlasher does not assert it as fact, and there is no model-specific regression fixture for it (only the generic Tcl-compat fix via not vendoring the buggy script at all, see above).

Clone-MCU ("fake-chip") flashing

The original and the fork support flashing an ESC whose genuine STM32F1 controller has been replaced with a cheaper GD32 or AT32 clone (--fake-chip, unlock_gd32(), oocd/scripts/target/stm32f1x-nocpuid.cfg / at32.cfg — core.py:29-40,113-146,236-247, utils.py: FAKEDRV_DEV). Both clone-chip target configs work by wildcarding the JTAG/SWD TAP ID check (_CPUTAPID 0) that the stock target/stm32f1x.cfg uses to confirm it's actually talking to the expected silicon.

Better ScooterFlasher supports this too (--clone-chip on every hardware command / the "Clone chip" checkbox in the GUI's sidebar), but without vendoring either non-stock target script: target_config_commands() in backend/openocd/targets.py prepends -c "set CPUTAPID 0" before the same stock -f target/stm32f1x.cfg every genuine-chip flash already uses — the stock script itself reads a pre-set CPUTAPID Tcl variable before falling back to the real part's expected id, so 0 (the same wildcard value the original's bundled configs hardcoded) works without needing a modified copy of the file. One mechanism covers every STM32F1-compatible clone uniformly, not just the two the original special-cased by name.

Scoped to families with a known clone-chip variant — STM32F1 only, so far; requesting it for nRF51 or an unmapped family still fails closed with UnsupportedCombinationError, matching targets.py's existing "no plausible-looking guess for unverified hardware" policy. GD32/AT32's own GD32-specific unlock sequence (unlock_gd32()'s tolerance for an expected halt timeout) was not ported — Better ScooterFlasher's existing family-generic stm32f1x unlock 0 is used unchanged; if that turns out to need a clone-specific variant, that's a follow-up once real hardware is available to verify against.

Still unverified against real hardware — this is a fail-closed default (allow_clone_chip=False unless explicitly requested) that lets a user with known clone silicon proceed at their own choice; it does not carry a tested claim, same as every other OpenOCD-backend capability in this project until hardware-in-the-loop evidence exists.

UID extraction

The original's --extract-uid reads the STM32F1 factory unique-ID register (dump_image ... 0x1FFFF7E8 12, core.py:34-40) and embeds it at userdata offset 436 - used by some activation flows.

Better ScooterFlasher ports this as --extract-uid on flash (and the interactive wizard's equivalent prompt, shown only for STM32F1 ESC targets): flashops/userdata_read.py's read_stm32_uid() reads the register via a synthetic MemoryRegion at the fixed address (it isn't part of the normal flash address space, so it's never one of a target's persisted regions) rather than a dedicated backend method, calling unlock() first unconditionally - the original did the same regardless of whether the target was actually protected. esc.py's serialize() gained a uid parameter to embed it, following the same field-patching pattern as serial/mileage/activation. Gated behind its own confirmation token (uid_extraction) and, like clone-chip flashing, unverified against real hardware.

CLI differences

ScooterFlasher: python -m scooterflasher --device <dev> --target {BLE,ESC} --sn ... --km ... (single-shot argparse script, one device/target per invocation, no dry-run mode, no JSON output, no distinct exit codes beyond a generic success/failure).

Better ScooterFlasher: scooterflasher <subcommand> --device <model_id> --target <target_id> ... with doctor, devices, adapters, probe, backup, plan, flash, verify, restore, catalogs subcommands; every hardware command supports --json for machine-readable output and a distinct exit code per failure category; plan is a new dry-run-only command with no equivalent in the original; --write/ --artifact replace the original's --custom-fw/--cfw with explicit region-targeting and unverified-provenance confirmation.

--fake-chip is ported as --clone-chip (see "Clone-MCU" above); --extract-uid is ported unchanged in name (see "UID extraction" above) - both same default-off, explicit-opt-in behavior. The original flags with no equivalent here: --extract-data/--custom-ram (the original's raw-RAM-dump- based userdata capture path - Better ScooterFlasher reads the persisted userdata region directly instead, see flashops/userdata_read.py).

License and attribution

Both scooterflasher and better-scooterflasher-fork are GPL-3.0 (no project-specific copyright header found in either LICENSE file, only the FSF boilerplate). scooterflasher/core.py credits ScooterHacking.org's ReFlasher as the original inspiration. Better ScooterFlasher's LICENSE is the same GPLv3 text; see architecture.md for how reverse-engineered hardware knowledge is attributed here.