diff --git a/README.md b/README.md index 4500219..4539e2d 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Free replacement firmware for the **Turtle Beach VelocityOne Multi-Shift**, inst - The Handbrake button as a normal button while the switch is in H - The High/low button as a toggle, if you like - A neutral button, for games that stay in gear when you move the lever to neutral +- Anti-jitter, so the gears and the handbrake axis hold still - On Linux, games find the shifter as a joystick with no extra driver - The Turtle Beach firmware can be put back at any time diff --git a/docs/protocol.md b/docs/protocol.md index a25197e..ee8dc97 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -30,7 +30,7 @@ Settings page, as 16-bit halfwords: | 0x2a to 0x36 | 13 auxiliary bytes (`24 23`) | | 0x37 to 0x3e | per-gear match radius | | 0x3f, 0x40 | sequential thresholds in y: lever pushed forward (positive), pulled back (negative) | -| 0x50 | OpenShifter options: high byte `0xA5` marks them as set; bit 0 logo LED on, bit 1 high/low button is a toggle, bit 3 gamma correction on, bit 4 neutral button on (0.5.0) | +| 0x50 | OpenShifter options: high byte `0xA5` marks them as set; bit 0 logo LED on, bit 1 high/low button is a toggle, bit 3 gamma correction on, bit 4 neutral button on (0.5.0), bits 5 and 6 anti-jitter level (0.6.0) | | 0x51 to 0x53 | OpenShifter LED colour R, G, B | | 0x54 to 0x56 | OpenShifter white balance gains R, G, B | | 0x63 | `0x1254` once calibration is complete | @@ -38,7 +38,7 @@ Settings page, as 16-bit halfwords: Stock never reads or writes halfwords 0x41 to 0x62. OpenShifter uses 0x50 to 0x56. Without the `0xA5` marker in halfword 0x50 they mean the defaults: logo off, high/low as a button, colour 255 182 78 (warm orange), gamma off, gains -255 162 96, neutral button off. The marker is there +255 162 96, neutral button off, anti-jitter none. The marker is there because the page can come back from an update as zeros, not only as `0xFFFF`: OpenShifter 0.2.0 read a zeroed page as colour 0 0 0, which turned every LED off. @@ -97,7 +97,7 @@ application collection: 12 buttons and 4 constant padding bits, the 16-bit Z axis, and report 0x24 in and out on vendor page `0xFF00`, which Linux's HID input driver ignores. The top-level usage (Generic Desktop, Joystick) and the input and output report IDs and sizes are the same as -stock's. OpenShifter 0.4.0 and newer add feature report 0x25 (below). +stock's. OpenShifter 0.4.0 and newer add feature report 0x25, and 0.6.0 and newer input report 0x26 (below). In 0.4.0 the 12 button bits are buttons 1 to 12. From 0.5.0 they are buttons 2 to 13, and the next bit (`buttons` bit 4) is button 1, the neutral button, @@ -131,7 +131,7 @@ Input reports, sent every 2 ms: | 13 + 6k | gear k+1 x, y, big-endian | | 17, 29, 30, 35, 36, 41, 42, 47 | per-gear radius / 8 | | 18 | flags: bit 0 button A, 1 button B, 2 switch in H, 3 handbrake mode, 4 lever pulled back, 5 lever pushed forward (the last two are `seq_down` and `seq_up` in the source) | - | 23 | OpenShifter only (stock sends 0): bit 7 set, bit 0 logo LED on, bit 1 high/low is a toggle, bit 2 toggle is on, bit 3 gamma on, bit 4 neutral button on | + | 23 | OpenShifter only (stock sends 0): bit 7 set, bit 0 logo LED on, bit 1 high/low is a toggle, bit 2 toggle is on, bit 3 gamma on, bit 4 neutral button on, bits 5 and 6 the anti-jitter level | | 24, 53, 54 | OpenShifter 0.3.0 and newer (stock sends 0): white balance gains R, G, B | | 48 | r / 8: the field strength at the sensor. With x and y it gives the lever's tilt, atan2(√(x² + y²) / 6.55, √(r² − (x² + y²) / 6.55²)) | | 59 to 62 | handbrake rest / pulled x | @@ -158,6 +158,7 @@ OpenShifter adds these (stock ignores them): | `24 33 R G B s` | white balance: a gain per channel, 255 = full; saved when s is 1, live only when 0 | | `24 34 v` | gamma correction: 1 on, 0 off (default); saved | | `24 35 v` | neutral button (0.5.0 and newer): 1 on, 0 off (default); saved | +| `24 36 v` | anti-jitter on the lever position (0.6.0 and newer): 0 none (default), 1 low, 2 medium, 3 high; saved | | `24 3F n` | light only LED n of the chain (0 to 2) in white, to find which LED is which; `24 3F FF` ends it. Not saved | `tools/openshifter_ctl.py` sends all of these. @@ -166,12 +167,27 @@ Commands marked "saved" write the settings page in flash, and every write erases To change the LED colour continuously, for example to show RPM or the gear, use `24 20`. It is never saved. +While the settings page is erased and written (about 25 ms), OpenShifter takes no USB packet: EP0 ignores the host, so a control request then fails, and EP1 answers NAK, so input reports pause. On a unit, control requests during the erase froze it, with interrupts off or not. + +Anti-jitter (`24 36`) steadies the lever position as the sensor reports it: x, y and z (s14). Everything else is worked out from those, so it applies to the gears, the sequential shifts, the handbrake axis, the x and y in report 0x24 and calibration. Each value runs through a running average of the last 2 samples (low and medium) or about 4 (high), then holds still until the average moves more than a band from it: 4, 8 or 16 units for x and y, 13, 16 or 20 for z. Going back the other way costs twice the band of free travel. If the average stays more than half a band away for 128 ms, the value moves to it, so a still lever reads within half a band of where it is. A change larger than 150 units in x or y, or 80 in z, passes at once, so shifts and a yanked handbrake are never late. Measured on a unit, x and y have a noise of about 2 (standard deviation) and z flickers by one step of its high byte (25 units). A single frame that jumps more than 600 in x or y, or 300 in z, from the one before is a bad read and is skipped; if the next frame agrees, it counts. With none (the default), the values are the raw ones, as on stock. + 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 web tool uses this report to tell OpenShifter versions apart. Stock firmware and older OpenShifter versions do not declare it. +Input report ID 0x26, 5 bytes, OpenShifter 0.6.0 and newer: `26 x_hi x_lo y_hi y_lo`, +the lever's x and y as the sensor read them, before anti-jitter. It is sent while anti-jitter +is on, in every other slot of report 0x24, so the host gets no more reports than usual and +report 0x24 comes every 4 ms instead of 2. With anti-jitter off, report 0x24 already has the +raw reading. The web tool draws it under the position games see. + +Two earlier designs failed on a real unit with Chrome. Reading report 0x26 as a feature +report every 15 ms froze the unit during a settings write (see below). Asking for it with a +command every 400 ms held Chrome's input reports back for 60 to 90 ms after each command; +the same commands from Python on Linux caused no gap, so the delay is in Chrome. + LEDs in OpenShifter: | LED | Lit | diff --git a/docs/testing.md b/docs/testing.md index 4a27308..f4dd2f6 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4,9 +4,9 @@ OpenShifter has been tested without hardware, in three layers. Run them all with | Suite | Tests | What it covers | |---|---|---| -| `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_shifter.py` | 33 | the gear/sensor core built for the host with trapping UBSan, against exact float oracles; the OpenShifter settings, LEDs and buttons; anti-jitter; when settings are written to flash | +| `tests/test_emulated.py` | 29 | the real `openshifter.bin`, and the stock image, on an emulated board | +| `tests/test_ctl.py` | 11 | `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`) @@ -90,14 +90,27 @@ real bugs were found this way and fixed: - 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 anti-jitter at high, a lever held with sensor noise reports still x + and y in H and a still handbrake axis, where none follows the noise; a full + pull still reaches 65535 at once, report 0x26 keeps giving the raw reading, + and the level survives a power cycle +- with anti-jitter on, report 0x26 takes every other report 0x24 slot, with the + total report rate unchanged; with it off there is no report 0x26 +- control requests every 15 ms through a settings write: no USB packet and no + interrupt while the flash is busy, and only requests during the write fail - 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. +that, and the clock wrapping after 49 days. `AntiJitter` checks each level +against noise on x, y and z at neutral, in a gear and on the handbrake; gear 7 +right at its limit (the raw reading keeps dropping and taking it); shifts and +handbrake yanks (the same reports at the same samples as none); slow moves; +calibration on a noisy sensor; a single bad read (skipped) and a real jump +(at most one frame later); report 0x26; and a restart after the sensor resets. -None of these tests may write flash outside the FPEC rules. The emulator records every program and erase and checks it. +None of these tests may write flash outside the FPEC rules. The emulator records every program and erase and checks it. An erase takes 20 ms and a halfword 50 µs in the emulator, and taking an interrupt or a USB packet in that time is a violation too (a unit froze that way). The differential tests turn that timing off, because stock writes for about 70 ms and its timing would no longer match. ## Intentional differences @@ -118,7 +131,8 @@ None of these tests may write flash outside the FPEC rules. The emulator records | Gear and sequential debounce | 20 samples (40 ms) | 5 samples (10 ms) (`Core.test_calibration_round_trip_and_gears`); not yet checked on a real unit | | Handbrake button LED | lit in every mode; green in handbrake mode | the set colour in H, off in sequential mode, green in handbrake mode | | High/low button (A) | a button | a button, or a latching toggle (`24 32 1`) with a red/green LED | -| Report descriptor | 11 buttons in nested application collections without a usage; Linux maps them to `BTN_0`.. and udev does not tag a joystick | one Joystick collection with the 12 report bits as buttons 2 to 13, button 1 for the optional neutral button (`24 35 1`), padding, Z and report 0x24 on vendor page `0xFF00` (`OpenShifter.test_report_descriptor`); not yet checked on a real host | +| Report descriptor | 11 buttons in nested application collections without a usage; Linux maps them to `BTN_0`.. and udev does not tag a joystick | one Joystick collection with the 12 report bits as buttons 2 to 13, button 1 for the optional neutral button (`24 35 1`), padding, Z, and reports 0x24, 0x25 and 0x26 on vendor page `0xFF00` (`OpenShifter.test_report_descriptor`); not yet checked on a real host | +| Lever position | raw | optional anti-jitter on x, y and z (`24 36`, none by default); none gives stock's values | | Report 0x24 bytes 23, 24, 53, 54 | 0 | OpenShifter options and white balance | | Settings halfwords 0x50 to 0x56 | unused | OpenShifter options, colour and white balance | @@ -142,8 +156,7 @@ 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 red stop after a failed flag write has 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 diff --git a/firmware/Makefile b/firmware/Makefile index 7408b81..9e3ecfd 100644 --- a/firmware/Makefile +++ b/firmware/Makefile @@ -1,5 +1,5 @@ # OpenShifter firmware. Needs clang + lld (LLVM >= 15); no libc, no libgcc. -VERSION ?= 0.5.0 +VERSION ?= 0.6.0 BUILD := build TARGET := $(BUILD)/openshifter SRCS := $(wildcard src/*.c) diff --git a/firmware/src/flash.c b/firmware/src/flash.c index cc0652e..50cab23 100644 --- a/firmware/src/flash.c +++ b/firmware/src/flash.c @@ -90,8 +90,16 @@ int settings_write(const uint16_t st[SH_SETTINGS_HALFWORDS]) } if (!changed) return 0; + /* A unit froze when the host sent control requests during a settings + * write: the erase never finished. So the USB block takes no packets while + * the flash is busy (usb_pause), and no interrupt runs then either. Reports + * and the clock pause for the write, about 25 ms. */ write_active = 1; + irq_disable(); + usb_pause(); int err = write_page(); + usb_unpause(); + irq_enable(); write_active = 0; return err ? -1 : 1; } @@ -130,6 +138,7 @@ void enter_bootloader(void) for (unsigned i = 0; i < PAGE_HALFWORDS; i++) page[i] = *flash_hw(i); page[SETTINGS_BOOT_FLAG] = 1; + usb_pause(); if (write_page() && write_page()) flash_failed(); board_reset(); diff --git a/firmware/src/main.c b/firmware/src/main.c index 563896a..33e4be6 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -65,8 +65,17 @@ static void in_send_one(void) in_due &= (uint8_t)~IN_R1; in_next = IN_R36; } else { - shifter_report36(&sh, r); - usb_in_send(r, 64); + /* With anti-jitter on, every other 0x24 slot carries 0x26, so the + * host gets no more reports than usual. */ + static uint8_t raw_turn; + raw_turn = shifter_raw_wanted(&sh) && !raw_turn; + if (raw_turn) { + shifter_report_raw(&sh, r); + usb_in_send(r, 5); + } else { + shifter_report36(&sh, r); + usb_in_send(r, 64); + } in_due &= (uint8_t)~IN_R36; in_next = IN_R1; } @@ -90,6 +99,10 @@ unsigned usb_get_report(uint8_t report_id, uint8_t *out) shifter_report36(&sh, out); return 64; } + if (report_id == 0x26) { + shifter_report_raw(&sh, out); + return 5; + } return 0; } diff --git a/firmware/src/shifter.c b/firmware/src/shifter.c index 84263e3..6d9e971 100644 --- a/firmware/src/shifter.c +++ b/firmware/src/shifter.c @@ -324,7 +324,8 @@ void shifter_load(shifter_t *s, const uint16_t st[SH_SETTINGS_HALFWORDS]) s->g1_left_of_g3 = s->gear_x[0] < s->gear_x[2]; if (st[SH_ST_FLAGS] >> 8 == SH_ST_MARK) { - s->options = (uint8_t)(st[SH_ST_FLAGS] & (SH_OPT_LOGO | SH_OPT_RANGE_TOGGLE | SH_OPT_GAMMA | SH_OPT_NEUTRAL)); + s->options = (uint8_t)(st[SH_ST_FLAGS] & (SH_OPT_LOGO | SH_OPT_RANGE_TOGGLE | SH_OPT_GAMMA | SH_OPT_NEUTRAL | + SH_OPT_JITTER)); if (st[SH_ST_COLOR] <= 0xff && st[SH_ST_COLOR + 1] <= 0xff && st[SH_ST_COLOR + 2] <= 0xff) for (int i = 0; i < 3; i++) s->color[i] = (uint8_t)st[SH_ST_COLOR + i]; @@ -372,7 +373,92 @@ static int32_t proj(uint16_t s12, int32_t q30) return q30 < 0 ? -v : v; } -/* Sensor frame -> s12/s14/r/theta/x/y. */ +/* Anti-jitter (24 36) on the lever position: x, y and the sensor's z (s14), + * from which everything else follows (gears, sequential shifts, the + * handbrake axis, the reports, calibration). Each runs through a short + * running average, then holds still until the average moves more than a + * band from it. The band hides the sensor noise and a slightly shaky hand; + * going back the other way costs twice the band of free travel. If the + * average stays more than half a band away for JIT_SETTLE samples, the + * output moves to it once, so a still lever reads within half a band of + * where it is (noise does not stay on one side that long). A jump much + * larger than the noise passes at once, so quick moves are never late. A + * frame that jumps further than the lever can move in 2 ms is a bad read and + * is skipped; if the next frame agrees, it counts. + * Tuned on one unit: x and y have a noise of about 2 (sd) and z flickers by + * one step of its high byte (25 units of s14). */ +static const uint8_t jit_shift[4] = { 0, 1, 1, 2 }; +static const uint8_t jit_band[2][4] = { { 0, 4, 8, 16 }, /* x, y */ + { 0, 13, 16, 20 } }; /* z */ +static const uint8_t jit_jump[2] = { 150, 80 }; +#define JIT_SETTLE 64 /* 128 ms */ +static const uint16_t jit_bad[2] = { 600, 300 }; /* x or y, z: a bad read */ + +static int steady(shifter_t *s, unsigned ch, int v, unsigned lv) +{ + unsigned k = ch == 2; + uint32_t u = (uint32_t)(v + 32768) << 4; + int avg = (int)(s->jit_avg[ch] >> 4) - 32768; + int d = v - avg; + if (!s->jit_ready || d > jit_jump[k] || d < -jit_jump[k]) { + s->jit_avg[ch] = u; + s->jit_held[ch] = (int16_t)v; + s->jit_far[ch] = 0; + return v; + } + if (u >= s->jit_avg[ch]) + s->jit_avg[ch] += (u - s->jit_avg[ch]) >> jit_shift[lv]; + else + s->jit_avg[ch] -= (s->jit_avg[ch] - u) >> jit_shift[lv]; + avg = (int)(s->jit_avg[ch] >> 4) - 32768; + int b = jit_band[k][lv]; + if (avg > s->jit_held[ch] + b) + s->jit_held[ch] = (int16_t)(avg - b); + else if (avg < s->jit_held[ch] - b) + s->jit_held[ch] = (int16_t)(avg + b); + int off = avg - s->jit_held[ch]; + if (off > b / 2 || off < -(b / 2)) { + if (++s->jit_far[ch] >= JIT_SETTLE) { + s->jit_held[ch] = (int16_t)avg; + s->jit_far[ch] = 0; + } + } else { + s->jit_far[ch] = 0; + } + return s->jit_held[ch]; +} + +static void steady_position(shifter_t *s) +{ + unsigned lv = (s->options & SH_OPT_JITTER) >> SH_OPT_JITTER_SHIFT; + int16_t raw[3] = { s->x, s->y, s->s14 }; + int bad = 0; + for (unsigned ch = 0; ch < 3; ch++) { + int d = raw[ch] - s->jit_raw[ch]; + if (d > jit_bad[ch == 2] || d < -jit_bad[ch == 2]) + bad = 1; + s->jit_raw[ch] = raw[ch]; + } + if (!lv) + return; + if (bad && s->jit_ready && !s->jit_skipped) { + s->jit_skipped = 1; + s->x = s->jit_held[0]; + s->y = s->jit_held[1]; + s->s14 = s->jit_held[2]; + } else { + s->jit_skipped = 0; + s->x = (int16_t)steady(s, 0, raw[0], lv); + s->y = (int16_t)steady(s, 1, raw[1], lv); + s->s14 = (int16_t)steady(s, 2, raw[2], lv); + s->jit_ready = 1; + } + /* s12 to match: x and y are s12 * 6.55 along the lever's direction. */ + uint32_t h = sh_isqrt((uint32_t)((int32_t)s->x * s->x + (int32_t)s->y * s->y)); + s->s12 = (uint16_t)((h * 100u + 327u) / 655u); +} + +/* Sensor frame -> s12/s14/x/y/r/theta. */ static void sensor_math(shifter_t *s, const uint8_t f[8]) { s->raw_t = (uint16_t)(f[1] << 8 | f[2]); @@ -384,6 +470,22 @@ static void sensor_math(shifter_t *s, const uint8_t f[8]) s->s12 = (uint16_t)(((uint64_t)s->raw_y * S12_MUL) >> 32); s->s14 = (int16_t)(((int32_t)f[7] - 128) * 1280 / 51); + + /* x = r cos(theta) sin(phi) 6.55, y = r cos(theta) cos(phi) 6.55, + * r cos(theta) == s12. Truncation toward zero as in d2iz. */ + uint32_t ang = (uint32_t)(((uint64_t)s->raw_x * PHI_Q) >> 16); + int32_t sn, cs; + sh_sincos_q30(ang, &sn, &cs); + int32_t x = proj(s->s12, sn); + int32_t y = proj(s->s12, cs); + if (x < -5000 || x > 5000) + x = 0; + if (y < -5000 || y > 5000) + x = 0; /* sic: stock clears x, not y */ + s->x = (int16_t)x; + s->y = (int16_t)y; + steady_position(s); + s->r2 = (int32_t)s->s12 * s->s12 + (int32_t)s->s14 * s->s14; s->r = (uint16_t)sh_isqrt((uint32_t)s->r2); s->rf = sf_sqrt_int((uint32_t)s->r2); @@ -399,20 +501,6 @@ static void sensor_math(shifter_t *s, const uint8_t f[8]) s->theta_lt = lhs < rhs; s->theta_le = lhs <= rhs; } - - /* x = r cos(theta) sin(phi) 6.55, y = r cos(theta) cos(phi) 6.55, - * r cos(theta) == s12. Truncation toward zero as in d2iz. */ - uint32_t ang = (uint32_t)(((uint64_t)s->raw_x * PHI_Q) >> 16); - int32_t sn, cs; - sh_sincos_q30(ang, &sn, &cs); - int32_t x = proj(s->s12, sn); - int32_t y = proj(s->s12, cs); - if (x < -5000 || x > 5000) - x = 0; - if (y < -5000 || y > 5000) - x = 0; /* sic: stock clears x, not y */ - s->x = (int16_t)x; - s->y = (int16_t)y; if (s->ref_r < s->rf) /* non-negative floats order like their bits */ s->ref_r = s->rf; } @@ -666,6 +754,7 @@ int shifter_sensor_frame(shifter_t *s, const uint8_t f[8]) for (int i = 1; i < 8; i++) any |= f[i]; if (!any) { + s->jit_ready = 0; if (s->empty_frames < 255) s->empty_frames++; res = s->empty_frames >= 100 ? SH_FRAME_POWER_OFF : SH_FRAME_EMPTY; @@ -860,6 +949,12 @@ unsigned shifter_command(shifter_t *s, const uint8_t *buf, unsigned len) return 0; s->options = (uint8_t)((s->options & ~SH_OPT_NEUTRAL) | (b[2] ? SH_OPT_NEUTRAL : 0)); return SH_ACT_SAVE; + case 0x36: /* anti-jitter level for the lever position, 0 to 3; saved */ + if (b[2] > 3) + return 0; + s->options = (uint8_t)((s->options & ~SH_OPT_JITTER) | b[2] << SH_OPT_JITTER_SHIFT); + s->jit_ready = 0; + return SH_ACT_SAVE; case 0x3f: /* light only chain position 0..2 in white; 0xFF ends */ if (b[2] > 2 && b[2] != 0xff) return 0; @@ -921,6 +1016,21 @@ void shifter_report36(const shifter_t *s, uint8_t out[64]) out[63] = s->mode; } +/* Input report 0x26: the lever's x and y as read, before anti-jitter, so a + * host can show what anti-jitter removes. Sent only while anti-jitter is on; + * with it off, report 0x24 already has the raw reading. */ +int shifter_raw_wanted(const shifter_t *s) +{ + return (s->options & SH_OPT_JITTER) != 0; +} + +void shifter_report_raw(const shifter_t *s, uint8_t out[5]) +{ + out[0] = 0x26; + be16(&out[1], s->jit_raw[0]); + be16(&out[3], s->jit_raw[1]); +} + void shifter_uart_packet(const shifter_t *s, uint8_t out[16]) { for (int i = 0; i < 16; i++) diff --git a/firmware/src/shifter.h b/firmware/src/shifter.h index 3e1e079..a2d5ed1 100644 --- a/firmware/src/shifter.h +++ b/firmware/src/shifter.h @@ -33,6 +33,8 @@ #define SH_OPT_RANGE_TOGGLE 0x02u /* high/low button latches */ #define SH_OPT_GAMMA 0x08u /* gamma 2.2 on the LED output */ #define SH_OPT_NEUTRAL 0x10u /* HID button 1 held in H-pattern neutral */ +#define SH_OPT_JITTER 0x60u /* anti-jitter level 0 to 3 on the lever position */ +#define SH_OPT_JITTER_SHIFT 5 /* Default LED colour and white balance (a gain per channel, 255 = full), * both set by eye on a unit. Its blue and green LEDs are much brighter than @@ -137,6 +139,12 @@ typedef struct { uint8_t gear_gap; /* samples left of the neutral between two gears */ uint8_t led_test; /* chain position lit white by 24 3F, 0xFF = off */ uint8_t booting; /* 24 00 received: all LEDs yellow */ + uint8_t jit_ready; /* jit_avg and jit_held follow the lever */ + int16_t jit_held[3]; /* anti-jitter output for x, y, s14, held inside a band */ + uint32_t jit_avg[3]; /* running averages of x, y, s14, each + 32768, Q4 */ + uint8_t jit_far[3]; /* samples the average has stayed over half a band away */ + int16_t jit_raw[3]; /* x, y, s14 as last read: report 0x26, and to spot a bad read */ + uint8_t jit_skipped; /* the last frame was skipped as a bad read */ } shifter_t; void shifter_init(shifter_t *s); @@ -157,6 +165,9 @@ unsigned shifter_command(shifter_t *s, const uint8_t *buf, unsigned len); void shifter_report1(const shifter_t *s, uint8_t out[5]); void shifter_report36(const shifter_t *s, uint8_t out[64]); +void shifter_report_raw(const shifter_t *s, uint8_t out[5]); +/* 1 while report 0x26 is sent: whenever anti-jitter is on. */ +int shifter_raw_wanted(const shifter_t *s); void shifter_uart_packet(const shifter_t *s, uint8_t out[16]); /* Wire order G,R,B for the three WS2812 LEDs, in chain order; all zero when * asleep. */ diff --git a/firmware/src/usb.c b/firmware/src/usb.c index eb0388b..a908e04 100644 --- a/firmware/src/usb.c +++ b/firmware/src/usb.c @@ -34,7 +34,7 @@ const uint8_t usb_device_desc[18] = { * Button 1 is report bit 12, the neutral button (off unless turned on with * 24 35 1). Linux (joydev, SDL) numbers buttons from 0 in usage order, so * gear 1 is button 1 there; Windows numbers from 1, where gear 1 is button 2. */ -const uint8_t usb_report_desc[89] = { +const uint8_t usb_report_desc[97] = { 0x05, 0x01, /* Usage Page (Generic Desktop) */ 0x09, 0x04, /* Usage (Joystick) */ 0xa1, 0x01, /* Collection (Application) */ @@ -67,6 +67,10 @@ const uint8_t usb_report_desc[89] = { 0x09, 0x02, /* Usage (2) */ 0x95, 0x0f, /* 15 x 8 bits */ 0xb1, 0x02, /* Feature (Data, Var, Abs): version */ + 0x85, 0x26, /* Report ID 0x26 */ + 0x09, 0x03, /* Usage (3) */ + 0x95, 0x04, /* 4 x 8 bits */ + 0x81, 0x02, /* Input (Data, Var, Abs): raw lever x, y */ 0xc0, /* End Collection */ }; @@ -111,6 +115,7 @@ static const struct { const char *s; uint8_t n; } usb_strings[] = { #define EP_CTR_TX 0x0080u #define EP_CONTROL 0x0200u #define EP_INTERRUPT 0x0600u +#define STAT_DISABLED 0u #define STAT_STALL 1u #define STAT_NAK 2u #define STAT_VALID 3u @@ -604,6 +609,39 @@ void usb_reconnect(void) delay_ms(STOCK_MS(200)); } +/* Settings writes. A unit froze when the host sent control requests during + * a flash erase, even with interrupts off: the erase never finished. While + * the flash is busy, EP0 ignores everything (the host sees a failed request) + * and EP1 answers NAK (the host tries again later). */ +static uint8_t paused_stat[3]; + +void usb_pause(void) +{ + if (!(RCC_APB1ENR & APB1_USB)) + return; + uint32_t r0 = USB_EPR(0), r1 = USB_EPR(1); + paused_stat[0] = (uint8_t)((r0 >> 4 & 3) | (r0 >> 12 & 3) << 2); + paused_stat[1] = (uint8_t)((r1 >> 4 & 3) | (r1 >> 12 & 3) << 2); + paused_stat[2] = 1; + ep_stat_tx(0, STAT_DISABLED); + ep_stat_rx(0, STAT_DISABLED); + if (paused_stat[1] & 3) + ep_stat_tx(1, STAT_NAK); + if (paused_stat[1] >> 2 & 3) + ep_stat_rx(1, STAT_NAK); +} + +void usb_unpause(void) +{ + if (!paused_stat[2]) + return; + paused_stat[2] = 0; + ep_stat_tx(0, paused_stat[0] & 3); + ep_stat_rx(0, paused_stat[0] >> 2 & 3); + ep_stat_tx(1, paused_stat[1] & 3); + ep_stat_rx(1, paused_stat[1] >> 2 & 3); +} + void usb_detach(void) { USB_AIR_DPPU = 0; diff --git a/firmware/src/usb.h b/firmware/src/usb.h index d50003a..84576c8 100644 --- a/firmware/src/usb.h +++ b/firmware/src/usb.h @@ -15,6 +15,9 @@ extern volatile uint16_t usb_reset_count; void usb_reconnect(void); /* Drop off the bus and stay off. */ void usb_detach(void); +/* Around a flash erase or write: EP0 ignores the host, EP1 answers NAK. */ +void usb_pause(void); +void usb_unpause(void); void usb_init(void); void usb_irq_handler(void); @@ -31,6 +34,6 @@ unsigned usb_get_report(uint8_t report_id, uint8_t *out); /* Exposed for tests. */ extern const uint8_t usb_device_desc[18]; extern const uint8_t usb_config_desc[41]; -extern const uint8_t usb_report_desc[89]; +extern const uint8_t usb_report_desc[97]; #endif diff --git a/tests/emu/harness.py b/tests/emu/harness.py index dacf37a..24f4bc7 100644 --- a/tests/emu/harness.py +++ b/tests/emu/harness.py @@ -34,9 +34,10 @@ def stock_image(): class Rig: """One powered shifter on a simulated USB host.""" - def __init__(self, image, settings=None, *, h_pattern=False, enumerate=True, pos=(0, 0, 0x80)): + def __init__(self, image, settings=None, *, h_pattern=False, enumerate=True, pos=(0, 0, 0x80), flash_busy=True): self.image = image - self.m = Machine(image, settings) + self.flash_busy = flash_busy + self.m = Machine(image, settings, flash_busy=flash_busy) self.m.buttons['PB10'] = h_pattern self.m.host.auto_enumerate = enumerate self.m.set_position(*pos) @@ -127,4 +128,5 @@ def settings_page(self, n=2048): def reboot(self, **kw): """Power-cycle with the flash contents this unit has written.""" + kw.setdefault('flash_busy', self.flash_busy) return type(self)(self.image, self.settings_page(), **kw) diff --git a/tests/emu/stm32emu.py b/tests/emu/stm32emu.py index b631fab..25a1446 100644 --- a/tests/emu/stm32emu.py +++ b/tests/emu/stm32emu.py @@ -32,6 +32,8 @@ FLASH_SIZE = 0x20000 APP_BASE = 0x08010000 SETTINGS_ADDR = 0x0800F000 +FLASH_ERASE_US = 20_000 # page erase, STM32F103 typical +FLASH_PROGRAM_US = 50 # one halfword RAM_BASE = 0x20000000 RAM_SIZE = 0x10000 SYSMEM_BASE = 0x1FFFF000 @@ -296,6 +298,12 @@ def _set_stat_tx(self, n, s): self.epr[n] = (self.epr[n] & ~EP_STAT_TX) | s << 4 # host tokens + def _check_flash_idle(self, *what): + """A unit froze when it took control requests during a flash erase.""" + m = self.m + if m.time_us < m.flash_busy_until: + m.flash_violations.append(('USB packet while flash busy',) + what) + def addressed(self, addr): return (self.daddr & 0x80) and (self.daddr & 0x7F) == addr @@ -305,6 +313,7 @@ def setup(self, addr, data): n = self.find_ep(0) if (self.epr[n] & EP_TYPE) != 0x0200 or self._stat(n, 12) == STAT_DISABLED: return 'TIMEOUT' + self._check_flash_idle('setup') self.buf_write(self.bt(n, 2), data) self.bt_set(n, 3, (self.bt(n, 3) & 0xFC00) | len(data)) self.epr[n] |= EP_CTR_RX | EP_SETUP @@ -321,6 +330,7 @@ def in_token(self, addr, ep): return 'TIMEOUT' s = self._stat(n, 4) if s == STAT_VALID: + self._check_flash_idle('in', ep) cnt = self.bt(n, 1) & 0x3FF data = self.buf_read(self.bt(n, 0), cnt) self._set_stat_tx(n, STAT_NAK) @@ -338,6 +348,7 @@ def out_token(self, addr, ep, data): return 'TIMEOUT' s = self._stat(n, 12) if s == STAT_VALID: + self._check_flash_idle('out', ep) c = self.bt(n, 3) size = ((c >> 10) & 0x1F) * 2 if not c & 0x8000 else (((c >> 10) & 0x1F) + 1) * 32 if len(data) > size: @@ -545,7 +556,7 @@ def g(): class Machine: def __init__(self, image, settings=None, *, mips=24, slice_us=20, page_size=2048, - hse=True, profile=None, uid_top=0x1C): + hse=True, profile=None, uid_top=0x1C, flash_busy=True): self.profile = dict(profile or {}) self.mips = mips self.slice_us = slice_us @@ -584,6 +595,12 @@ def __init__(self, image, settings=None, *, mips=24, slice_us=20, page_size=2048 self.flash_events = [] self.flash_violations = [] self.flash_worn = False # True: the settings page refuses every erase and program + # FPEC busy until this time (us). On the AIR32 an interrupt taken while + # the flash is busy can fetch code the flash cannot give it and lock + # the bus (seen on a unit: a GET_REPORT during a settings write froze + # it), so taking one then is a flash violation. + self.flash_busy_until = 0 + self.flash_busy = flash_busy # False: erases and writes take no time self.sensor = Sensor() self.buttons = {'PA4': False, 'PA5': False, 'PB10': False} self.usb = UsbDevice(self) @@ -650,6 +667,8 @@ def _flash_write_hook(self, uc, access, addr, size, value, ud): else: self.flash_events.append(('program', addr, value)) self.regs[0x4002200C] |= 0x20 + if self.flash_busy: + self.flash_busy_until = self.time_us + FLASH_PROGRAM_US def _flash_ctrl_write(self, a, v): if a == 0x40022004: # KEYR @@ -680,6 +699,8 @@ def _flash_ctrl_write(self, a, v): self.uc.mem_write(page, b'\xff' * self.page_size) self.flash_events.append(('erase', page)) self.regs[0x4002200C] |= 0x20 + if self.flash_busy: + self.flash_busy_until = self.time_us + FLASH_ERASE_US self.regs[a] &= ~0x40 if v & 0x40 and v & 0x4: self.flash_violations.append(('mass-erase',)) @@ -785,6 +806,8 @@ def _p_read(self, uc, off, size, ud): v = self._idr('A' if wa == 0x40010808 else 'B') elif wa == 0x40013800: v = 0xC0 # TXE | TC + elif wa == 0x4002200C: + v = self.regs[wa] | (1 if self.time_us < self.flash_busy_until else 0) # BSY else: v = self.regs[wa] return (v >> sh) & ((1 << (8 * size)) - 1) @@ -1000,6 +1023,8 @@ def _take_exception(self): if best is None: return False exc = best[1] + if self.time_us < self.flash_busy_until: + self.flash_violations.append(('interrupt while flash busy', exc)) self.pending.discard(exc) uc = self.uc saved = [uc.reg_read(r) for r in SAVED_REGS] diff --git a/tests/test_ctl.py b/tests/test_ctl.py index 785e48d..da8e5d5 100644 --- a/tests/test_ctl.py +++ b/tests/test_ctl.py @@ -222,6 +222,23 @@ def test_neutral(self): self.assertEqual(rc, 2) self.assertIn('0.5.0 or newer', err) + def test_anti_jitter(self): + new = Bus('OpenShifter 0.6.0') + rc, out, err = self.run_ctl('status', bus=new) + self.assertEqual(rc, 0, err) + self.assertIn('anti-jitter none', out) + self.assertNotIn('anti-jitter', self.run_ctl('status', bus=Bus('OpenShifter 0.5.0'))[1]) + for level, bits in (('high', 0x60), ('low', 0x20), ('medium', 0x40), ('none', 0)): + rc, out, err = self.run_ctl('anti-jitter', level, bus=new) + self.assertEqual(rc, 0, err) + self.assertIn(f'anti-jitter {level} (saved)', out) + self.assertEqual(self.dev.settings()[0x50] & 0x60, bits, level) + self.run_ctl('anti-jitter', 'medium', bus=new) + self.assertIn('anti-jitter medium', self.run_ctl('status', bus=new)[1]) + rc, _, err = self.run_ctl('anti-jitter', 'low', bus=Bus('OpenShifter 0.5.0')) + self.assertEqual(rc, 2) + self.assertIn('0.6.0 or newer', err) + def test_guided_balance(self): rc, out, err = self.run_ctl('balance', steps=['b -40', 'g+4', 'r 300', 'x', '']) self.assertEqual(rc, 0, err) diff --git a/tests/test_emulated.py b/tests/test_emulated.py index 7f20145..e03d2c2 100644 --- a/tests/test_emulated.py +++ b/tests/test_emulated.py @@ -11,6 +11,7 @@ with the expected SHA-256. """ import pathlib +import random import sys import unittest @@ -103,8 +104,9 @@ def bits(kind, report): self.assertEqual(bits('input', 0x24), 8 * 63) self.assertEqual(bits('output', 0x24), 8 * 63) self.assertEqual(bits('feature', 0x25), 8 * 15) + self.assertEqual(bits('input', 0x26), 8 * 4) self.assertEqual({(f['kind'], f['report']) for f in fields}, - {('input', 1), ('input', 0x24), ('output', 0x24), ('feature', 0x25)}) + {('input', 1), ('input', 0x24), ('output', 0x24), ('feature', 0x25), ('input', 0x26)}) data = [f for f in fields if not f['const']] buttons = [u for f in data for u in f['usages'] if u >> 16 == 0x09] @@ -112,7 +114,7 @@ def bits(kind, report): self.assertEqual(buttons, [0x00090000 | n for n in [*range(2, 14), 1]], 'one usage per button bit') for f in data: self.assertEqual(f['application'], 0x00010004) - if f['report'] in (0x24, 0x25): + if f['report'] in (0x24, 0x25, 0x26): self.assertEqual({u >> 16 for u in f['usages']}, {0xFF00}) else: self.assertEqual(len(set(f['usages'])), f['count'], 'repeated usage') @@ -215,6 +217,7 @@ def test_both_reports_flow_when_the_host_polls_slowly(self): # queued them, and a host polling every 2 ms got only report 1. for miss, least in ((lambda n: n % 7 == 0, 350), (lambda n: n % 2 == 0, 200)): r = Rig(openshifter_image()).boot() + r.run(SETTLE_MS) # past the first settings write (see the next test) r.m.host.miss = miss n = len(r.m.host.in_reports) r.run(1000) @@ -260,6 +263,108 @@ 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_anti_jitter_steadies_the_lever(self): + """24 36: a lever held still with sensor noise, at level 0 and 3, in + H and in handbrake mode; a full pull is not held back; the level is + kept after a power cycle.""" + def changes(r, level, x0, y0): + r.command(0x24, 0x36, level) + rng = random.Random(3) + t0 = r.m.time_us + for _ in range(150): + r.m.set_position(x0 + rng.randint(-3, 3), y0 + rng.randint(-3, 3)) + r.m.run(ms=2) + late = [(t, p) for t, p in r.m.host.in_reports if t > t0 + 60_000] + axis = [p[3] | p[4] << 8 for t, p in late if p[0] == 0x01] + pos = [bytes(p[2:6]) for t, p in late if p[0] == 0x24] + self.assertGreater(min(len(axis), len(pos)), 40) # 0x24 at half rate with anti-jitter on + n = lambda v: sum(a != b for a, b in zip(v, v[1:])) # noqa: E731 + return n(pos), n(axis), axis[-1] + + r = Rig(openshifter_image(), h_pattern=True).boot() + calibrate(r) + raw_xy, _, _ = changes(r, 0, 120, -280) + steady_xy, _, _ = changes(r, 3, 120, -280) + self.assertGreater(raw_xy, 30, 'raw x and y follow the noise') + self.assertEqual(steady_xy, 0, 'x and y hold still in H') + r.press('PB10', hold=False, ms=200) + r.press('PA5', ms=100) + r.press('PA5', hold=False, ms=100) + self.assertEqual(r.last(0x24)[63], 2, 'handbrake mode') + _, raw, raw_end = changes(r, 0, -150, -850) + _, steady, steady_end = changes(r, 3, -150, -850) + self.assertGreater(raw, 30, 'the raw axis follows the noise') + self.assertEqual(steady, 0) + self.assertLess(abs(steady_end - raw_end), 2000, 'about the same position') + # Report 0x26 carries the raw reading. + t0 = r.m.time_us + rng = random.Random(4) + for _ in range(100): + r.m.set_position(-150 + rng.randint(-3, 3), -850 + rng.randint(-3, 3)) + r.m.run(ms=2) + late = [p for t, p in r.m.host.in_reports if t > t0 + 20_000] + raw = {int.from_bytes(p[3:5], 'big', signed=True) for p in late if p[0] == 0x26} + shown = {bytes(p[2:6]) for p in late if p[0] == 0x24} + self.assertGreater(len(raw), 2, 'report 0x26 follows the noise') + self.assertEqual(len(shown), 1, 'report 0x24 holds still') + r.move(-150, -1700, ms=20) + self.assertEqual(r.last(0x01)[3:5], b'\xff\xff', 'a full pull is not held back') + r.run(SETTLE_MS) + self.assertFlashClean(r) + r = r.reboot().boot() + self.assertEqual(r.last(0x24)[23] >> 5 & 3, 3, 'kept after a restart') + + def test_control_requests_during_a_settings_write(self): + """What froze a unit: control requests every 15 ms (a test build of the + web tool read a feature report that often) while a setting was being + written. While the flash is busy the unit takes no USB packet and no + interrupt (assertFlashClean), so a request then fails; all others are + answered, and the setting lands.""" + r = Rig(openshifter_image(), h_pattern=True).boot() + r.run(SETTLE_MS) + n = erases(r) + r.command(0x24, 0x36, 2, ms=0) + failed = 0 + for _ in range(110): + rep = r.control(0xA1, 0x01, 0x0124, 0, 64) + if isinstance(rep, str): + failed += 1 + else: + self.assertEqual(rep[0], 0x24) + r.m.run(ms=13) + self.assertLessEqual(failed, 2, 'only requests during the write fail') + self.assertEqual(erases(r), n + 1) + self.assertEqual(r.m.settings()[0x50] & 0x60, 0x40) + # Reports pause for the write, and only that long. + times = [t for t, rep in r.m.host.in_reports if rep[0] == 0x01] + self.assertLess(max(b - a for a, b in zip(times, times[1:])), 40_000) + self.assertFlashClean(r) + + def test_raw_report_only_with_anti_jitter(self): + """With anti-jitter on, report 0x26 takes every other report 0x24 + slot, so the host gets no more reports than usual. With it off, there + is no report 0x26: report 0x24 already has the raw reading.""" + def counts(r, ms): + n = len(r.m.host.in_reports) + r.run(ms) + ids = [p[0] for _, p in r.m.host.in_reports[n:]] + return {k: ids.count(k) for k in (0x01, 0x24, 0x26)} + + r = Rig(openshifter_image()).boot() + r.run(SETTLE_MS) # past the first settings write, which pauses reports + before = counts(r, 400) + self.assertEqual(before[0x26], 0) + r.command(0x24, 0x36, 1, ms=50) + during = counts(r, 400) + self.assertGreater(during[0x26], 80) + self.assertGreater(during[0x24], 80) + self.assertAlmostEqual(during[0x01], before[0x01], delta=4) + self.assertAlmostEqual(during[0x24] + during[0x26], before[0x24], delta=4) + rep = [p for _, p in r.m.host.in_reports if p[0] == 0x26][-1] + self.assertEqual(len(rep), 5) + r.command(0x24, 0x36, 0, ms=20) + self.assertEqual(counts(r, 300)[0x26], 0, 'none: no report 0x26') + def test_settings_are_written_once_they_stop_changing(self): r = Rig(openshifter_image(), h_pattern=True).boot() r.run(SETTLE_MS) @@ -327,7 +432,7 @@ def as_stock_page(): '05010904a1018501 0509 1902290d 15002501 7501950c 8102 0901 9501 8102 9503 8103' '0501 0932 150027ffff0000 350047ffff0000 75109501 8102' '8524 0600ff 0901 150026ff00 7508953f 8102 0901 9102' - '8525 0902 950f b102 c0') + '8525 0902 950f b102 8526 0903 9504 8102 c0') def as_stock_descriptor(d): @@ -434,6 +539,9 @@ def rig(img): cls = Rig if img is stock else StockView def make(image, settings=None, **kw): + # Instant flash: stock's writes take about 70 ms and shift + # its timing against OpenShifter's; these tests compare logic. + kw.setdefault('flash_busy', False) return cls(image, as_stock_page() if settings is None else settings, **kw) return make stock, ours = stock_image(), openshifter_image() diff --git a/tests/test_shifter.py b/tests/test_shifter.py index 74aa590..76b2945 100644 --- a/tests/test_shifter.py +++ b/tests/test_shifter.py @@ -68,6 +68,8 @@ def setUpModule(): ('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_report_raw', None, [ctypes.c_void_p, ctypes.c_char_p]), + ('shifter_raw_wanted', i32, [ctypes.c_void_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]), @@ -521,6 +523,235 @@ def test_led_identify_and_update(self): self.assertEqual(self.leds(s), [led(255, 255, 0)] * 3) +class AntiJitter(CoreHelpers, unittest.TestCase): + """24 36: anti-jitter on the lever position, at each level.""" + + def calibrated(self, level): + """A calibrated unit (rest y 0, pulled y -1500) in H, at `level`.""" + s = self.new() + lib.shifter_buttons(s, 1, 0, 0) + self.feed(s, 0, 0) + self.cmd(s, 0x24, 0x21, 9) + self.feed(s, -300, -1500) + self.cmd(s, 0x24, 0x21, 10) + for k, (x, y, z) in enumerate(GEARS, 1): + self.feed(s, x, y, z) + self.cmd(s, 0x24, 0x21, k) + st = (ctypes.c_uint16 * 100)(*[0xFFFF] * 100) + lib.shifter_save(s, st) + s = self.new(list(st)) + lib.shifter_buttons(s, 1, 0, 0) + self.assertEqual(self.cmd(s, 0x24, 0x36, level), SH_ACT_SAVE) + return s + + def to_handbrake_mode(self, s): + for b in (0, 1, 1, 0): + lib.shifter_buttons(s, 0, b, 0) + self.assertEqual(self.report36(s)[63], 2) + + def report36(self, s): + out = ctypes.create_string_buffer(64) + lib.shifter_report36(s, out) + return out.raw + + def axis(self, s): + r = self.report1(s) + return r[3] | r[4] << 8 + + def run_frames(self, s, poses): + """Feeds (x, y, z) frames; returns (gears, axis, x, y, r/8) after each.""" + out = [] + for x, y, z in poses: + lib.shifter_sensor_frame(s, frame(x, y, z)) + r1, r36 = self.report1(s), self.report36(s) + out.append((r1[1], r1[3] | r1[4] << 8, struct.unpack('>hh', r36[2:6]), r36[48])) + return out + + @staticmethod + def changes(rows, i): + return sum(a[i] != b[i] for a, b in zip(rows, rows[1:])) + + def test_command_and_storage(self): + s = self.new() + for level in range(4): + self.assertEqual(self.cmd(s, 0x24, 0x36, level), SH_ACT_SAVE) + self.assertEqual(self.report36(s)[23], 0x80 | level << 5) + self.assertEqual(self.cmd(s, 0x24, 0x36, 4), 0) + self.assertEqual(self.report36(s)[23] >> 5 & 3, 3, 'a bad level changes nothing') + st = (ctypes.c_uint16 * 100)(*[0xFFFF] * 100) + lib.shifter_save(s, st) + self.assertEqual(st[0x50], 0xA560) + self.assertEqual(self.report36(self.new(list(st)))[23], 0xE0, 'kept after a restart') + self.assertEqual(self.report36(self.new())[23], 0x80, 'none by default') + + def test_lever_position_holds_still(self): + rng = random.Random(7) + poses = {'neutral': (120, -280), 'gear 3': (60, 3150), 'handbrake': (-150, -850)} + for name, (x0, y0) in poses.items(): + noise = [(x0 + rng.randint(-3, 3), y0 + rng.randint(-3, 3), 0x80 + rng.randint(0, 1)) + for _ in range(600)] + for level in range(4): + s = self.calibrated(level) + if name == 'handbrake': + self.to_handbrake_mode(s) + rows = self.run_frames(s, noise)[100:] + moved = [self.changes(rows, i) for i in (1, 2, 3)] # axis, x/y, r + if level == 0: + self.assertGreater(moved[1], 100, f'{name}: the raw x/y follow the noise') + if name == 'neutral': # where z decides the field strength + self.assertGreater(moved[2], 50, f'{name}: the raw r follows z') + else: + # Low may still step once in a while near neutral, where + # x and y are noisiest; never back and forth. + allowed = 3 if level == 1 else 0 + self.assertLessEqual(max(moved), allowed, f'{name} at level {level}: {moved}') + self.assertEqual(self.changes(rows, 0), 0, f'{name}: gears at level {level}') + + def test_gear_7_does_not_chatter(self): + """Gear 7 is held while its field strength stays under a limit, and + that strength steps with z. With the lever right at the limit and z + flipping between the steps on either side of it, the raw reading + keeps dropping and taking the gear. Anti-jitter settles on one side + and stays there.""" + rng = random.Random(11) + x, y, _ = GEARS[6] + poses = [(x, y, rng.choice((0x6E, 0x6F))) for _ in range(1500)] + for level in range(4): + s = self.calibrated(level) + self.run_frames(s, [GEARS[6]] * 40) + self.assertEqual(self.report1(s)[1], 0x40) + flips = self.changes(self.run_frames(s, poses), 0) + if level == 0: + self.assertGreater(flips, 4, 'the raw reading chatters') + else: + self.assertLessEqual(flips, 1, level) + + def test_quick_moves_are_not_late(self): + """Shifts and a yanked handbrake: every level gives the same reports + at the same samples as none.""" + def path(steps, *points): + out = [] + for (x0, y0, z0), (x1, y1, z1) in zip(points, points[1:]): + out += [(round(x0 + (x1 - x0) * i / steps), round(y0 + (y1 - y0) * i / steps), z1 if i else z0) + for i in range(steps)] + [(x1, y1, z1)] * 30 + return out + n = (0, 0, 0x80) + shifts = path(8, n, GEARS[0], n, GEARS[2], GEARS[3], n, GEARS[5], n) + yank = path(10, n, (-150, -1700, 0x80), n, (-150, -1700, 0x80), n) + ref = None + for level in range(4): + s = self.calibrated(level) + got = [r[0] for r in self.run_frames(s, shifts)] + self.to_handbrake_mode(s) + got += [r[1] for r in self.run_frames(s, yank)] + ref = ref or got + self.assertEqual(got, ref, level) + self.assertIn(65535, ref) + + def test_follows_slow_moves(self): + span = 1100 # axis from rest - 300 (-300) to pulled + 100 (-1400) + ramp = [round(-300 - 1100 * i / 300) for i in range(300)] + [-1400] * 100 + back = [round(-1400 + 900 * i / 200) for i in range(200)] + [-500] * 100 + poses = [(-150, y, 0x80) for y in ramp + back] + s = self.calibrated(0) + self.to_handbrake_mode(s) + ref = [r[1] for r in self.run_frames(s, poses)] + speed = 4.5 # y per sample, the faster of the two moves + for level, band, shift in ((1, 4, 1), (2, 8, 1), (3, 16, 2)): + s = self.calibrated(level) + self.to_handbrake_mode(s) + out = [r[1] for r in self.run_frames(s, poses)] + worst = max(abs(a - b) for a, b in zip(out, ref)) + # The band's free travel when the lever turns round, plus the + # running average's lag. + limit = 2 * band + (2 ** shift - 1) * speed + 2 + self.assertLess(worst, limit * 65535 / span, level) + # Where the lever stopped: within the band (frame() rounds y by 1 or 2). + for at in (399, len(out) - 1): + self.assertLessEqual(abs(out[at] - ref[at]), (band + 2) * 65535 / span, (level, at)) + + def test_calibration_with_noise(self): + """Calibrated at high with a noisy sensor, every gear is found.""" + rng = random.Random(5) + def noisy(x, y, z, n=60): + return [(x + rng.randint(-3, 3), y + rng.randint(-3, 3), z + rng.randint(0, 1)) for _ in range(n)] + s = self.new() + lib.shifter_buttons(s, 1, 0, 0) + self.cmd(s, 0x24, 0x36, 3) + self.run_frames(s, noisy(0, 0, 0x80)) + self.cmd(s, 0x24, 0x21, 9) + self.run_frames(s, noisy(-300, -1500, 0x80)) + self.cmd(s, 0x24, 0x21, 10) + for k, (x, y, z) in enumerate(GEARS, 1): + self.run_frames(s, noisy(x, y, z)) + self.cmd(s, 0x24, 0x21, k) + st = (ctypes.c_uint16 * 100)(*[0xFFFF] * 100) + lib.shifter_save(s, st) + s = self.new(list(st)) + lib.shifter_buttons(s, 1, 0, 0) + self.run_frames(s, noisy(0, 0, 0x80)) + for k, (x, y, z) in enumerate(GEARS, 1): + rows = self.run_frames(s, noisy(x + 120, y - 90, z, n=150)) + self.assertEqual(rows[-1][0], 1 << (k - 1), f'gear {k}') + self.run_frames(s, noisy(0, 0, 0x80)) + self.assertEqual(self.report1(s)[1], 0, f'neutral after gear {k}') + + def test_raw_report(self): + """Report 0x26 gives the reading before anti-jitter, at every level, + and is sent while anti-jitter is on.""" + s = self.new() + for level, wanted in ((0, 0), (1, 1), (3, 1), (0, 0)): + self.cmd(s, 0x24, 0x36, level) + self.assertEqual(bool(lib.shifter_raw_wanted(s)), bool(wanted), level) + for level in range(4): + s = self.calibrated(level) + self.run_frames(s, [(120, -280, 0x80)] * 40) + rows = self.run_frames(s, [(126, -274, 0x80)]) + out = ctypes.create_string_buffer(5) + lib.shifter_report_raw(s, out) + x, y = struct.unpack('>hh', out.raw[1:5]) + self.assertEqual(out.raw[0], 0x26) + self.assertLessEqual(abs(x - 126) + abs(y + 274), 4, level) # frame() rounds by 1 or 2 + if level >= 2: + self.assertNotEqual(rows[0][2], (x, y), 'report 0x24 holds still') + + def test_a_bad_read_is_skipped(self): + """One frame far from the last (seen on a unit: y 6598 at rest) moves + nothing with anti-jitter on. Two in a row are a real jump: the second + counts, one frame later than with none.""" + hold = [(-150, -850, 0x80)] * 60 + bad = [(1800, -3200, 0x80)] + for level in range(4): + s = self.calibrated(level) + self.to_handbrake_mode(s) + before = self.run_frames(s, hold)[-1] + spike = self.run_frames(s, bad)[0] + after = self.run_frames(s, hold[:5]) + if level == 0: + self.assertNotEqual(spike[2], before[2], 'none passes the bad read') + else: + self.assertEqual((spike[1], spike[2]), (before[1], before[2]), level) + self.assertEqual([r[1:3] for r in after], [before[1:3]] * 5, level) + s = self.calibrated(level) + self.to_handbrake_mode(s) + self.run_frames(s, hold) + jump = [r[1] for r in self.run_frames(s, [(-150, -1700, 0x80)] * 6)] + full = jump.index(65535) + ref = ref_full if level else full + if not level: + ref_full = full + self.assertLessEqual(full, ref + 1, f'level {level}: one frame later at most') + + def test_starts_over_after_the_sensor_restarts(self): + s, ref = self.calibrated(3), self.calibrated(0) + for t in (s, ref): + self.run_frames(t, [(100, -300, 0x80)] * 50) + for _ in range(120): + lib.shifter_sensor_frame(t, bytes(8)) + self.assertEqual(self.run_frames(s, [(110, -310, 0x80)])[0][2], + self.run_frames(ref, [(110, -310, 0x80)])[0][2], 'no value left from before') + + class Saves(ctypes.Structure): _fields_ = [('changed_ms', ctypes.c_uint32), ('refill_ms', ctypes.c_uint32), ('pending', ctypes.c_uint8), ('allowance', ctypes.c_uint8)] diff --git a/tools/openshifter_ctl.py b/tools/openshifter_ctl.py index bc66931..3d23994 100755 --- a/tools/openshifter_ctl.py +++ b/tools/openshifter_ctl.py @@ -7,7 +7,7 @@ to confirm each change. Settings are saved on the shifter. Status and calibration also work with the stock firmware; the LED and button settings need OpenShifter 0.2.0 or newer, white balance and gamma 0.3.0 or newer, the -neutral button 0.5.0 or newer. +neutral button 0.5.0 or newer, anti-jitter 0.6.0 or newer. Access to /dev/hidraw* needs root or the udev rule printed by `openshifter_flash.py udev-rule`. @@ -31,6 +31,7 @@ CMD_BALANCE = 0x33 CMD_GAMMA = 0x34 CMD_NEUTRAL = 0x35 +CMD_JITTER = 0x36 CMD_LED_TEST = 0x3F OPT_LOGO = 0x01 @@ -38,11 +39,13 @@ OPT_RANGE_ON = 0x04 OPT_GAMMA = 0x08 OPT_NEUTRAL = 0x10 +OPT_JITTER = 0x60 # anti-jitter level in bits 5-6 OPT_PRESENT = 0x80 DEFAULT_COLOR = (255, 182, 78) # warm orange, as in the firmware DEFAULT_GAINS = (255, 162, 96) # white balance, as in the firmware MODES = {0: 'H-pattern', 1: 'sequential', 2: 'handbrake'} +JITTER_LEVELS = ('none', 'low', 'medium', 'high') # calibration target names -> 24 21 argument TARGETS = {f'gear{k}': k for k in range(1, 9)} @@ -85,6 +88,7 @@ def __init__(self, raw: bytes): highlow_on = property(lambda self: bool(self.raw[23] & OPT_RANGE_ON)) gamma = property(lambda self: bool(self.raw[23] & OPT_GAMMA)) neutral_button = property(lambda self: bool(self.raw[23] & OPT_NEUTRAL)) + jitter = property(lambda self: (self.raw[23] & OPT_JITTER) >> 5) gains = property(lambda self: (self.raw[24], self.raw[53], self.raw[54])) def gear(self, k): @@ -217,6 +221,8 @@ def show_status(sh: Shifter, out=None): say(f'gamma {"on" if st.gamma else "off"}', out) if (openshifter_version(sh.info) or (0,)) >= (0, 5, 0): say(f'neutral button {"on" if st.neutral_button else "off"}', out) + if (openshifter_version(sh.info) or (0,)) >= (0, 6, 0): + say(f'anti-jitter {JITTER_LEVELS[st.jitter]}', out) say(f'lever x={st.x} y={st.y}', out) say('calibration', out) say(f' neutral {st.neutral}', out) @@ -288,6 +294,14 @@ def cmd_neutral(sh, args, out=None): return 0 +def cmd_jitter(sh, args, out=None): + need_options(sh, (0, 6, 0)) + level = JITTER_LEVELS.index(args.level) + set_and_check(sh, (CMD_JITTER, level), lambda st: st.jitter == level, 'anti-jitter') + say(f'anti-jitter {args.level} (saved)', out) + return 0 + + def set_gains(sh, gains, save): sh.write(command(CMD_BALANCE, *gains, int(save))) @@ -443,6 +457,8 @@ def main(argv=None, bus=None, inp=None, out=None, opener=open_hidraw): s = sub.add_parser('neutral', help='hold button 1 while the lever is in neutral, ' 'for games that need a neutral binding (off by default)') s.add_argument('state', choices=['on', 'off']) + s = sub.add_parser('anti-jitter', help='steady the lever position: none (default), low, medium or high') + s.add_argument('level', choices=JITTER_LEVELS) sub.add_parser('identify-leds', help='light each LED in turn to find which is which') args = p.parse_args(argv) @@ -454,6 +470,7 @@ def main(argv=None, bus=None, inp=None, out=None, opener=open_hidraw): 'balance': lambda sh: cmd_balance(sh, args, out, inp), 'gamma': lambda sh: cmd_gamma(sh, args, out), 'neutral': lambda sh: cmd_neutral(sh, args, out), + 'anti-jitter': lambda sh: cmd_jitter(sh, args, out), 'identify-leds': lambda sh: cmd_identify(sh, args, out, inp)} try: sh = open_shifter(bus or LinuxBus(), args.device, opener) diff --git a/web/package-lock.json b/web/package-lock.json index 3515a0b..b6c6f1c 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "openshifter-web", - "version": "0.5.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openshifter-web", - "version": "0.5.0", + "version": "0.6.0", "license": "MIT", "dependencies": { "@fontsource-variable/inter": "5.3.0", diff --git a/web/package.json b/web/package.json index ea7f18f..7fc6d7b 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "openshifter-web", "private": true, - "version": "0.5.0", + "version": "0.6.0", "description": "Browser tool (WebHID) to update, configure and calibrate a VelocityOne Multi-Shift running OpenShifter", "license": "MIT", "type": "module", diff --git a/web/src/components/SettingsPanel.tsx b/web/src/components/SettingsPanel.tsx index fa0eb4a..3b4da07 100644 --- a/web/src/components/SettingsPanel.tsx +++ b/web/src/components/SettingsPanel.tsx @@ -3,8 +3,8 @@ import { Description, Field, Fieldset, Input, Label, Legend, Radio, RadioGroup } import { useCallback, useEffect, useRef, useState } from 'react' import { parseHex, toHex } from '../lib/color' import { - CMD_BALANCE, CMD_COLOR, CMD_GAMMA, CMD_HIGHLOW, CMD_LED, CMD_LOGO, CMD_NEUTRAL, DEFAULT_COLOR, DEFAULT_GAINS, - type RGB, type Status, + CMD_BALANCE, CMD_COLOR, CMD_GAMMA, CMD_HIGHLOW, CMD_JITTER, CMD_LED, CMD_LOGO, CMD_NEUTRAL, DEFAULT_COLOR, + DEFAULT_GAINS, MODE_HANDBRAKE, type RGB, type Status, } from '../lib/protocol' import type { Firmware, Session } from '../lib/session' import { Button, Notice, Section, Spinner, Toggle, cx, focusRing } from './ui' @@ -287,6 +287,176 @@ function WhiteBalance({ session, status, onEditing }: ) } +function RadioCards({ label, value, onChange, disabled, options, className }: + { label: string; value: T; onChange(v: T): void; disabled: boolean; className: string + options: { value: T; title: string; text: string }[] }) { + return ( + + {options.map((o) => ( + + + + + + {o.title} + {o.text} + + + ))} + + ) +} + +/** Seconds the trace shows. */ +const TRACE_S = 4 + +type Raw = { x: number; y: number } | null + +interface Lane { + name: string + /** As games see it. */ + get(s: Session): number | null + /** The same before anti-jitter, from feature report 0x26. */ + raw(r: Raw, s: Session): number | null + /** Each lane zooms in on its own range, never closer than this. */ + minSpan: number + unit?: string +} + +/** Raw y on the handbrake axis, mapped from the calibration as the firmware does. */ +function rawAxis(r: Raw, s: Session): number | null { + const st = s.status + if (!r || !st) return null + const lo = st.neutral[1] - 300 + const hi = st.handbrake[1] + 100 + if (lo <= hi) return null + return Math.min(100, Math.max(0, ((lo - r.y) / (lo - hi)) * 100)) +} + +const LANES: Lane[] = [ + { name: 'Lever x', get: (s) => s.status?.x ?? null, raw: (r) => r?.x ?? null, minSpan: 40 }, + { name: 'Lever y', get: (s) => s.status?.y ?? null, raw: (r) => r?.y ?? null, minSpan: 40 }, +] +const AXIS_LANE: Lane = { name: 'Handbrake axis', get: (s) => (s.inputs.handbrake / 65535) * 100, raw: rawAxis, + minSpan: 5, unit: '%' } + +/** The lever position over the last few seconds, as the shifter reports it, + * over the raw sensor reading in grey, so what anti-jitter removes shows at + * once. Each lane zooms in on its own range. With anti-jitter on, the raw + * reading comes in report 0x26; with it off, the reported position is the raw + * one. The trace sends nothing to the shifter: in Chrome, every command or + * feature request holds input reports back for tens of milliseconds. */ +function LeverTrace({ session, handbrake, level }: { session: Session; handbrake: boolean; level: number }) { + const canvas = useRef(null) + const [hasRaw, setHasRaw] = useState(false) + const lanes = handbrake ? [...LANES, AXIS_LANE] : LANES + useEffect(() => { + const c = canvas.current + const ctx = c?.getContext('2d') + if (!c || !ctx) return + const pts: { t: number; v: (number | null)[]; r: (number | null)[] }[] = [] + const views: ([number, number] | null)[] = lanes.map(() => null) + let frame = 0 + let rawSeen = false + const draw = (t: number) => { + const st = session.status + const raw: Raw = level ? (t - session.rawAt < 100 ? session.raw : null) : st && { x: st.x, y: st.y } + if (!!raw !== rawSeen) { rawSeen = !!raw; setHasRaw(rawSeen) } + pts.push({ t, v: lanes.map((l) => l.get(session)), r: lanes.map((l) => l.raw(raw, session)) }) + while (pts.length && pts[0].t < t - TRACE_S * 1000) pts.shift() + const dpr = window.devicePixelRatio || 1 + const w = c.clientWidth + const h = c.clientHeight + if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { + c.width = Math.round(w * dpr) + c.height = Math.round(h * dpr) + } + ctx.setTransform(dpr, 0, 0, dpr, 0, 0) + ctx.clearRect(0, 0, w, h) + const style = getComputedStyle(c) + const laneH = h / lanes.length + ctx.font = '12px system-ui, sans-serif' + lanes.forEach((lane, i) => { + const top = i * laneH + if (i) { + ctx.strokeStyle = style.borderColor + ctx.lineWidth = 1 + ctx.beginPath() + ctx.moveTo(0, top) + ctx.lineTo(w, top) + ctx.stroke() + } + let lo = Infinity + let hi = -Infinity + for (const q of pts) { + for (const v of [q.v[i], q.r[i]]) if (v !== null) { lo = Math.min(lo, v); hi = Math.max(hi, v) } + } + if (lo > hi) return + // The range to show, eased so a change of zoom is easy to follow. + const span = Math.max(lane.minSpan, (hi - lo) * 1.2) + const want: [number, number] = [(lo + hi) / 2 - span / 2, (lo + hi) / 2 + span / 2] + const view = views[i] + const [v0, v1] = views[i] = view + ? [view[0] + (want[0] - view[0]) * 0.2, view[1] + (want[1] - view[1]) * 0.2] : want + const py = (v: number) => top + 22 + (laneH - 28) * (1 - (v - v0) / (v1 - v0)) + const line = (color: string, width: number, get: (q: (typeof pts)[number]) => number | null) => { + ctx.strokeStyle = color + ctx.lineWidth = width + ctx.lineJoin = 'round' + ctx.beginPath() + let open = false + for (const q of pts) { + const v = get(q) + if (v === null) { open = false; continue } + const x = w - ((t - q.t) / (TRACE_S * 1000)) * w + if (open) ctx.lineTo(x, py(v)) + else ctx.moveTo(x, py(v)) + open = true + } + ctx.stroke() + } + line(style.outlineColor, 1.5, (q) => q.r[i]) + line(style.color, 2, (q) => q.v[i]) + const last = pts[pts.length - 1].v[i] + ctx.fillStyle = style.textDecorationColor + ctx.textBaseline = 'top' + ctx.fillText(`${lane.name} ${last === null ? '–' : Math.round(last) + (lane.unit ?? '')}`, 8, top + 6) + }) + frame = requestAnimationFrame(draw) + } + frame = requestAnimationFrame(draw) + return () => cancelAnimationFrame(frame) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [session, handbrake, level]) + return ( +
+
+ + As games see it + + {hasRaw && ( + + Raw sensor reading + + )} +
+ +

Last {TRACE_S} seconds.

+
+ ) +} + +const JITTER_OPTIONS = [ + { value: 0, title: 'None', text: 'The raw reading. The lever position twitches even when you hold it still.' }, + { value: 1, title: 'Low', text: 'Hides the sensor noise. Slow moves arrive about 2 ms later.' }, + { value: 2, title: 'Medium', text: 'Also stays still when your hand shakes a little.' }, + { value: 3, title: 'High', text: 'Steadiest. Slow moves arrive about 7 ms later.' }, +] + export function SettingsPanel({ session, status, firmware, onPinAccent, onOpenFirmware }: { session: Session; status: Status | null; firmware: Firmware | null; onPinAccent(c: RGB | null): void; onOpenFirmware(): void }) { if (!status || !firmware) return

Reading the shifter…

@@ -302,17 +472,20 @@ export function SettingsPanel({ session, status, firmware, onPinAccent, onOpenFi ) } return + antiJitter={firmware.antiJitter} onPinAccent={onPinAccent} /> } -function OpenShifterSettings({ session, status, balance, neutral, onPinAccent }: - { session: Session; status: Status; balance: boolean; neutral: boolean; onPinAccent(c: RGB | null): void }) { +function OpenShifterSettings({ session, status, balance, neutral, antiJitter, onPinAccent }: + { session: Session; status: Status; balance: boolean; neutral: boolean; antiJitter: boolean + onPinAccent(c: RGB | null): void }) { const logo = useImmediate(session, status.logo, (v) => [CMD_LOGO, +v], (st, v) => st.logo === v, 'logo LED') const highlow = useImmediate(session, status.highlowToggle, (v) => [CMD_HIGHLOW, +v], (st, v) => st.highlowToggle === v, 'high/low') const gamma = useImmediate(session, status.gamma, (v) => [CMD_GAMMA, +v], (st, v) => st.gamma === v, 'gamma') const neutralButton = useImmediate(session, status.neutralButton, (v) => [CMD_NEUTRAL, +v], (st, v) => st.neutralButton === v, 'neutral button') + const jitter = useImmediate(session, status.antiJitter, (v) => [CMD_JITTER, v], (st, v) => st.antiJitter === v, + 'anti-jitter') const [wbColor, setWbColor] = useState(null) const onEditing = useCallback((c: RGB | null) => { setWbColor(c); onPinAccent(c) }, [onPinAccent]) const options = [ @@ -339,25 +512,25 @@ function OpenShifterSettings({ session, status, balance, neutral, onPinAccent }: )}
- - {options.map((o) => ( - - - - - - {o.title} - {o.text} - - - ))} - +
+
+ {antiJitter ? ( + <> + +
+ + + ) : ( +

+ Anti-jitter needs OpenShifter 0.6.0 or newer. Update from the Firmware tab. +

+ )} +
{neutral ? (
diff --git a/web/src/lib/demo.ts b/web/src/lib/demo.ts index 190f90a..e31a23f 100644 --- a/web/src/lib/demo.ts +++ b/web/src/lib/demo.ts @@ -27,7 +27,7 @@ export class Demo { private run = 0 constructor(start: DemoStart) { - const fw = start === 'openshifter' ? new TextEncoder().encode('\0OpenShifter 0.5.0\0') : null + const fw = start === 'openshifter' ? new TextEncoder().encode('\0OpenShifter 0.6.0\0') : null this.sim = new SimShifter({ firmware: fw, clock: realClock, bootMode: start === 'update' }) const g: Point[] = [1, 2, 3, 4, 5, 6, 7, 8].map((k) => { const [x, y] = POSES[`gear${k}`] diff --git a/web/src/lib/lib.test.ts b/web/src/lib/lib.test.ts index a726dff..a0ccc1b 100644 --- a/web/src/lib/lib.test.ts +++ b/web/src/lib/lib.test.ts @@ -8,10 +8,11 @@ import { orientation, slot, tilt, toGate, toSequential } from './gate' import type { ShifterDevice } from './hid' import { findOpenShifterVersion, loadImage, problems } from './image' import { - BTN_NEUTRAL, CHUNK, CMD_NEUTRAL, DEFAULT_COLOR, PID_APP, PID_BOOT, REPORT_ID, Status, chunk, chunkCount, command, - compareVersions, engagedGear, parseVersion, + BTN_NEUTRAL, CHUNK, CMD_JITTER, CMD_NEUTRAL, DEFAULT_COLOR, PID_APP, PID_BOOT, REPORT_ID, Status, chunk, chunkCount, command, + compareVersions, engagedGear, parseRaw, parseVersion, } from './protocol' import { POSES, SimShifter, type SimOptions } from './sim' +import { Session } from './session' import { UDEV_RULE } from './udev' const BIN = join(__dirname, '..', '..', '..', 'firmware', 'build', 'openshifter.bin') @@ -108,6 +109,47 @@ describe('protocol', () => { sim.lever = POSES.neutral expect(sim.inputs()[1]).toBe(0) }) + + it('sets the anti-jitter level from 0.6.0', async () => { + const open = async (version: string) => { + const sim = new SimShifter({ firmware: fakeImage(4000, `OpenShifter ${version}`) }) + const s = new Session((await sim.bus().devices())[0], (ms) => sim.bus().sleep(ms)) + const t = setInterval(() => sim.emit(), 5) + try { + await s.start() + return { sim, s, fw: s.firmware, stop: () => clearInterval(t) } + } catch (e) { clearInterval(t); throw e } + } + const old = await open('0.5.0') + expect(old.fw).toMatchObject({ kind: 'openshifter', neutral: true, antiJitter: false }) + await old.s.write(CMD_JITTER, 2) + expect(new Status(old.sim.status()).antiJitter).toBe(0) + old.stop() + + const cur = await open('0.6.0') + expect(cur.fw).toMatchObject({ kind: 'openshifter', antiJitter: true }) + for (const level of [3, 1, 2, 0]) { + const st = await cur.s.setAndCheck([CMD_JITTER, level], (x) => x.antiJitter === level, 'anti-jitter') + expect(st.raw[23] & 0x60).toBe(level << 5) + } + await cur.s.write(CMD_JITTER, 4) + expect(new Status(cur.sim.status()).antiJitter).toBe(0) + cur.sim.lever = [-1234, 567] + cur.s.raw = null + await cur.s.freshStatus() + expect(cur.s.raw).toBeNull() + await cur.s.setAndCheck([CMD_JITTER, 1], (x) => x.antiJitter === 1, 'anti-jitter') + expect(cur.s.raw).toEqual({ x: -1234, y: 567 }) + old.sim.emit() + expect(old.s.raw).toBeNull() + cur.stop() + }) + + it('reads the raw report with or without the report ID', () => { + expect(parseRaw(new DataView(new Uint8Array([0x26, 0xfb, 0x2e, 0x02, 0x37]).buffer))).toEqual({ x: -1234, y: 567 }) + expect(parseRaw(new DataView(new Uint8Array([0xfb, 0x2e, 0x02, 0x37]).buffer))).toEqual({ x: -1234, y: 567 }) + expect(parseRaw(new DataView(new Uint8Array([0x26, 1]).buffer))).toBeNull() + }) }) describe('image checks', () => { diff --git a/web/src/lib/protocol.ts b/web/src/lib/protocol.ts index 01a1b2a..d8339e8 100644 --- a/web/src/lib/protocol.ts +++ b/web/src/lib/protocol.ts @@ -9,6 +9,9 @@ export const PID_BOOT = 0x7097 export const REPORT_ID = 0x24 export const VERSION_REPORT_ID = 0x25 +/** Input report: the lever's x and y before anti-jitter, sent while + * anti-jitter is on (0.6.0 and newer). */ +export const RAW_REPORT_ID = 0x26 export const REPORT_LEN = 63 export const CMD_BOOT = 0x00 @@ -23,6 +26,7 @@ export const CMD_HIGHLOW = 0x32 export const CMD_BALANCE = 0x33 export const CMD_GAMMA = 0x34 export const CMD_NEUTRAL = 0x35 +export const CMD_JITTER = 0x36 export const CHUNK = 60 export const ERASE_WAIT_MS = 2000 @@ -36,6 +40,9 @@ export const OPT_RANGE_TOGGLE = 0x02 export const OPT_RANGE_ON = 0x04 export const OPT_GAMMA = 0x08 export const OPT_NEUTRAL = 0x10 +/** Anti-jitter level 0 to 3 in bits 5 and 6 (0.6.0 and newer). */ +export const OPT_JITTER = 0x60 +export const OPT_JITTER_SHIFT = 5 export const OPT_PRESENT = 0x80 export type RGB = readonly [number, number, number] @@ -110,6 +117,8 @@ export class Status { get highlowOn() { return (this.raw[23] & OPT_RANGE_ON) !== 0 } get gamma() { return (this.raw[23] & OPT_GAMMA) !== 0 } get neutralButton() { return (this.raw[23] & OPT_NEUTRAL) !== 0 } + /** Anti-jitter on the lever position: 0 none, 1 low, 2 medium, 3 high. */ + get antiJitter() { return (this.raw[23] & OPT_JITTER) >> OPT_JITTER_SHIFT } get gains(): RGB { return [this.raw[24], this.raw[53], this.raw[54]] } /** Strength of the magnet's field at the sensor, sent as r / 8. */ get radius() { return this.raw[48] * 8 } @@ -160,6 +169,13 @@ export function parseVersion(data: DataView): string | null { return /^\d+\.\d+\.\d+/.test(s) ? s : null } +/** Report 0x26: raw lever x, y, big-endian, with or without the report ID. */ +export function parseRaw(data: DataView): { x: number; y: number } | null { + const off = data.byteLength === 5 && data.getUint8(0) === RAW_REPORT_ID ? 1 : 0 + if (data.byteLength - off < 4) return null + return { x: data.getInt16(off), y: data.getInt16(off + 2) } +} + export function compareVersions(a: string, b: string): number { const pa = a.split(/[^0-9]/).slice(0, 3).map(Number) const pb = b.split(/[^0-9]/).slice(0, 3).map(Number) diff --git a/web/src/lib/session.ts b/web/src/lib/session.ts index a19ccb4..cbbba69 100644 --- a/web/src/lib/session.ts +++ b/web/src/lib/session.ts @@ -3,23 +3,29 @@ // commands that are checked against a fresh status, as in openshifter_ctl.py. import type { InputReport, ShifterDevice } from './hid' import { readVersion } from './flash' -import { PID_BOOT, REPORT_ID, Status, command, compareVersions, parseInputs, type Inputs, type Lever } from './protocol' +import { + PID_BOOT, RAW_REPORT_ID, REPORT_ID, Status, command, compareVersions, parseInputs, parseRaw, type Inputs, type Lever, +} from './protocol' export type Firmware = | { kind: 'bootloader' } | { kind: 'stock' } /** `version` is exact from 0.4.0 on; older builds only show what they support. */ - | { kind: 'openshifter'; version: string | null; balance: boolean; neutral: boolean } + | { kind: 'openshifter'; version: string | null; balance: boolean; neutral: boolean; antiJitter: boolean } export class SessionError extends Error {} -/** Status reports averaged for the lever: 24 ms at the shifter's rate. */ +/** Status reports averaged for the lever: 24 ms at the shifter's rate, 48 ms + * with anti-jitter on (report 0x26 then takes every other slot). */ const LEVER_SAMPLES = 12 export class Session { readonly device: ShifterDevice status: Status | null = null inputs: Inputs = { gears: 0, buttons: 0, handbrake: 0 } + /** The lever before anti-jitter, from report 0x26 (sent while anti-jitter is on). */ + raw: { x: number; y: number } | null = null + rawAt = 0 version: string | null = null private waiters: ((s: Status) => void)[] = [] private recent: Lever[] = [] @@ -33,6 +39,9 @@ export class Session { for (const f of w) f(this.status) } else if (e.reportId === 1 && e.data.byteLength >= 2) { this.inputs = parseInputs(e.data) + } else if (e.reportId === RAW_REPORT_ID) { + this.raw = parseRaw(e.data) + this.rawAt = performance.now() } } @@ -75,8 +84,8 @@ export class Session { if (!st) return null if (!st.hasOptions) return { kind: 'stock' } const balance = this.version !== null || st.gains.some((g) => g !== 0) - const neutral = this.version !== null && compareVersions(this.version, '0.5.0') >= 0 - return { kind: 'openshifter', version: this.version, balance, neutral } + const atLeast = (v: string) => this.version !== null && compareVersions(this.version, v) >= 0 + return { kind: 'openshifter', version: this.version, balance, neutral: atLeast('0.5.0'), antiJitter: atLeast('0.6.0') } } nextStatus(timeoutMs = 1000): Promise { diff --git a/web/src/lib/sim.ts b/web/src/lib/sim.ts index f133acb..f3cd6ea 100644 --- a/web/src/lib/sim.ts +++ b/web/src/lib/sim.ts @@ -5,9 +5,9 @@ import type { Bus, InputReport, ShifterDevice } from './hid' import { findOpenShifterVersion } from './image' import { APP_MAX, BTN_NEUTRAL, BTN_SHIFT_DOWN, BTN_SHIFT_UP, CHUNK, CHUNK_GAP_MS, CMD_BALANCE, CMD_BOOT, CMD_CALIBRATE, CMD_COLOR, CMD_DONE, CMD_ERASE, - CMD_GAMMA, CMD_HIGHLOW, CMD_LED, CMD_LOGO, CMD_NEUTRAL, CMD_WRITE, DEFAULT_COLOR, DEFAULT_GAINS, ERASE_WAIT_MS, - MODE_H, MODE_SEQ, OPT_GAMMA, OPT_LOGO, OPT_NEUTRAL, OPT_PRESENT, OPT_RANGE_ON, OPT_RANGE_TOGGLE, PID_APP, PID_BOOT, - REPORT_ID, REPORT_LEN, VERSION_REPORT_ID, compareVersions, type Point, type RGB, + CMD_GAMMA, CMD_HIGHLOW, CMD_JITTER, CMD_LED, CMD_LOGO, CMD_NEUTRAL, CMD_WRITE, DEFAULT_COLOR, DEFAULT_GAINS, ERASE_WAIT_MS, + MODE_H, MODE_SEQ, OPT_GAMMA, OPT_JITTER_SHIFT, OPT_LOGO, OPT_NEUTRAL, OPT_PRESENT, OPT_RANGE_ON, OPT_RANGE_TOGGLE, PID_APP, PID_BOOT, + RAW_REPORT_ID, REPORT_ID, REPORT_LEN, VERSION_REPORT_ID, compareVersions, type Point, type RGB, } from './protocol' export interface Clock { @@ -87,6 +87,7 @@ export class SimShifter { highlowOn = false gamma = false neutralButton = false + antiJitter = 0 switchH = true lever: Point = POSES.neutral radius = RADIUS.neutral @@ -243,6 +244,7 @@ export class SimShifter { case CMD_BALANCE: this.gains = [a, b, c]; void e; break case CMD_GAMMA: this.gamma = a !== 0; break case CMD_NEUTRAL: if (compareVersions(this.version!, '0.5.0') >= 0) this.neutralButton = a !== 0; break + case CMD_JITTER: if (compareVersions(this.version!, '0.6.0') >= 0 && a <= 3) this.antiJitter = a; break } } @@ -261,6 +263,7 @@ export class SimShifter { this.highlowToggle = false this.gamma = false this.neutralButton = false + this.antiJitter = 0 this.gears = this.gears.map(() => [0, 0] as Point) this.neutral = [0, 0] this.handbrake = [0, 0] @@ -293,7 +296,7 @@ export class SimShifter { if (this.isOpenShifter) { r[23] = OPT_PRESENT | (this.logo ? OPT_LOGO : 0) | (this.highlowToggle ? OPT_RANGE_TOGGLE : 0) | (this.highlowOn ? OPT_RANGE_ON : 0) | (this.gamma ? OPT_GAMMA : 0) | - (this.neutralButton ? OPT_NEUTRAL : 0) + (this.neutralButton ? OPT_NEUTRAL : 0) | this.antiJitter << OPT_JITTER_SHIFT r[24] = this.gains[0] r[53] = this.gains[1] r[54] = this.gains[2] @@ -326,9 +329,15 @@ export class SimShifter { if (!this.present || this.pid !== PID_APP) return const st = this.status() const i = this.inputs() + // Report 0x26 while anti-jitter is on. No noise in the simulator: the raw + // lever is the reported one. + const raw = this.antiJitter ? new DataView(new ArrayBuffer(4)) : null + raw?.setInt16(0, this.lever[0]) + raw?.setInt16(2, this.lever[1]) for (const l of this.listeners) { l({ reportId: REPORT_ID, data: new DataView(st.buffer, 1, 63) }) l({ reportId: 1, data: new DataView(i.buffer) }) + if (raw) l({ reportId: RAW_REPORT_ID, data: raw }) } } } diff --git a/wiki/Command-line.md b/wiki/Command-line.md index 18d7908..1527b58 100644 --- a/wiki/Command-line.md +++ b/wiki/Command-line.md @@ -37,6 +37,7 @@ python3 tools/openshifter_ctl.py highlow toggle # or button python3 tools/openshifter_ctl.py balance # white balance, guided python3 tools/openshifter_ctl.py gamma on # or off python3 tools/openshifter_ctl.py neutral on # neutral button, or off +python3 tools/openshifter_ctl.py anti-jitter medium # none, low, medium or high ``` After calibrating, unplug the shifter and plug it back in. `calibrate` and `status` also work with the stock firmware. diff --git a/wiki/Settings.md b/wiki/Settings.md index 84c5daf..6ffd697 100644 --- a/wiki/Settings.md +++ b/wiki/Settings.md @@ -12,3 +12,4 @@ Settings need OpenShifter. With the stock firmware, [install OpenShifter](Instal | White balance | Fixes LEDs that look blue or green when they should be white. Press **Adjust**, move the sliders until the LEDs look white, then press **Save white balance**. | Red 255, green 162, blue 96 | | High/low button | **Button:** on while you hold it. **Toggle:** each press switches it on or off, and its LED shows red for off and green for on. Saved when you pick one. | Button | | Neutral button | With the switch in H, presses the shifter's first button while the lever is out of gear. Turn it on if your game stays in the last gear when you move to neutral, then bind that button to **Neutral** in the game. See [Using the shifter](Using-the-shifter#what-games-see). Needs OpenShifter 0.5.0. Saved when you flip the switch. | Off | +| Anti-jitter | Keeps the lever position still while you hold the lever still. The lever's magnet sensor reads a little noise, so without it the position twitches, and with it the handbrake axis and, right at the edge of a gear, the gear. **Low** hides that noise, **Medium** also hides a slightly shaky hand, and **High** is the steadiest; slow moves arrive a few milliseconds later. Quick shifts and a yanked handbrake are never delayed. The trace under the choices shows the lever live as games see it, over the raw sensor reading in grey, so you can see what anti-jitter removes. Needs OpenShifter 0.6.0. Saved when you pick one. | None |