The pin crosses libavr's phase 6 - the renamed system surface, the named serial configs, the receiver-tolerance table, the paged SPM receipts - and every loader image comes out size-identical: the full matrix on six representative chips (the exhaustive cross product on three of them), the stock and autobaud columns untouched, the four tsb tiers back on their recorded floors at 510/526/638/836. Byte parity was not free, and the two libavr defects it surfaced were fixed there rather than absorbed here. The EEPROM write procedure's step 2 - the SPMEN spin - had landed unconditionally and cost every build six bytes for a wait a polled loader can never take; it is scoped now, and the loaders state the datasheet's own omission clause (spm_interlock::omitted, DS40002061B 8.6.3). The blocking page erase/write grew an internal wait the tiers' settle() already provides, so the tiers issue the command form and pureboot keeps its host-driven sp_spm path. What the port states rather than inherits: the stock 115200 at 16 MHz sits +2.1 % past the receiver-tolerance table libavr now holds rates to, so the hardware links say .allow_baud_error = true - the same 2.5 % envelope pureboot_baud_feasible() has always enforced, proven on silicon across the fleet. rx_ready() reads readable() now. Alongside the pin: rule 33's ASCII sweep over every source (docs keep their typography), rule 34's InsertBraces in .clang-format with the tree reformatted, std::array over the simavr runners' raw buffers, and the stale Studio size in ide/README.md replaced by the claim its check-flags gate actually holds. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
212 lines
11 KiB
Python
212 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""End-to-end autobaud test: drive an autobaud loader in simavr through the
|
|
calibration handshake and a flash + EEPROM + fuse round-trip, cross-checked
|
|
against the simulator's ground-truth memory - then repeat at a second F_CPU with
|
|
the *same* loader binary, which is the property autobaud exists for: one
|
|
clock-agnostic image that locks onto whatever rate the host sends.
|
|
|
|
Usage: pbautobaud.py <device_bin> <loader_elf> <mcu> <base_hex> <page>
|
|
<app_bin> <app_hz> <app_baud> <tool_py> <workdir> [link]
|
|
|
|
The loader is a software-serial build, driven over the GPIO<->pty bridge; the
|
|
optional link overrides the default -l sw:B0,B1 - RX == TX in it is the
|
|
one-wire deployment, and every session then runs with the host's echo
|
|
discard on. The app fixture is built for (app_hz, app_baud); the hand-over
|
|
is checked at that point, and a second point at half the clock proves the
|
|
lock is measured, not baked in.
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
|
|
|
|
def fail(message):
|
|
print(f"FAIL: {message}")
|
|
sys.exit(1)
|
|
|
|
|
|
def main():
|
|
args = sys.argv[1:]
|
|
link = args.pop() if len(args) == 11 else "sw:B0,B1"
|
|
(device_bin, elf, mcu, base_hex, page, app_bin, app_hz, app_baud, tool, workdir) = args
|
|
base, page, app_hz, app_baud = int(base_hex, 0), int(page), int(app_hz), int(app_baud)
|
|
one_wire = re.fullmatch(r"sw:([A-H][0-7]),\1(@[01])?", link) is not None
|
|
extra = ("--one-wire",) if one_wire else ()
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(tool)))
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
import pbsim
|
|
import pureboot as pb
|
|
|
|
os.makedirs(workdir, exist_ok=True)
|
|
ee_image = bytes(range(0xA0, 0xB0))
|
|
ee_path = os.path.join(workdir, "ee.bin")
|
|
open(ee_path, "wb").write(ee_image)
|
|
|
|
# The geometry the surgery planner needs, from the chip class the runner is
|
|
# told - the same derivation pbtest.py makes: the boot-sectioned megas need
|
|
# no vector surgery, the tinies and the boot-section-less m48s do, and the
|
|
# large chips speak word addresses.
|
|
mega = mcu.startswith("atmega")
|
|
patch = not mega or mcu.startswith("atmega48")
|
|
word_flash = base + pb.SLOT > 0x10000
|
|
wire_base = base // 2 if word_flash else base
|
|
flags = (1 if patch else 0) | (2 if word_flash else 0)
|
|
ground_truth = pb.Info(bytes([ord("P"), ord("B"), pb.NEWEST_LOADER, 0, 0, 0, page & 0xFF,
|
|
wire_base & 0xFF, wire_base >> 8, 0, 0, flags]))
|
|
|
|
def round_trip(hz, baud, label, hand_over):
|
|
"""One clock point: reset, calibrate + knock, program, verify against the
|
|
simulator's own flash, and (at the app's point) hand over to the fixture."""
|
|
dump = os.path.join(workdir, f"flash_{label}.bin")
|
|
device = pbsim.Device(device_bin, elf, mcu, str(hz), base_hex, page, baud, dump, link=link)
|
|
try:
|
|
# The host tool, in autobaud mode, sends the 0xC0 calibration pulse
|
|
# and a single knock at `baud`; the loader locks to it.
|
|
out = pbsim.run_tool(tool, device.pty, baud, *extra, "--autobaud", "--info", "--clock", str(hz),
|
|
"--fuses", "--flash", app_bin, "--eeprom", ee_path, "--stay")
|
|
for needed in ("version", "signature", "fuses", "verify:", "stays"):
|
|
if needed not in out:
|
|
fail(f"{label}: session output lacks {needed!r}\n{out}")
|
|
# The measured clock, decoded from the unit at whichever home this
|
|
# version keeps it in. The runner's clock is exact, so the figure
|
|
# must land inside the
|
|
# encoding's own envelope: the loader floors the bit period to
|
|
# 4-cycle spin granules after an 8-cycle discount, and the edge
|
|
# poll can shave a few cycles more - one granule of slack below
|
|
# the true clock, none above (in cycles per bit, times the rate).
|
|
measured = re.search(r"measured\s+(\d+) Hz", out)
|
|
if not measured:
|
|
fail(f"{label}: --info lacks the measured clock\n{out}")
|
|
measured = int(measured.group(1))
|
|
if not hz - 19 * baud <= measured <= hz + 4 * baud:
|
|
fail(f"{label}: measured clock {measured} Hz is {measured - hz:+d} off the true {hz}")
|
|
# Read both memories back over the locked link and check them.
|
|
read_flash = os.path.join(workdir, f"rf_{label}.bin")
|
|
read_eeprom = os.path.join(workdir, f"re_{label}.bin")
|
|
out = pbsim.run_tool(tool, device.pty, baud, *extra, "--autobaud", "--verify-flash", app_bin,
|
|
"--verify-eeprom", ee_path, "--read-flash", read_flash,
|
|
"--read-eeprom", read_eeprom, "--stay")
|
|
if out.count("verify:") != 2:
|
|
fail(f"{label}: did not verify both memories\n{out}")
|
|
if open(read_eeprom, "rb").read()[: len(ee_image)] != ee_image:
|
|
fail(f"{label}: EEPROM read-back mismatch")
|
|
|
|
if hand_over:
|
|
# Regression: a calibration pulse with no knock behind it must
|
|
# not wedge the loader. The knock's edge wait used to be
|
|
# unbudgeted, so one stray low pulse - EMI, or a host that opens
|
|
# the port and never knocks - held the loader forever and the
|
|
# application never ran. The whole activation is bounded now, so
|
|
# the window closes and the app boots; the banner is the proof.
|
|
# (The pause lets the loader reach its measurement loop, so the
|
|
# pulse is genuinely seen and the test cannot pass vacuously.)
|
|
device.reset()
|
|
port = pb.Port(device.pty, baud)
|
|
if one_wire:
|
|
port = pb.OneWirePort(port)
|
|
try:
|
|
time.sleep(0.2)
|
|
port.write(bytes((pb.CALIBRATE,)))
|
|
# Accumulate rather than match exactly: the reset leaves the
|
|
# idle line a framing artefact ahead of the banner, which is
|
|
# noise here - the question is only whether the app ran.
|
|
seen = b""
|
|
deadline = time.monotonic() + 180.0
|
|
while b"APP" not in seen and time.monotonic() < deadline:
|
|
seen += port.read_available(1.0)
|
|
if b"APP" not in seen:
|
|
fail(f"{label}: lone calibration pulse wedged the loader - app never bannered, saw {seen!r}")
|
|
print(f" {label}: lone calibration pulse does not wedge the loader")
|
|
finally:
|
|
port.close()
|
|
|
|
device.reset()
|
|
port = pb.Port(device.pty, baud)
|
|
if one_wire:
|
|
port = pb.OneWirePort(port)
|
|
try:
|
|
loader = pb.Loader(port)
|
|
live = loader.connect_autobaud(15)
|
|
if not pb.OLDEST_LOADER <= live.version <= pb.NEWEST_LOADER:
|
|
fail(f"{label}: loader reports pureboot {live.version}")
|
|
if loader.unified:
|
|
# pureboot 5's data space. 0x0200 is clear of the
|
|
# loader's own .noinit unit at the bottom of SRAM and of
|
|
# the stack at the top. Reading it back over the same
|
|
# locked link proves both directions of the new space.
|
|
probe = bytes(range(0x30, 0x40))
|
|
loader.write_ram(0x0200, probe)
|
|
if loader.read_ram(0x0200, len(probe)) != probe:
|
|
fail(f"{label}: RAM round-trip mismatch")
|
|
# The register file and the I/O space share the data
|
|
# address space on AVR, so the same command reaches a
|
|
# peripheral register. SPMCSR reads back as idle here.
|
|
verbose_ram = loader.read_ram(0x0200, 4)
|
|
print(f" {label}: RAM read/write ok ({verbose_ram.hex()})")
|
|
loader.run_application()
|
|
banner = port.read_exact(3, 5.0)
|
|
if banner != b"APP":
|
|
fail(f"{label}: application banner was {banner!r}")
|
|
finally:
|
|
port.close()
|
|
finally:
|
|
device.stop()
|
|
|
|
# Ground truth (read after the runner exits and writes its dump): what
|
|
# the tool programmed must be what the simulator actually holds.
|
|
pages = pb.plan_flash(open(app_bin, "rb").read(), ground_truth)
|
|
flash_true = open(dump, "rb").read()
|
|
for address, data in pages.items():
|
|
if flash_true[address : address + page] != data:
|
|
fail(f"{label}: simulator flash differs from the programmed image at {address:#06x}")
|
|
print(f" {label}: locked at {hz} Hz / {baud} Bd, flash+EEPROM verified"
|
|
+ (", hand-over ok" if hand_over else ""))
|
|
|
|
def must_lock(hz, baud, label):
|
|
"""The calibration alone, at a tight bit period. Nothing is programmed -
|
|
the question is only whether the loader can still measure the pulse."""
|
|
dump = os.path.join(workdir, f"flash_{label}.bin")
|
|
device = pbsim.Device(device_bin, elf, mcu, str(hz), base_hex, page, baud, dump,
|
|
link=link)
|
|
try:
|
|
port = pb.Port(device.pty, baud)
|
|
if one_wire:
|
|
port = pb.OneWirePort(port)
|
|
try:
|
|
live = pb.Loader(port).connect_autobaud(15)
|
|
if live.version != pb.NEWEST_LOADER:
|
|
fail(f"{label}: loader reports pureboot {live.version}")
|
|
finally:
|
|
port.close()
|
|
finally:
|
|
device.stop()
|
|
print(f" {label}: locked at {hz} Hz / {baud} Bd ({hz / baud:.0f} cycles a bit)")
|
|
|
|
# The app fixture is built for one clock; the hand-over banners there. A
|
|
# second point at double that clock, same loader binary, proves the lock is
|
|
# measured, not baked in - the whole point of autobaud. (Doubling keeps the
|
|
# bit period healthy; halving would drop it below the software UART's floor.)
|
|
round_trip(app_hz, app_baud, "clock-a", hand_over=True)
|
|
round_trip(app_hz * 2, app_baud, "clock-b", hand_over=False)
|
|
|
|
# Both points above sit near 100 cycles a bit, which is comfortable. The
|
|
# calibration's real floor is far tighter, and it is worth a gate: measured
|
|
# here, the lock is solid down to ~36 cycles a bit and fails outright by ~31
|
|
# - a sharp edge, not a fraying one. This pins the tightest standard rate the
|
|
# fixture's clock reaches, so a change that raises the floor is caught.
|
|
#
|
|
# It does *not* bound what a real deployment can use. On silicon the
|
|
# oscillator's own jitter costs roughly a factor of two: an ATtiny13A on its
|
|
# factory RC trim was reliable at ~118 cycles a bit and already locking only
|
|
# 1 attempt in 5 by ~59, which no exact-clock simulation can show. The
|
|
# deployable envelope is a README matter; this is the logic's floor.
|
|
must_lock(app_hz, app_baud * 2, "tight-bit")
|
|
print("pbautobaud: calibration lock and flash/EEPROM/fuse round-trip pass at both clocks, "
|
|
"and the tight bit period still locks")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|