diff --git a/docs/protocol.md b/docs/protocol.md index 8293e01..a25197e 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -44,6 +44,8 @@ OpenShifter 0.2.0 read a zeroed page as colour 0 0 0, which turned every LED off Stock assumes 2 KB flash pages and rewrites halfwords 0 to 0x3ff. OpenShifter preserves everything outside halfwords 0 to 99. +Every way into update mode (`24 00`, both buttons at power-up, a fault, a stall, a host that never configures the unit) writes the flag in halfword 0. If that write fails twice, OpenShifter leaves USB and blinks all LEDs red instead of resetting, because a reset would only start the application again. + ## Update protocol (bootloader) Observed on a real unit (stock to stock, flashed from Linux with `tools/openshifter_flash.py`, 2026-10-20): @@ -160,6 +162,10 @@ OpenShifter adds these (stock ignores them): `tools/openshifter_ctl.py` sends all of these. +Commands marked "saved" write the settings page in flash, and every write erases the page first. A flash page only takes so many erases, and this one also holds the bootloader flag, so OpenShifter writes a change once nothing has changed for 1 second. Up to 16 writes can follow each other; after that, one more is allowed each minute and later changes wait in memory. `24 00` writes a waiting change at once. A change that has not been written yet is lost if the shifter loses power. OpenShifter 0.5.0 and older wrote every change at once, like stock. + +To change the LED colour continuously, for example to show RPM or the gear, use `24 20`. It is never saved. + Feature report ID 0x25, 16 bytes, OpenShifter 0.4.0 and newer: `25` followed by the version string, for example `0.4.0`, padded with NULs. It is read with GET_REPORT (feature). Browsers cannot read the iConfiguration string, so the diff --git a/docs/testing.md b/docs/testing.md index 7065255..4a27308 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4,10 +4,10 @@ OpenShifter has been tested without hardware, in three layers. Run them all with | Suite | Tests | What it covers | |---|---|---| -| `tests/test_shifter.py` | 17 | the gear/sensor core built for the host with trapping UBSan, against exact float oracles; the OpenShifter settings, LEDs and buttons | -| `tests/test_emulated.py` | 20 | the real `openshifter.bin`, and the stock image, on an emulated board | -| `tests/test_ctl.py` | 9 | `openshifter_ctl.py` against the shifter core running in a thread | -| `tests/test_flasher.py` | 19 | the flasher against a simulated bootloader and a fake sysfs tree | +| `tests/test_shifter.py` | 24 | the gear/sensor core built for the host with trapping UBSan, against exact float oracles; the OpenShifter settings, LEDs and buttons; when settings are written to flash | +| `tests/test_emulated.py` | 26 | the real `openshifter.bin`, and the stock image, on an emulated board | +| `tests/test_ctl.py` | 10 | `openshifter_ctl.py` against the shifter core running in a thread | +| `tests/test_flasher.py` | 21 | the flasher against a simulated bootloader and a fake sysfs tree | ## The emulator (`tests/emu`) @@ -19,7 +19,8 @@ OpenShifter has been tested without hardware, in three layers. Run them all with - GPIO and bit-band - TIM3 PWM and DMA, used for the LEDs - USART1 DMA - - flash (FPEC, with programming rules checked on every write) + - flash (FPEC, with programming rules checked on every write), and a worn + settings page that refuses every erase and write - the USB device peripheral and its packet memory - the boot ROM table the stock image calls during PLL setup - the MLX90393 at pin level (the firmware bit-bangs SPI) @@ -36,7 +37,8 @@ and the settings page contents, byte for byte. OpenShifter's own settings start differently from stock (logo off, a warm colour), so these tests give both images a settings page with logo on, gamma off, stock's yellow and full gains in halfwords 0x50 to 0x56, which stock -ignores. The remaining differences are checked explicitly, not skipped: report +ignores. Settings pages are compared after waiting long enough for +OpenShifter's delayed write (see below). The remaining differences are checked explicitly, not skipped: report 0x24 bytes 23, 24, 53 and 54 are cleared after they are checked, OpenShifter's report descriptor (and its length in the HID descriptor) is checked against the expected one and then replaced with stock's, and LED frames in sequential mode are compared with the handbrake LED @@ -85,6 +87,15 @@ real bugs were found this way and fixed: high/low toggle, the handbrake button in H and the handbrake LED in SEQ - both input reports keep flowing when the host polls only every 2 ms or misses frames (0.3.0 failed this: report 0x24 dropped to about 3 per second) +- 40 colour changes in a row cost one flash erase, made 1 s after the last + one; after 16 writes the next change waits, though the LEDs already show it +- `24 00` writes a waiting change before it resets +- with a worn settings page, `24 00` tries the flag twice, then leaves USB and + blinks red instead of resetting + +`SettingsWrites` in `test_shifter.py` checks the write timing itself with a +fake clock: the 1 s wait, the 16-write burst, one more write per minute after +that, and the clock wrapping after 49 days. None of these tests may write flash outside the FPEC rules. The emulator records every program and erase and checks it. @@ -95,9 +106,9 @@ None of these tests may write flash outside the FPEC rules. The emulator records | iConfiguration | 0 (none) | string 4, "OpenShifter x.y.z" | | GET_REPORT | returns a fixed buffer of unrelated RAM | returns the current report 1 or 0x24 | | Control SET_REPORT | ignored if short; a 64-byte one crashes (jump to 0) | runs the command, like interrupt OUT | -| Recovery | none | High/low and Handbrake buttons held at power-up, fault, 3 s stall, host never configuring, PLL failure: all enter the vendor bootloader | +| Recovery | none | High/low and Handbrake buttons held at power-up, fault, 3 s stall, host never configuring, PLL failure: all enter the vendor bootloader. If the flag cannot be written, the unit leaves USB and blinks red | | System clock | 216 MHz | 72 MHz; delays use stock's effective durations | -| Settings write | read-modify-write of 0x400 halfwords, assuming 2 KB pages | erase, then program only halfwords that need it; works with 1 KB or 2 KB pages; same resulting page | +| Settings write | read-modify-write of 0x400 halfwords, assuming 2 KB pages, on every change | erase, then program only halfwords that need it; works with 1 KB or 2 KB pages; same resulting page. Written once nothing has changed for 1 s, at most 16 writes in a row, then one a minute; `24 00` writes at once | | Default LED colour | yellow (255 255 0) | 255 182 78 (warm orange), settable with `24 30` | | LED output | colour × 2/3 | optional gamma 2.2 (`24 34 1`, off by default) and a white balance gain per channel, then × 2/3; gamma off and gains of 255 give stock's output | | Logo LED | always lit | off unless turned on (`24 31 1`) | @@ -131,6 +142,8 @@ Some timings differ by a few tens of milliseconds, all measured in the emulator: - USB electrical and timing behaviour of the AIR32 USB block - the AIR32 PLL at 72 MHz (the stock image only shows its 216 MHz configuration) - the flash page size + - the delayed settings writes and the red stop after a failed flag write + have only run in the emulator - **The vendor bootloader.** It is not in any update package, so the flasher is tested against a simulator written from Tuner's code. Two real updates went through it without errors; an interrupted update has not been tried. See @@ -150,7 +163,7 @@ Some timings differ by a few tens of milliseconds, all measured in the emulator: ```sh pip install -r requirements-dev.txt # unicorn 2.1.4 make -C firmware # builds build/openshifter.bin -make -C firmware test # all suites (about 4 minutes) +make -C firmware test # all suites (about 6 minutes) python3 -m unittest discover -s tests -p test_flasher.py -v # just one suite ``` diff --git a/firmware/src/flash.c b/firmware/src/flash.c index 47af171..cc0652e 100644 --- a/firmware/src/flash.c +++ b/firmware/src/flash.c @@ -8,7 +8,9 @@ */ #include "flash.h" #include "board.h" +#include "periph.h" #include "regs.h" +#include "usb.h" #define PAGE_HALFWORDS 1024 @@ -91,7 +93,24 @@ int settings_write(const uint16_t st[SH_SETTINGS_HALFWORDS]) write_active = 1; int err = write_page(); write_active = 0; - return err; + return err ? -1 : 1; +} + +/* The flag cannot be written, so a reset would only start the application + * again, and a fault would come back here and erase again. Leave the bus and + * blink red until the unit is unplugged. */ +static __attribute__((noreturn)) void flash_failed(void) +{ + static const uint8_t red[9] = {0, 170, 0, 0, 170, 0, 0, 170, 0}; + static const uint8_t off[9]; + usb_detach(); + leds_init(); + for (unsigned n = 0;; n++) { + while (leds_busy()) + ; + leds_show(n & 1 ? off : red); + delay_cycles(g_sysclk_hz / 4); /* 250 ms */ + } } void enter_bootloader(void) @@ -111,6 +130,7 @@ void enter_bootloader(void) for (unsigned i = 0; i < PAGE_HALFWORDS; i++) page[i] = *flash_hw(i); page[SETTINGS_BOOT_FLAG] = 1; - write_page(); + if (write_page() && write_page()) + flash_failed(); board_reset(); } diff --git a/firmware/src/flash.h b/firmware/src/flash.h index ef268dc..872c417 100644 --- a/firmware/src/flash.h +++ b/firmware/src/flash.h @@ -10,13 +10,14 @@ void settings_read(uint16_t st[SH_SETTINGS_HALFWORDS]); /* Read-modify-write of the settings page; only the first - * SH_SETTINGS_HALFWORDS halfwords change. Returns 0 on success (or nothing - * to do), -1 on a flash error. */ + * SH_SETTINGS_HALFWORDS halfwords change. Returns 0 if nothing changed (no + * erase), 1 after a good write, -1 on a flash error. */ int settings_write(const uint16_t st[SH_SETTINGS_HALFWORDS]); /* Set the bootloader flag and reset. The vendor bootloader then stays in * update mode (USB 10f5:7097) until a new image is written. Safe to call from - * any context, including fault handlers. */ + * any context, including fault handlers. If the flag cannot be written after + * one retry, the unit leaves USB and blinks red instead of resetting. */ __attribute__((noreturn)) void enter_bootloader(void); #endif diff --git a/firmware/src/main.c b/firmware/src/main.c index d0f9076..563896a 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -13,6 +13,12 @@ * - SysTick sees PendSV or the main loop stalled for 3 s; * - the host reset the bus 6+ times without ever configuring the device; * - the PLL could not be configured. + * If the bootloader flag cannot be written, the unit leaves USB and blinks + * red instead (flash.c). + * + * A settings change reaches flash 1 s after the last change, at a limited + * rate (sh_saves_* in shifter.c), because every write erases the page that + * holds the bootloader flag. */ #include "shifter.h" #include "board.h" @@ -27,7 +33,8 @@ static shifter_t sh; static uint16_t st_loaded[SH_SETTINGS_HALFWORDS]; /* as read at boot */ static uint16_t st_pending[SH_SETTINGS_HALFWORDS]; /* snapshot for the next write */ -static volatile uint8_t save_pending, boot_pending; +static sh_saves_t saves; /* touch with interrupts off */ +static volatile uint8_t boot_pending; static volatile uint8_t sensor_ready, sensor_paused, sensor_off_timer, sensor_off_ticks; static volatile uint8_t asleep, led_dirty; @@ -94,7 +101,7 @@ static void apply_actions(unsigned act) for (unsigned i = 0; i < SH_SETTINGS_HALFWORDS; i++) st_pending[i] = st_loaded[i]; shifter_save(&sh, st_pending); - save_pending = 1; + sh_saves_changed(&saves, g_ms); } if (act & SH_ACT_BOOT) { led_dirty = 1; @@ -206,6 +213,41 @@ void usb_lp_handler(void) usb_irq_handler(); } +/* ---- settings writes ------------------------------------------------------ */ + +static void spent(void) +{ + irq_disable(); + sh_saves_spent(&saves); + irq_enable(); +} + +/* Writes the settings when sh_saves_take() allows it. Returns 1 while a + * change is still waiting. */ +static int save_settings(void) +{ + uint16_t st[SH_SETTINGS_HALFWORDS]; + irq_disable(); + int due = sh_saves_take(&saves, g_ms, boot_pending); + if (due) + for (unsigned i = 0; i < SH_SETTINGS_HALFWORDS; i++) + st[i] = st_pending[i]; + irq_enable(); + + if (due) { + int r = settings_write(st); + if (r) + spent(); + if (r < 0 && settings_write(st)) /* one retry */ + spent(); + } + + irq_disable(); + int waiting = saves.pending; + irq_enable(); + return waiting; +} + /* ---- startup -------------------------------------------------------------- */ static int buttons_held_at_power_up(void) @@ -220,6 +262,8 @@ static int buttons_held_at_power_up(void) int main(void) { + sh_saves_init(&saves); + /* Exception priorities: SysTick 0 (highest), USB 1, PendSV 3. */ SCB_SHPR3 = (PRIO_PENDSV << 4 << 16) | (0u << 24); @@ -259,17 +303,9 @@ int main(void) else uart_enable(); - if (save_pending) { - uint16_t st[SH_SETTINGS_HALFWORDS]; - irq_disable(); - for (unsigned i = 0; i < SH_SETTINGS_HALFWORDS; i++) - st[i] = st_pending[i]; - save_pending = 0; - irq_enable(); - settings_write(st); - } + int waiting = save_settings(); - if (boot_pending && !save_pending) { + if (boot_pending && !waiting) { /* "24 00": show yellow, then hand over to the bootloader. */ uint32_t t0 = g_ms; while ((led_dirty || leds_busy()) && g_ms - t0 < 200) diff --git a/firmware/src/shifter.c b/firmware/src/shifter.c index f772cc7..84263e3 100644 --- a/firmware/src/shifter.c +++ b/firmware/src/shifter.c @@ -1007,3 +1007,41 @@ void shifter_led_grb(const shifter_t *s, int asleep, uint8_t out[9]) if (s->options & SH_OPT_LOGO) led_put(s, out, SH_LED_LOGO, r, g, b); } + +/* ---- settings writes ---------------------------------------------------- */ + +void sh_saves_init(sh_saves_t *v) +{ + v->changed_ms = 0; + v->refill_ms = 0; + v->pending = 0; + v->allowance = SH_SAVE_BURST; +} + +void sh_saves_changed(sh_saves_t *v, uint32_t now_ms) +{ + v->pending = 1; + v->changed_ms = now_ms; +} + +int sh_saves_take(sh_saves_t *v, uint32_t now_ms, int urgent) +{ + while (v->allowance < SH_SAVE_BURST && now_ms - v->refill_ms >= SH_SAVE_REFILL_MS) { + v->allowance++; + v->refill_ms += SH_SAVE_REFILL_MS; + } + if (v->allowance >= SH_SAVE_BURST) + v->refill_ms = now_ms; + if (!v->pending) + return 0; + if (!urgent && (now_ms - v->changed_ms < SH_SAVE_QUIET_MS || !v->allowance)) + return 0; + v->pending = 0; + return 1; +} + +void sh_saves_spent(sh_saves_t *v) +{ + if (v->allowance) + v->allowance--; +} diff --git a/firmware/src/shifter.h b/firmware/src/shifter.h index 6b239b2..3e1e079 100644 --- a/firmware/src/shifter.h +++ b/firmware/src/shifter.h @@ -162,6 +162,30 @@ void shifter_uart_packet(const shifter_t *s, uint8_t out[16]); * asleep. */ void shifter_led_grb(const shifter_t *s, int asleep, uint8_t out[9]); +/* When to write the settings. Every write erases the settings page, which + * also holds the bootloader flag, and a flash page only takes so many + * erases. A change is written once nothing has changed for + * SH_SAVE_QUIET_MS. Up to SH_SAVE_BURST writes can follow each other; + * after that, one more is allowed every SH_SAVE_REFILL_MS. */ +#define SH_SAVE_QUIET_MS 1000u +#define SH_SAVE_BURST 16u +#define SH_SAVE_REFILL_MS 60000u + +typedef struct { + uint32_t changed_ms; /* time of the last change */ + uint32_t refill_ms; /* time the allowance last grew, or was full */ + uint8_t pending; /* a change is waiting to be written */ + uint8_t allowance; /* writes left before the limit applies */ +} sh_saves_t; + +void sh_saves_init(sh_saves_t *v); +void sh_saves_changed(sh_saves_t *v, uint32_t now_ms); +/* 1 if the waiting change should be written now, and clears it. `urgent` + * (update mode was asked for) skips both the wait and the limit. */ +int sh_saves_take(sh_saves_t *v, uint32_t now_ms, int urgent); +/* Call after each write that erased the page. */ +void sh_saves_spent(sh_saves_t *v); + /* Exposed for tests. */ uint32_t sh_isqrt(uint32_t v); void sh_sincos_q30(uint32_t angle, int32_t *sin_q30, int32_t *cos_q30); diff --git a/firmware/src/usb.c b/firmware/src/usb.c index f0818f0..eb0388b 100644 --- a/firmware/src/usb.c +++ b/firmware/src/usb.c @@ -604,6 +604,12 @@ void usb_reconnect(void) delay_ms(STOCK_MS(200)); } +void usb_detach(void) +{ + USB_AIR_DPPU = 0; + USB_CNTR = CNTR_FRES | CNTR_PDWN; +} + void usb_init(void) { RCC_APB1ENR |= APB1_USB; diff --git a/firmware/src/usb.h b/firmware/src/usb.h index dea61d7..d50003a 100644 --- a/firmware/src/usb.h +++ b/firmware/src/usb.h @@ -13,6 +13,8 @@ extern volatile uint16_t usb_reset_count; /* Drop off the bus, wait, come back. Blocking. */ void usb_reconnect(void); +/* Drop off the bus and stay off. */ +void usb_detach(void); void usb_init(void); void usb_irq_handler(void); diff --git a/tests/emu/stm32emu.py b/tests/emu/stm32emu.py index 99fc997..b631fab 100644 --- a/tests/emu/stm32emu.py +++ b/tests/emu/stm32emu.py @@ -583,6 +583,7 @@ def __init__(self, image, settings=None, *, mips=24, slice_us=20, page_size=2048 self.flash_keys = 0 self.flash_events = [] self.flash_violations = [] + self.flash_worn = False # True: the settings page refuses every erase and program self.sensor = Sensor() self.buttons = {'PA4': False, 'PA5': False, 'PB10': False} self.usb = UsbDevice(self) @@ -632,6 +633,11 @@ def flash_bytes(self, addr, n): def _flash_write_hook(self, uc, access, addr, size, value, ud): cr = self.regs[0x40022010] old = struct.unpack('= SETTINGS_ADDR: + self.flash_events.append(('program-failed', addr, value)) + self.regs[0x4002200C] |= 0x04 + self._undo = (addr & ~1, old) + return ok = (cr & 1) and not (cr & 0x80) and size == 2 and not addr & 1 and (old == 0xFFFF or value == 0) if addr < SETTINGS_ADDR: ok = False @@ -667,6 +673,9 @@ def _flash_ctrl_write(self, a, v): if page < SETTINGS_ADDR or page >= FLASH_BASE + FLASH_SIZE: self.flash_violations.append(('erase', hex(page))) self.regs[0x4002200C] |= 0x10 + elif self.flash_worn: + self.flash_events.append(('erase-failed', page)) + self.regs[0x4002200C] |= 0x10 else: self.uc.mem_write(page, b'\xff' * self.page_size) self.flash_events.append(('erase', page)) diff --git a/tests/native/shim.c b/tests/native/shim.c index 827eb6e..5798dbe 100644 --- a/tests/native/shim.c +++ b/tests/native/shim.c @@ -26,3 +26,5 @@ void t_match(const shifter_t *s, int i, int *x, int *y, int *r) } int t_settings_valid(const shifter_t *s) { return s->settings_valid; } + +unsigned t_saves_sizeof(void) { return sizeof(sh_saves_t); } diff --git a/tests/test_emulated.py b/tests/test_emulated.py index 7a89700..7f20145 100644 --- a/tests/test_emulated.py +++ b/tests/test_emulated.py @@ -26,13 +26,17 @@ import openshifter_flash as flasher # noqa: E402 from harness import OPENSHIFTER_BIN, Rig, openshifter_image, stock_image # noqa: E402 from test_flasher import STOCK_REPORT_DESCRIPTOR # noqa: E402 -from test_shifter import led # noqa: E402 (LED colour reference) +from test_shifter import SAVE_BURST, SAVE_QUIET_MS, led # noqa: E402 (LED colour reference) if not OPENSHIFTER_BIN.exists(): raise unittest.SkipTest('build the firmware first: make -C firmware') VERSION = flasher.Image(openshifter_image()).openshifter_version +# Long enough for a settings change to reach flash. +SETTLE_MS = SAVE_QUIET_MS + 100 +RED, DARK = bytes([0, 170, 0]) * 3, bytes(9) + GEARS = [(1986, 2400, 0x80), (2400, -1886, 0x80), (40, 3175, 0x80), (70, -2536, 0x80), (-1956, 1720, 0x80), (-2576, -1856, 0x80), (-866, 170, 0x70), (-1116, -236, 0x70)] @@ -52,6 +56,11 @@ def hb(): if not hb_first: hb() r.move(0, 0) + r.run(SETTLE_MS) + + +def erases(r): + return sum(e[0] == 'erase' for e in r.m.flash_events) class EmulatedCase(unittest.TestCase): @@ -226,6 +235,7 @@ def test_options_persist_and_drive_leds(self): blue, red = led(30, 60, 90), led(255, 0, 0) self.assertEqual(r.m.led_frames[-1][1], blue + blue + red) self.assertEqual(r.last(0x24)[23], 0x83) + r.run(SETTLE_MS) self.assertFlashClean(r) r = r.reboot(h_pattern=True).boot() @@ -250,6 +260,57 @@ def test_options_persist_and_drive_leds(self): self.assertEqual(r.m.led_frames[-1][1][:3], led(0, 255, 0)) self.assertFlashClean(r) + def test_settings_are_written_once_they_stop_changing(self): + r = Rig(openshifter_image(), h_pattern=True).boot() + r.run(SETTLE_MS) + n = erases(r) + for i in range(40): + r.command(0x24, 0x30, i, 255 - i, 7, ms=10) + self.assertEqual(erases(r), n, 'written while the colour was still changing') + r.run(SETTLE_MS) + self.assertEqual(erases(r), n + 1) + self.assertEqual(r.m.settings()[0x51:0x54], [39, 216, 7]) + self.assertFlashClean(r) + + def test_writes_are_limited_after_a_burst(self): + r = Rig(openshifter_image(), h_pattern=True).boot() + r.run(SETTLE_MS) + left = SAVE_BURST - erases(r) # a blank page is written once at boot + for i in range(left + 1): + r.command(0x24, 0x30, i, 0, 0, ms=SETTLE_MS) + self.assertEqual(erases(r), SAVE_BURST) + self.assertEqual(r.m.settings()[0x51:0x54], [left - 1, 0, 0], 'the last change should wait') + self.assertEqual(r.last(0x24)[6:9], bytes([left, 0, 0]), 'the last change should be in use') + self.assertFlashClean(r) + + def test_update_command_writes_waiting_settings_first(self): + r = Rig(openshifter_image()).boot() + r.run(SETTLE_MS) + t0 = r.m.time_us + r.command(0x24, 0x30, 1, 2, 3, ms=0) + r.command(*flasher.command(flasher.CMD_BOOT), ms=0) + r.m.run(ms=1000) + self.assertEnteredBootloader(r) + self.assertLess(r.reset_events()[0] - t0, SAVE_QUIET_MS * 1000, 'waited for the quiet time') + self.assertEqual(r.m.settings()[0x51:0x54], [1, 2, 3]) + + def test_worn_settings_page_stops_with_red_leds(self): + """If the bootloader flag cannot be written, a reset would start the + application again (or loop through a fault): stop instead.""" + r = Rig(openshifter_image()).boot() + r.run(SETTLE_MS) + r.m.flash_worn = True + t0 = r.m.time_us + r.command(*flasher.command(flasher.CMD_BOOT), ms=0) + r.m.run(ms=2500) + self.assertEqual(r.reset_events(), [], 'reset with the flag not set') + self.assertEqual(sum(e[0] == 'erase-failed' for e in r.m.flash_events), 2, 'one try and one retry') + self.assertEqual(r.m.host.state, 'detached', 'still on USB') + frames = [f for t, f in r.m.led_frames if t > t0 and f != led(255, 255, 0) * 3] + self.assertGreaterEqual(len(frames), 4) + self.assertEqual(frames[:4], [RED, DARK, RED, DARK]) + self.assertFlashClean(r) + def as_stock_page(): """An erased settings page with OpenShifter's own settings (halfwords @@ -428,6 +489,7 @@ def sc(img, Rig): for x, y, z in steps: r.move(x, y, z) out.append(r.state()) + r.run(SETTLE_MS) return out, r.settings_page() (a, pa), (b, pb) = self.both(sc) for i, (x, y) in enumerate(zip(a, b)): @@ -450,6 +512,7 @@ def sc(img, Rig): r.move(-300, -1500) r.command(0x24, 0x21, 10) snap('cal 10') + r.run(SETTLE_MS) page1 = r.settings_page() r = r.reboot(h_pattern=True).boot() snap('reboot') @@ -480,7 +543,7 @@ def sc(img, Rig): r.press('PA4', hold=True, ms=100) r.press('PA4', hold=False, ms=100) snap('A toggle') - r.run(300) + r.run(SETTLE_MS) return log, page1, r.settings_page(), [f for _, f in r.m.led_frames[-3:]] a, b = self.both(sc) for x, y in zip(a[0], b[0]): diff --git a/tests/test_shifter.py b/tests/test_shifter.py index 9f320ab..74aa590 100644 --- a/tests/test_shifter.py +++ b/tests/test_shifter.py @@ -11,6 +11,7 @@ import os import pathlib import random +import re import shutil import struct import subprocess @@ -24,6 +25,17 @@ SH_FRAME_OK, SH_FRAME_EMPTY, SH_FRAME_POWER_OFF = 0, 1, 2 SH_ACT_SAVE, SH_ACT_LED, SH_ACT_BOOT = 1, 2, 4 + +def _define(name): + m = re.search(rf'^#define {name}\s+(\d+)u?\b', (SRC / 'shifter.h').read_text(), re.M) + return int(m.group(1)) + + +# Settings write timing, from shifter.h (also used by test_emulated.py). +SAVE_QUIET_MS = _define('SH_SAVE_QUIET_MS') +SAVE_BURST = _define('SH_SAVE_BURST') +SAVE_REFILL_MS = _define('SH_SAVE_REFILL_MS') + lib = None _tmp = None @@ -55,7 +67,12 @@ def setUpModule(): ('shifter_command', ctypes.c_uint, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint]), ('shifter_buttons', ctypes.c_uint, [ctypes.c_void_p, i32, i32, i32]), ('shifter_led_grb', None, [ctypes.c_void_p, i32, ctypes.c_char_p]), - ('shifter_report36', None, [ctypes.c_void_p, ctypes.c_char_p])): + ('shifter_report36', None, [ctypes.c_void_p, ctypes.c_char_p]), + ('sh_saves_init', None, [ctypes.c_void_p]), + ('sh_saves_changed', None, [ctypes.c_void_p, u32]), + ('sh_saves_take', i32, [ctypes.c_void_p, u32, i32]), + ('sh_saves_spent', None, [ctypes.c_void_p]), + ('t_saves_sizeof', ctypes.c_uint, [])): f = getattr(lib, name) f.restype, f.argtypes = res, args @@ -504,5 +521,98 @@ def test_led_identify_and_update(self): self.assertEqual(self.leds(s), [led(255, 255, 0)] * 3) +class Saves(ctypes.Structure): + _fields_ = [('changed_ms', ctypes.c_uint32), ('refill_ms', ctypes.c_uint32), + ('pending', ctypes.c_uint8), ('allowance', ctypes.c_uint8)] + + +class SettingsWrites(unittest.TestCase): + """When main.c writes the settings page (sh_saves_*).""" + + def setUp(self): + self.assertEqual(ctypes.sizeof(Saves), lib.t_saves_sizeof()) + self.v = Saves() + lib.sh_saves_init(ctypes.byref(self.v)) + + def changed(self, t): + lib.sh_saves_changed(ctypes.byref(self.v), t % 2**32) + + def take(self, t, urgent=0): + return lib.sh_saves_take(ctypes.byref(self.v), t % 2**32, urgent) + + def write(self, t): + """A change at t, written once it is due; returns the time of the write.""" + self.changed(t) + t += SAVE_QUIET_MS + while not self.take(t): + t += 1000 + lib.sh_saves_spent(ctypes.byref(self.v)) + return t + + def test_nothing_to_write(self): + self.assertEqual(self.take(0), 0) + self.assertEqual(self.take(10**6, urgent=1), 0) + + def test_written_once_changes_stop(self): + self.changed(0) + self.changed(400) + self.changed(900) + self.assertEqual(self.take(900 + SAVE_QUIET_MS - 1), 0) + self.assertEqual(self.take(900 + SAVE_QUIET_MS), 1) + self.assertEqual(self.take(900 + SAVE_QUIET_MS + 1), 0, 'written twice') + + def test_urgent_write_skips_the_wait_and_the_limit(self): + for _ in range(SAVE_BURST): + lib.sh_saves_spent(ctypes.byref(self.v)) + self.changed(5) + self.assertEqual(self.take(5), 0) + self.assertEqual(self.take(5, urgent=1), 1) + self.assertEqual(self.v.allowance, 0) + + def test_limit_after_a_burst(self): + t = 0 + for _ in range(SAVE_BURST): + t = self.write(t) + self.assertEqual(self.v.allowance, 0) + # The allowance started to drop with the first write, at SAVE_QUIET_MS. + first = SAVE_QUIET_MS + self.changed(t) + self.assertEqual(self.take(first + SAVE_REFILL_MS - 1), 0) + self.assertEqual(self.take(first + SAVE_REFILL_MS), 1) + lib.sh_saves_spent(ctypes.byref(self.v)) + # From then on, one write per SAVE_REFILL_MS. + t, times = first + SAVE_REFILL_MS, [] + for _ in range(3): + t = self.write(t) + times.append(t) + self.assertEqual(times, [first + k * SAVE_REFILL_MS for k in (2, 3, 4)]) + + def test_allowance_comes_back(self): + t = 0 + for _ in range(SAVE_BURST): + t = self.write(t) + self.take(t + SAVE_BURST * SAVE_REFILL_MS) + self.assertEqual(self.v.allowance, SAVE_BURST) + # Time spent with a full allowance is not stored up for later. + self.take(t + 10**7) + t = self.write(t + 10**7) + self.take(t + SAVE_REFILL_MS - 1) + self.assertEqual(self.v.allowance, SAVE_BURST - 1) + self.take(t + SAVE_REFILL_MS) + self.assertEqual(self.v.allowance, SAVE_BURST) + + def test_clock_wraps(self): + start = 2**32 - 300 + self.changed(start) + self.assertEqual(self.take(start + SAVE_QUIET_MS - 1), 0) + self.assertEqual(self.take(start + SAVE_QUIET_MS), 1) + t = start + for _ in range(SAVE_BURST): + t = self.write(t) + self.changed(t) + self.assertEqual(self.take(start + SAVE_QUIET_MS + SAVE_REFILL_MS - 1), 0) + self.assertEqual(self.take(start + SAVE_QUIET_MS + SAVE_REFILL_MS), 1) + + if __name__ == '__main__': unittest.main() diff --git a/wiki/Troubleshooting.md b/wiki/Troubleshooting.md index 326448d..7d82005 100644 --- a/wiki/Troubleshooting.md +++ b/wiki/Troubleshooting.md @@ -10,6 +10,7 @@ | A gear is detected wrong | [Calibrate](Calibrate) again, then unplug the shifter and plug it back in. | | No gear shows right after plugging in | Move the lever through neutral once. | | The Settings tab says it needs OpenShifter | The shifter runs the stock firmware. [Install OpenShifter](Install) first. | +| All the LEDs blink red | The shifter could not write to its memory while going into update mode, and stopped. Unplug it and plug it back in: it should start normally. If it happens again, [open an issue](https://github.com/FilipNone/OpenShifter/issues). | | Linux: games see two shifters, or every press twice | You have the `hid-velocityone-multi-shift` driver installed. OpenShifter does not need it: stop and remove it. | ## Start in update mode by hand