firmware: document every test and test helper

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013PRsUCpxazyipPn5UGGkF8
This commit is contained in:
Claude committed 2026-10-18 21:16:05 +00:00
1 parent 046b2a722f
commit f47d285163
6 files changed
+125

No files matched your search

+14
View File
@@ -24,6 +24,7 @@ const INFO = { LEN: 14, BAUD_LOCKED: 0x08, BAUD_LEARNING: 0x10 };
const A_RX = 1;
let failures = 0, checks = 0;
// Counts a check and prints it as ok or FAIL.
function check(cond: boolean, what: string) {
checks++;
if (!cond) { failures++; console.log(` FAIL: ${what}`); } else console.log(` ok: ${what}`);
@@ -35,7 +36,9 @@ const mcu = sim.rp2040;
mcu.logger = new ConsoleLogger(LogLevel.Error);
mcu.loadBootrom(bootromB1);
mcu.flash.set(readFileSync(image), 0);
// The emulated RP2040's GPIO n.
const pin = (n: number) => mcu.gpio[n];
// The level the firmware drives on GPIO n.
const out = (n: number) => pin(n).outputValue;
// the far end: nothing attached yet, every receiver output idle (high = deasserted)
@@ -113,7 +116,10 @@ function sendWave(gpio: number, baud: number, text: string, errPct = 0): Promise
sim.rp2040.core.PC = 0x10000000;
sim.execute();
// Simulated time, in ms.
const simMs = () => Number(sim.clock.nanos / 1e6);
// Waits (checking every 5 ms of real time) until cond holds or simLimitMs of
// simulated time pass; true if cond held.
async function until(cond: () => boolean, simLimitMs: number): Promise<boolean> {
const end = simMs() + simLimitMs;
while (!cond()) {
@@ -122,8 +128,11 @@ async function until(cond: () => boolean, simLimitMs: number): Promise<boolean>
}
return true;
}
// Lets ms of simulated time pass.
const runFor = (ms: number) => until(() => false, ms);
// Sends a vendor IN request to the control interface and resolves with the
// reply's data stage (up to len bytes), or null after 20 s of real time.
function vendorIn(req: number, len: number): Promise<Uint8Array | null> {
return new Promise((resolve) => {
const timer = setTimeout(() => { ep0Waiter = null; resolve(null); }, 20000);
@@ -134,6 +143,7 @@ function vendorIn(req: number, len: number): Promise<Uint8Array | null> {
}));
});
}
// Sends a vendor OUT request (no data stage) to the control interface.
function vendorOut(req: number, value: number) {
ep0Waiter = () => {}; // swallow the status stage
mcu.usbCtrl.sendSetupPacket(createSetupPacket({
@@ -141,11 +151,15 @@ function vendorOut(req: number, value: number) {
bRequest: req, wValue: value, wIndex: ITF_CONTROL, wLength: 0,
}));
}
// The line-state bits of the last SERIAL_STATE notification, or -1 if none came.
const lastState = () => {
const n = notifications[notifications.length - 1];
return n ? n[8] | (n[9] << 8) : -1;
};
// The end-to-end scenario: enumerate over USB, detect a computer, learn its
// baud rate, pass data both ways, answer vendor requests, learn a new rate,
// and force DTE mode; exits 1 if any check failed.
async function main() {
console.log('boot and enumerate');
check(await until(() => connected, 3000), 'USB enumerates as a CDC device and takes DTR+RTS');
+22
View File
@@ -9,6 +9,8 @@
fake_hw_t hw;
// Clears every record and setting, then starts the clock at 1000 ms with the
// transceiver power and UART routing marked "never set" (0xFF).
void fake_reset(void) {
memset(&hw, 0, sizeof hw);
hw.now = 1000;
@@ -16,33 +18,53 @@ void fake_reset(void) {
hw.route = 0xFF;
}
// The test's clock: hw.now, which tests advance by hand.
uint32_t hal_millis(void) { return hw.now; }
// Records which transceiver was powered, and counts the calls.
void hal_xcvr_power(uint8_t role) { hw.xcvr = role; hw.xcvr_calls++; }
// Reports a computer on the line when the test set hw.peer_dce.
bool hal_peer_dce(void) { return hw.peer_dce; }
// Reports a modem on the line when the test set hw.peer_dte.
bool hal_peer_dte(void) { return hw.peer_dte; }
// The raw detect bits the real board would report for hw.peer_dce / peer_dte.
uint8_t hal_detect_bits(void) {
return (uint8_t)((hw.peer_dce ? PS_DETECT_A_STATUS : 0) | (hw.peer_dte ? PS_DETECT_B_INVALID : 0));
}
// Records which chip the UART was routed to.
void hal_uart_route(uint8_t role) { hw.route = role; }
// Records the UART format last set, and counts the calls.
void hal_uart_format(const uart_format_t *f) { hw.format = *f; hw.format_calls++; }
// Records whether hardware CTS flow control is on.
void hal_uart_hw_cts(bool on) { hw.hw_cts = on; }
// Records whether a break is being sent.
void hal_uart_break(bool on) { hw.brk = on; }
// Counts the times the core said data was queued for the UART.
void hal_uart_kick_tx(void) { hw.kicks++; }
// Counts the times the core dropped the UART's received data.
void hal_uart_rx_flush(void) { hw.rx_flushes++; }
// Records whose RX line baud learning is timing, and counts the calls.
void hal_autobaud(uint8_t role) { hw.ab_role = role; hw.ab_calls++; }
// The capture clock the tests' waveforms use: FAKE_AB_HZ (the RP2040's 62.5 MHz).
uint32_t hal_autobaud_hz(void) { return FAKE_AB_HZ; }
// Records the modem lines driven, and for which role.
void hal_lines_out(uint8_t role, uint8_t asserted) { hw.out_role = role; hw.out = asserted; }
// Returns the far end's modem lines as the test set them in hw.in.
uint8_t hal_lines_in(uint8_t role) { (void)role; return hw.in; }
// Records the LED mask.
void hal_leds(uint8_t mask) { hw.leds = mask; }
// Copies out the fake flash, if something was saved (or a test put it there).
bool hal_settings_load(void *buf, uint32_t len) {
if (!hw.flash_valid || len > sizeof hw.flash) return false;
memcpy(buf, hw.flash, len);
return true;
}
// Copies the settings into the fake flash and counts the saves.
void hal_settings_save(const void *buf, uint32_t len) {
memcpy(hw.flash, buf, len);
hw.flash_valid = true;
hw.saves++;
}
// No interrupts on the host: nothing to mask.
uint32_t hal_irq_save(void) { return 0; }
// No interrupts on the host: nothing to restore.
void hal_irq_restore(uint32_t s) { (void)s; }
+1
View File
@@ -26,4 +26,5 @@ typedef struct {
#define FAKE_AB_HZ 62500000u
extern fake_hw_t hw;
// Back to a fresh board: nothing recorded, clock at 1000 ms.
void fake_reset(void);
+10
View File
@@ -21,6 +21,8 @@ static ab_t a;
static wave_t wv;
#define rnd wave_rnd
// Makes a waveform (see wave_make) and feeds every run of it to a fresh
// detector, as the capture interrupt would.
static void synth(uint32_t hz, uint32_t baud, double err, const uart_format_t *f,
const uint8_t *msg, size_t len, double gap_bits, double jitter) {
wave_make(&wv, hz, baud, err, f, msg, len, gap_bits, jitter);
@@ -29,12 +31,16 @@ static void synth(uint32_t hz, uint32_t baud, double err, const uart_format_t *f
}
typedef struct { uint8_t buf[512]; uint32_t n; uint32_t errs; } sink_t;
// ab_decode's output callback: collects the decoded bytes (up to 512) and
// counts those that came with a framing or parity error.
static void sink(void *ctx, uint8_t b, uint8_t e) {
sink_t *s = ctx;
if (s->n < sizeof s->buf) s->buf[s->n++] = b;
if (e) s->errs++;
}
// Decodes the captured waveform at baud and format f; true if it gives back
// exactly msg (to f's data bits), with no errors and nothing extra.
static bool decodes_to(uint32_t hz, uint32_t baud, const uart_format_t *f, const uint8_t *msg, size_t len) {
sink_t s = {{0}, 0, 0};
uint8_t mask = (uint8_t)((1u << f->data_bits) - 1);
@@ -48,6 +54,9 @@ static bool decodes_to(uint32_t hz, uint32_t baud, const uart_format_t *f, const
static const uart_format_t F8N1 = {0, 8, 1, 0}, F7E1 = {0, 7, 1, 2}, F8N2 = {0, 8, 2, 0},
F7O1 = {0, 7, 1, 1}, F8E1 = {0, 8, 1, 2};
// Sends msg at every standard rate (with the given rate error, edge jitter
// and idle gap) and checks the detector picks that rate and decodes msg.
// Prints one ok/FAIL line per scenario, and each rate that went wrong.
static void every_rate(const char *name, const uart_format_t *f, const uint8_t *msg, size_t len,
double err, double jitter, double gap, uint32_t hz) {
int bad = 0;
@@ -61,6 +70,7 @@ static void every_rate(const char *name, const uart_format_t *f, const uint8_t *
printf("%-44s %s\n", name, bad ? "FAIL" : "ok");
}
// Runs every scenario; exits 1 if any check failed.
int main(void) {
const uint32_t HZ = 62500000; // 125 MHz / 2
const uint8_t at[] = "AT\r", at_lc[] = "at", dial[] = "ATDT5551212\r", ok[] = "\r\nOK\r\n";
+60
View File
@@ -23,6 +23,7 @@ static void run_ms(uint32_t ms) { // advance time, polling every 5 ms
for (uint32_t t = 0; t < ms; t += 5) { hw.now += 5; core_poll(&c); }
}
// A fresh core in auto mode with nothing attached: no role, both chips off.
static void start_auto(void) {
core_init(&c);
CHECK(c.role == PS_ROLE_NONE);
@@ -37,6 +38,8 @@ static void start_dce_host_baud(void) {
CHECK(c.role == PS_ROLE_DCE && c.ab_state == AB_OFF);
}
// A computer on the line makes the board a DCE, but only after the settle
// time and several agreeing samples, so one reading can't switch it.
TEST(detects_computer_as_dce) {
start_auto();
hw.peer_dce = true;
@@ -49,6 +52,7 @@ TEST(detects_computer_as_dce) {
CHECK(hw.format_calls >= 1);
}
// A modem on the line makes the board a DTE and powers chip B.
TEST(detects_modem_as_dte) {
start_auto();
hw.peer_dte = true;
@@ -57,6 +61,8 @@ TEST(detects_modem_as_dte) {
CHECK(hw.xcvr == PS_ROLE_DTE);
}
// If both chips see a peer (e.g. a loopback or odd cable), the computer
// side wins: acting as a modem is the board's main job.
TEST(computer_wins_when_both_look_present) {
start_auto();
hw.peer_dce = hw.peer_dte = true;
@@ -64,6 +70,7 @@ TEST(computer_wins_when_both_look_present) {
CHECK(c.role == PS_ROLE_DCE);
}
// A single sample of a peer, then nothing, leaves the board undecided.
TEST(glitch_does_not_switch_on) {
start_auto();
run_ms(200);
@@ -72,6 +79,8 @@ TEST(glitch_does_not_switch_on) {
CHECK(c.role == PS_ROLE_NONE);
}
// Unplugging is tolerated for just under CORE_LOST_MS, then the board drops
// back to detecting with both chips off, and can come back as the other role.
TEST(unplug_returns_to_detect) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -87,6 +96,8 @@ TEST(unplug_returns_to_detect) {
CHECK(c.role == PS_ROLE_DTE);
}
// One good sample during a dropout restarts the loss timer, so a flaky
// cable doesn't keep the board switching roles.
TEST(short_loss_recovers) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -96,6 +107,8 @@ TEST(short_loss_recovers) {
CHECK(c.role == PS_ROLE_DCE);
}
// A mode saved in flash (forced DTE) applies at start-up and detection
// can't override it, even with a computer on the line.
TEST(forced_mode_ignores_detection) {
core_settings_t s = {PS_MODE_DTE, PS_FLOW_AUTO, PS_BAUD_AUTO};
uint8_t blob[CORE_SETTINGS_BLOB];
@@ -107,6 +120,8 @@ TEST(forced_mode_ignores_detection) {
CHECK(c.role == PS_ROLE_DTE);
}
// As a DCE, the host's DTR shows the computer DCD and DSR (like a modem
// that's on) and the host's RTS becomes CTS.
TEST(dce_line_mapping) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -120,6 +135,7 @@ TEST(dce_line_mapping) {
CHECK(hw.out == PS_LINE_CTS);
}
// As a DTE, the host's DTR and RTS go straight out on DTR and RTS.
TEST(dte_line_mapping) {
start_auto();
hw.peer_dte = true; run_ms(500);
@@ -128,6 +144,8 @@ TEST(dte_line_mapping) {
CHECK(hw.out_role == PS_ROLE_DTE);
}
// SET_OUTPUTS forces chosen lines on or off over the normal mapping (here
// RI on, DSR off); clearing it restores the mapping.
TEST(overrides) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -139,6 +157,8 @@ TEST(overrides) {
CHECK(hw.out == (PS_LINE_DCD | PS_LINE_DSR | PS_LINE_CTS));
}
// When the buffer to the host fills to 3/4, CTS to the computer drops; it
// comes back only once the buffer drains below half (hysteresis).
TEST(full_buffer_holds_the_far_end) {
start_dce_host_baud();
core_host_lines(&c, false, true); run_ms(5);
@@ -154,6 +174,8 @@ TEST(full_buffer_holds_the_far_end) {
CHECK(hw.out & PS_LINE_CTS);
}
// Auto flow control: CTS is obeyed only once the far end has been seen
// using its RTS, so a 3-wire cable still works; it stays on until unplugged.
TEST(flow_auto_latches) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -166,6 +188,8 @@ TEST(flow_auto_latches) {
CHECK(!hw.hw_cts); // forgotten when the peer goes
}
// The flow setting ON obeys CTS at once, OFF ignores it, and a bad value
// is refused.
TEST(flow_settings) {
start_auto();
hw.peer_dte = true; run_ms(500);
@@ -177,6 +201,8 @@ TEST(flow_settings) {
CHECK(!core_vendor_out(&c, PS_REQ_SET_FLOW, 7));
}
// SERIAL_STATE to the host as a DCE: sent only on change; carrier is on
// while a computer is attached, and the computer's DTR shows as DSR.
TEST(serial_state_dce) {
start_auto();
uint16_t s;
@@ -188,6 +214,8 @@ TEST(serial_state_dce) {
CHECK(core_serial_state(&c, &s) && s == (SS_DCD | SS_DSR)); // computer's DTR shows as DSR
}
// As a DTE, the modem's DCD, DSR and RI reach the host; framing, overrun
// and break are reported once each and counted in the stats.
TEST(serial_state_dte_and_events) {
start_auto();
hw.peer_dte = true; run_ms(500);
@@ -202,6 +230,9 @@ TEST(serial_state_dte_and_events) {
CHECK(c.stats.breaks == 1 && c.stats.framing == 1 && c.stats.overrun == 1);
}
// The host's line coding reaches the UART; what the UART can't do (1.5 stop
// bits, mark parity) is adjusted and flagged, and rates above the chips'
// rating are flagged too.
TEST(line_coding) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -216,6 +247,8 @@ TEST(line_coding) {
CHECK(!(c.info_flags & PS_INFO_CODING_ADJUSTED));
}
// A timed break ends after its duration; 0xFFFF holds it until the host
// sends 0.
TEST(break_timing) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -229,6 +262,8 @@ TEST(break_timing) {
CHECK(!hw.brk);
}
// Bytes from the host go out of the UART in order and received bytes reach
// the host, with both directions counted in the stats.
TEST(data_both_ways) {
start_dce_host_baud();
const uint8_t msg[] = "ATDT5551234\r";
@@ -242,6 +277,8 @@ TEST(data_both_ways) {
CHECK(c.stats.to_rs232 == sizeof msg - 1 && c.stats.from_rs232 == 2);
}
// GET_INFO reports protocol, mode and role; unknown requests and bad modes
// are refused; SET_MODE switches at once and is saved once, after a delay.
TEST(vendor_info_and_mode) {
start_auto();
uint8_t buf[64];
@@ -265,6 +302,8 @@ TEST(vendor_info_and_mode) {
CHECK(n == (int)sizeof(ps_inputs_t));
}
// Settings survive a pack/unpack round trip; a flipped bit or erased flash
// is rejected, and the core then starts with the defaults.
TEST(settings_blob) {
core_settings_t a = {PS_MODE_DTE, PS_FLOW_OFF, PS_BAUD_LEARN}, b = {0, 0, 0};
uint8_t blob[CORE_SETTINGS_BLOB];
@@ -279,6 +318,8 @@ TEST(settings_blob) {
CHECK(c.settings.mode == PS_MODE_AUTO && c.settings.flow == PS_FLOW_AUTO); // defaults
}
// The ring buffer holds exactly RING_SIZE bytes, refuses more, and gives
// them back in order across several wrap-arounds.
TEST(ring_wraps) {
static ring_t r;
ring_init(&r);
@@ -291,6 +332,8 @@ TEST(ring_wraps) {
}
}
// LEDs: power on from the start; TR, CD and RD light for the host's DTR,
// the carrier and received data; RD goes out after its pulse.
TEST(leds) {
start_auto();
core_vendor_out(&c, PS_REQ_SET_BAUD_MODE, PS_BAUD_HOST);
@@ -309,15 +352,19 @@ TEST(leds) {
static wave_t wv;
static const uart_format_t F8N1 = {0, 8, 1, 0};
// Sends msg at baud (1% fast, edges jittered by 3% of a bit, one idle bit
// between characters) as level runs, the way the capture interrupt reports them.
static void send_runs(uint32_t baud, const char *msg, const uart_format_t *f) {
wave_make(&wv, FAKE_AB_HZ, baud, 0.01, f, (const uint8_t *)msg, strlen(msg), 1, 0.03);
for (uint32_t i = 0; i < wv.n; i++) core_isr_run(&c, wv.high[i], wv.ticks[i]);
}
// Reads what has reached the host (up to 128 bytes); true if it is exactly want.
static bool host_got(const char *want) {
uint8_t buf[128];
uint32_t n = core_host_read(&c, buf, sizeof buf);
return n == strlen(want) && memcmp(buf, want, n) == 0;
}
// The board's GET_INFO reply.
static ps_info_t info(void) {
ps_info_t i;
uint8_t buf[sizeof i];
@@ -326,6 +373,9 @@ static ps_info_t info(void) {
return i;
}
// As a DCE in auto mode the board learns the computer's rate from "AT\r":
// the UART's garbage is dropped meanwhile, the characters it learned from
// still reach the host, and the host changing the format keeps that rate.
TEST(autobaud_learns_as_dce) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -351,6 +401,8 @@ TEST(autobaud_learns_as_dce) {
CHECK(info().baud == 9600);
}
// After locking, a few scattered framing errors are ignored but a burst
// restarts learning, and the board locks onto the computer's new rate.
TEST(autobaud_relearns_on_framing_errors) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -372,6 +424,8 @@ TEST(autobaud_relearns_on_framing_errors) {
CHECK(host_got("AT&F\r"));
}
// AUTOBAUD_RESTART learns again; HOST mode goes back to the host's rate,
// stops learning and is saved; AUTO learns again.
TEST(autobaud_vendor_restart_and_modes) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -395,6 +449,8 @@ TEST(autobaud_vendor_restart_and_modes) {
CHECK(c.ab_state == AB_LEARNING);
}
// As a DTE, auto mode follows the host (a modem does); LEARN mode learns a
// device that just talks (here a GPS), and starts afresh after unplugging.
TEST(autobaud_dte) {
start_auto();
hw.peer_dte = true; run_ms(500);
@@ -412,6 +468,9 @@ TEST(autobaud_dte) {
CHECK(c.ab_state == AB_LEARNING && hw.format.baud == 115200);
}
// Learning copes with a glitch before typing, with lost timings (queue
// overflow), with pauses longer than the timer can count (wrapped or 0), and
// GET_INFO shows the host's rate again after unplugging.
TEST(autobaud_rough_starts) {
start_auto();
hw.peer_dce = true; run_ms(500);
@@ -453,6 +512,7 @@ TEST(autobaud_rough_starts) {
CHECK(info().baud == 115200 && !(info().flags & (PS_INFO_BAUD_LOCKED | PS_INFO_BAUD_LEARNING)));
}
// Runs every test from a fresh fake board; exits 1 if any check failed.
int main(void) {
RUN(detects_computer_as_dce);
RUN(detects_modem_as_dte);
+18
View File
@@ -18,10 +18,13 @@ static int failures, checks;
static core_t c;
static links_t s;
// Advances the fake clock by ms, polling the core every 5 ms as the main loop would.
static void run_ms(uint32_t ms) {
for (uint32_t t = 0; t < ms; t += 5) { hw.now += 5; core_poll(&c); }
}
// Before each test: a fresh core and link table, the baud rate taken from
// the host, and a computer on the line, so the board is in DCE mode.
static void setup(void) {
core_init(&c);
links_init(&s, &c);
@@ -31,8 +34,11 @@ static void setup(void) {
CHECK(c.role == PS_ROLE_DCE);
}
// Writes the string t from link id; returns the bytes accepted.
static uint32_t wr(uint8_t id, const char *t) { return link_write(&s, &c, id, (const uint8_t *)t, (uint32_t)strlen(t)); }
// With only USB, the wired boards behave as before: USB owns the port once
// mounted, its lines and data reach the core, and unplugging frees the port.
TEST(usb_alone_is_like_before) {
CHECK(s.owner == LINK_NONE);
link_up(&s, &c, LINK_USB, true);
@@ -47,6 +53,9 @@ TEST(usb_alone_is_like_before) {
CHECK(s.owner == LINK_NONE && c.host_lines == 0);
}
// With USB plugged in only for power, the first phone to connect owns the
// port; a second link stays connected but read-only (its writes dropped, it
// reads nothing), and ownership passes on as links drop.
TEST(first_wireless_link_owns) {
link_up(&s, &c, LINK_USB, true); // plugged in for power only, port closed
link_up(&s, &c, LINK_BLE, true);
@@ -70,6 +79,9 @@ TEST(first_wireless_link_owns) {
CHECK(s.owner == LINK_USB);
}
// Opening the USB port takes the RS-232 port from a phone and applies USB's
// line coding; a non-owner can't send a break, and closing the port hands
// everything back to the phone, ending USB's break.
TEST(usb_port_open_takes_over) {
link_up(&s, &c, LINK_USB, true);
link_up(&s, &c, LINK_BLE, true);
@@ -88,6 +100,9 @@ TEST(usb_port_open_takes_over) {
CHECK(c.format.baud == 9600);
}
// Over SPP, DCD follows the phone's CONNECT and NO CARRIER result codes,
// even split across writes, but not text that merely contains them; with the
// setting off, DCD just means "connected".
TEST(spp_dcd_from_result_codes) {
link_up(&s, &c, LINK_SPP, true);
run_ms(10);
@@ -109,6 +124,8 @@ TEST(spp_dcd_from_result_codes) {
CHECK(c.outputs & PS_LINE_DCD);
}
// A result code only counts as a whole line: CONNECT at the end of a long
// line of other data doesn't raise DCD, one on its own line does.
TEST(long_lines_are_not_result_codes) {
link_up(&s, &c, LINK_SPP, true);
char big[64];
@@ -123,6 +140,7 @@ TEST(long_lines_are_not_result_codes) {
CHECK(c.outputs & PS_LINE_DCD);
}
// Runs every test from a fresh fake board; exits 1 if any check failed.
int main(void) {
RUN(usb_alone_is_like_before);
RUN(first_wireless_link_owns);