diff --git a/docs/8bitdo-retro-r8.md b/docs/8bitdo-retro-r8.md new file mode 100644 index 00000000..e3b6b3c4 --- /dev/null +++ b/docs/8bitdo-retro-r8.md @@ -0,0 +1,144 @@ +# 8BitDo Retro R8 Mouse (2dc8:5206 receiver) + +Driver for the Retro R8 through its 2.4 GHz receiver: reads its settings and +firmware versions, and writes the polling rate, DPI stages and lift-off. +Verified on a Retro R8 N Edition on Linux. Battery is not available on this connection (see +below); over Bluetooth the mouse reports it through the standard Battery +Service. + +## Hardware + +- Receiver: VID `0x2dc8`, PID `0x5206`, bcdDevice `4.26`, product string + "8BitDo Retro R8 Mouse Adapter". Four HID interfaces: + - 0: mouse (report 1); + - 1: keyboard, consumer and system control; + - 2: vendor collection, usage page `0xFF00`, usage `0x01`, unnumbered + 64-byte input and output reports. **This is the configuration channel.** + - 3: vendor usage page `0xFF0B` (reports `0x2A`–`0x2D`) and `0xFF02` + (feature `0x14`): the Realtek update channel. Not used. +- Over Bluetooth LE the mouse shows up as PID `0x5205` with GATT Device + Information, Battery (`0x180F`) and HID services. +- Receiver firmware identifies itself as Realtek SDK "RTK20250227D". + +## Sources + +- **8BitDo Ultimate Software V2, Windows V1.38**, read statically (it is a + .NET application plus a native helper DLL). Used for: which frames it sends + to PID `0x5206`, which reply bytes it checks, and the offsets it reads each + value from. No vendor code or binary is included in this repository. +- **Hardware**: every read below was sent to the receiver on Linux through + `/dev/hidraw` and the replies recorded. The DPI button was pressed while the + replies were polled, and the active stage followed it through all six + stages and back. +- **[mbs1337/r8-rs](https://github.com/mbs1337/r8-rs)** (GPL-3.0), an + independent Linux tool for the same receiver, uses the same frame and + `01 06 12 01` for the active DPI, which corroborates the layout above. No + code from it is used here. + +## Frame + +Unnumbered 64-byte output report, reply as a 64-byte input report. + +| Target | Request | Reply | +|---|---|---| +| Mouse (over the air) | `01 06 01 [args]` | `01 06 11 ` | +| Receiver | `06 01` | `26 11 ` | + +`op` `01` reads; the vendor tool writes with `04`. + +For a mouse request the receiver first acknowledges at once with +`21 06 01 … 14` while it forwards the request over the air; the mouse's +reply `01 06 11 …` follows 5–210 ms later. Wait for the reply and skip +the acknowledgement. When the mouse is asleep or switched off, only the +acknowledgement arrives. + +The mouse answers almost every id with `11`, including ids it does not use: +those get an empty payload. An empty `01 06 11` therefore does not prove +that a command exists or that it read anything, and the driver rejects replies +without the payload it expects. + +## Verified reads + +| Command | Payload | Example (N Edition) | +|---|---|---| +| Receiver `06 03 0A` | `[linked]` | `01` linked, `00` mouse asleep/off | +| `0x12` active DPI | `[stage count] [active stage, 0-based] [dpi u16 LE] [table…]` | `06 01 b0 04` → stage 2 of 6, 1200 | +| `0x28` DPI table, arg `00` X / `01` Y | `[axis] [enabled mask] [6 × dpi u16 LE]` | `00 3f` 800/1200/1600/2400/3200/6400 | +| `0x0D` polling | `[rate count] [active index, 0-based] 00 00 [6 × Hz u16 LE]` | `05 01` over 250/500/1000/2000/4000 → 500 Hz | +| `0x26` lift-off | `[level]` | `01` (the tool offers 1 and 2) | +| `0x25` edition | byte 3 | `01` N Edition; the tool also knows 0 Xbox, 3 C64, 7 Forest, 8 GoW | +| Mouse `01 04 04` / receiver `06 02 03` | firmware version: major in payload byte 8, minor in byte 14 | mouse `0b`/`03` → 11.03, receiver `0a`/`0e` → 10.14 | + +The versions match the newest entries of 8BitDo's firmware catalog (mouse +11.03, receiver 10.14), and the vendor tool computes them the same way. + +Also answered but not used by the driver: `0x27` left-handed mode, `0x23` +wheel direction, `0x24` wheel speed (all `0` on the test mouse). + +## Verified writes + +Op `04`, payload after `01 06 04`; the mouse confirms with +`01 06 14`. Layouts are the vendor tool's (`WriteLod`, `WriteDpiIndex`, +`WriteDpi`, `WriteRate`). The tool sends no separate save command, and none +was needed: the values were read back from the mouse. + +| Command | Payload | +|---|---| +| `0x26` lift-off | `[level]`, 1 or 2 | +| `0x12` active stage | `06 [slot] [that slot's dpi u16 LE]` | +| `0x28` DPI table, per axis | `[axis] [enabled mask] [6 × dpi u16 LE]`; the tool writes X then Y | +| `0x0D` polling | `[rate count] [active index] 00 00 00 00 [6 × Hz u16 LE]` (rates two bytes later than in the read) | + +DPI is 50–26,000 in steps of 50, the vendor tool's limits for this mouse. + +On hardware, each write was made, read back and restored: polling 500 → 1000 +Hz, lift-off 1 → 2, active stage 2 → 1 (three rounds), and an inactive stage +6400 → 6350 DPI; the mouse ended in exactly its starting state. Once, the read +right after a stage change went unanswered, so the driver retries its +verification reads. `readStatus` retries the settings it reports for the same +reason: the panel reads the status right after each write. With that, the +OpenMouse hardware test's write round-trip passes (DPI, polling 1000 → 2000 → +1000 Hz, lift-off). + +### Other mouse ids + +A read-only sweep of `0x00`–`0x3F` (every known id above, `0x1E` and `0x20` +skipped; link and active DPI re-read after every id, all unchanged), waiting +for the mouse's own reply past the acknowledgement: + +- `0x0E` and `0x13` return the active DPI and the stage table in two other + layouts (`03 06 60 09 …` and `06 03 20 03 …` with the mouse on stage 4 of 6); +- `0x17` returns one byte, `01`, of unknown meaning; +- `0x1B` and `0x2E` get only the receiver's acknowledgement; +- every other id, `0x1A` included, gets an empty `11`. + +## Not verified, not implemented + +- **Other writes.** The vendor tool also writes buttons, macros, the + profile, wheel settings and left-handed mode with op `04`. None of them has + been sent to hardware for this driver. +- **Stage count and mask.** The driver keeps the enabled mask and edits + values only; turning stages on or off has not been tried. +- **Lift-off levels.** Mapped to `Low` (1) and `High` (2) after the order of + the tool's two options; the distances are not documented. + +## Battery + +Not available through the receiver: + +- the vendor tool never reads a battery value for PID `0x5206`; +- `0x1A`, the opcode of the vendor DLL's `ReadBAT` export (used for other + products) and the read r8-rs tries, answers with an empty `11`; r8-rs's + README also notes that the battery is not exposed over this link; +- the mouse-id sweep above returns nothing battery-like, nor do receiver + classes `06 02 xx` and `06 03 xx` (`xx` = `0x00`–`0x3F`), and charging on + the dock changes no reply. + +## Do not send + +- Mouse `0x1E` and `0x20` (with op `01`) drop the mouse off the receiver. It + comes back after moving it or switching it off and on, with its settings + intact. +- Receiver `06 04 …` erases flash and `06 07 …` resets the receiver (the + vendor tool's update path, opcodes `0x0004`/`0x0007`; `0x00C1`/`0x00C3` + start the update and read its CRC). Never sweep receiver classes blindly. diff --git a/package.json b/package.json index b4fc0302..c1043536 100644 --- a/package.json +++ b/package.json @@ -143,6 +143,10 @@ "types": "./dist/kmart/index.d.ts", "import": "./dist/kmart/index.js" }, + "./8bitdo": { + "types": "./dist/8bitdo/index.d.ts", + "import": "./dist/8bitdo/index.js" + }, "./vaxee": { "types": "./dist/vaxee/index.d.ts", "import": "./dist/vaxee/index.js" diff --git a/src/8bitdo/index.test.ts b/src/8bitdo/index.test.ts new file mode 100644 index 00000000..ee08b479 --- /dev/null +++ b/src/8bitdo/index.test.ts @@ -0,0 +1,163 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + EIGHTBITDO_CMD, + EIGHTBITDO_RECEIVER_QUERY, + EIGHTBITDO_REPORT_SIZE, + eightBitDoDecodeReply, + eightBitDoEncodeActiveDpiWrite, + eightBitDoEncodeDpiTableWrite, + eightBitDoEncodeLiftOffWrite, + eightBitDoEncodePollingWrite, + eightBitDoEnabledStages, + eightBitDoEncodeMouseRead, + eightBitDoEncodeMouseVersionRead, + eightBitDoEncodeReceiverRead, + eightBitDoIsForwarded, + eightBitDoParseActiveDpi, + eightBitDoParseDpiTable, + eightBitDoParseEdition, + eightBitDoParseFirmwareVersion, + eightBitDoParseLiftOff, + eightBitDoParseLink, + eightBitDoParsePolling, + type EightBitDoMouseCommand, +} from "./index.ts"; + +const bytes = (hex: string) => { + const out = new Uint8Array(EIGHTBITDO_REPORT_SIZE); + out.set(hex.trim().split(/\s+/).map((b) => Number.parseInt(b, 16))); + return out; +}; +const hex = (data: Uint8Array, length = data.length) => + [...data.subarray(0, length)].map((b) => b.toString(16).padStart(2, "0")).join(" "); + +// Replies read from a Retro R8 N Edition through its receiver (trailing zeros trimmed). +const REPLY = { + linked: "26 03 0a 11 01", + unlinked: "26 03 0a 11", + activeDpi: "01 06 12 11 06 01 b0 04 20 03 b0 04 40 06 60 09 80 0c 00 19", + activeDpiStep: "01 06 12 11 06 03 60 09 20 03 b0 04 40 06 60 09 80 0c 00 19", + dpiTableX: "01 06 28 11 00 3f 20 03 b0 04 40 06 60 09 80 0c 00 19", + polling: "01 06 0d 11 05 01 00 00 fa 00 f4 01 e8 03 d0 07 a0 0f", + liftOff: "01 06 26 11 01", + edition: "01 06 25 11 00 00 00 01", + mouseVersion: "01 04 04 11 50 00 10 03 01 50 01 00 0b 25 12 30 10 50 03", + receiverVersion: "26 02 03 11 50 00 10 03 02 50 01 00 0a 25 02 27 17 20 0e 01", + // The receiver's immediate acknowledgement; the mouse's reply follows it. + forwarded: "21 06 12 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14", +}; + +const reply = (request: Uint8Array, text: string) => eightBitDoDecodeReply(bytes(text), request); + +test("encodes 64-byte read frames for the mouse and the receiver", () => { + const dpi = eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.activeDpi); + assert.equal(dpi.length, 64); + assert.equal(hex(dpi, 5), "01 06 12 01 00"); + assert.equal(hex(eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.dpiTable, [1]), 5), "01 06 28 01 01"); + assert.equal(hex(eightBitDoEncodeReceiverRead(EIGHTBITDO_RECEIVER_QUERY.link), 4), "06 03 0a 01"); +}); + +test("refuses to encode anything but the known reads", () => { + // 0x1E drops the R8 off its receiver; 0x33 is the vendor tool's profile wipe. + for (const command of [0x1e, 0x20, 0x33]) { + assert.throws(() => eightBitDoEncodeMouseRead(command as EightBitDoMouseCommand), RangeError); + } +}); + +test("decodes replies only for the request they answer", () => { + const link = eightBitDoEncodeReceiverRead(EIGHTBITDO_RECEIVER_QUERY.link); + const dpi = eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.activeDpi); + assert.equal(eightBitDoParseLink(reply(link, REPLY.linked)!), true); + assert.equal(eightBitDoParseLink(reply(link, REPLY.unlinked)!), false); + assert.equal(reply(dpi, REPLY.linked), null); + assert.equal(reply(link, REPLY.activeDpi), null); + assert.equal(reply(dpi, REPLY.forwarded), null); + assert.equal(eightBitDoIsForwarded(bytes(REPLY.forwarded), dpi), true); + assert.equal(eightBitDoDecodeReply(new Uint8Array([1, 6]), dpi), null); +}); + +test("parses the active DPI and follows the DPI button", () => { + const dpi = eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.activeDpi); + assert.deepEqual(eightBitDoParseActiveDpi(reply(dpi, REPLY.activeDpi)!), { stageCount: 6, activeStage: 1, dpi: 1200 }); + assert.deepEqual(eightBitDoParseActiveDpi(reply(dpi, REPLY.activeDpiStep)!), { stageCount: 6, activeStage: 3, dpi: 2400 }); + assert.equal(eightBitDoParseActiveDpi(new Uint8Array([6, 6, 0x20, 0x03])), null); +}); + +test("parses the DPI stage table and its enabled mask", () => { + const table = eightBitDoParseDpiTable(reply(eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.dpiTable, [0]), REPLY.dpiTableX)!)!; + assert.deepEqual(table, { axis: 0, enabledMask: 0x3f, stages: [800, 1200, 1600, 2400, 3200, 6400] }); + assert.deepEqual(eightBitDoEnabledStages({ ...table, enabledMask: 0b000101 }), [800, 1600]); +}); + +test("parses polling as an index into the mouse's own rate list", () => { + const polling = eightBitDoParsePolling(reply(eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.pollingRate), REPLY.polling)!); + assert.deepEqual(polling, { + rates: [250, 500, 1000, 2000, 4000], + slots: [250, 500, 1000, 2000, 4000, 0], + count: 5, + activeIndex: 1, + rateHz: 500, + }); + assert.equal(eightBitDoParsePolling(new Uint8Array([5, 7, 0, 0, 0xfa, 0])), null); +}); + +test("parses lift-off and edition", () => { + assert.equal(eightBitDoParseLiftOff(reply(eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.liftOff), REPLY.liftOff)!), 1); + assert.equal(eightBitDoParseLiftOff(new Uint8Array([3])), null); + assert.equal(eightBitDoParseEdition(reply(eightBitDoEncodeMouseRead(EIGHTBITDO_CMD.edition), REPLY.edition)!), "N Edition"); + assert.equal(eightBitDoParseEdition(new Uint8Array([0, 0, 0, 0x42])), null); +}); + +test("parses firmware versions the way 8BitDo's catalog writes them", () => { + // The catalog lists the newest mouse firmware as 11.03 and receiver firmware as 10.14. + const mouse = eightBitDoEncodeMouseVersionRead(); + const receiver = eightBitDoEncodeReceiverRead(EIGHTBITDO_RECEIVER_QUERY.version); + assert.equal(hex(mouse, 4), "01 04 04 01"); + assert.equal(hex(receiver, 4), "06 02 03 01"); + assert.equal(eightBitDoParseFirmwareVersion(reply(mouse, REPLY.mouseVersion)!), "11.03"); + assert.equal(eightBitDoParseFirmwareVersion(reply(receiver, REPLY.receiverVersion)!), "10.14"); + assert.equal(eightBitDoParseFirmwareVersion(new Uint8Array(15)), null); + assert.equal(eightBitDoParseFirmwareVersion(new Uint8Array(8)), null); +}); + +test("encodes the vendor tool's write frames", () => { + assert.equal(hex(eightBitDoEncodeLiftOffWrite(2), 5), "01 06 26 04 02"); + // Stage 2 (slot 1) at 1200 DPI. + assert.equal(hex(eightBitDoEncodeActiveDpiWrite(1, 1200), 8), "01 06 12 04 06 01 b0 04"); + assert.equal( + hex(eightBitDoEncodeDpiTableWrite({ axis: 1, enabledMask: 0x3f, stages: [800, 1200, 1600, 2400, 3200, 6400] }), 18), + "01 06 28 04 01 3f 20 03 b0 04 40 06 60 09 80 0c 00 19", + ); + // 1000 Hz: the rate list is written back two bytes later than it is read. + const polling = eightBitDoParsePolling(bytes("05 01 00 00 fa 00 f4 01 e8 03 d0 07 a0 0f"))!; + assert.equal( + hex(eightBitDoEncodePollingWrite(polling, 2), 22), + "01 06 0d 04 05 02 00 00 00 00 fa 00 f4 01 e8 03 d0 07 a0 0f 00 00", + ); +}); + +test("rejects writes the mouse cannot take", () => { + assert.throws(() => eightBitDoEncodeLiftOffWrite(3 as 1), RangeError); + assert.throws(() => eightBitDoEncodeActiveDpiWrite(6, 800), RangeError); + assert.throws(() => eightBitDoEncodeActiveDpiWrite(0, 825), RangeError); + assert.throws(() => eightBitDoEncodeActiveDpiWrite(0, 26050), RangeError); + assert.throws(() => eightBitDoEncodeDpiTableWrite({ axis: 0, enabledMask: 0x3f, stages: [800, 0, 1600, 2400, 3200, 6400] }), RangeError); + // A disabled stage may hold 0. + assert.doesNotThrow(() => eightBitDoEncodeDpiTableWrite({ axis: 0, enabledMask: 0x3d, stages: [800, 0, 1600, 2400, 3200, 6400] })); + const polling = eightBitDoParsePolling(bytes("05 01 00 00 fa 00 f4 01 e8 03 d0 07 a0 0f"))!; + assert.throws(() => eightBitDoEncodePollingWrite(polling, 5), RangeError); +}); + +test("accepts a write reply only with the write bit", () => { + const write = eightBitDoEncodeLiftOffWrite(1); + assert.notEqual(eightBitDoDecodeReply(bytes("01 06 26 14"), write), null); + // The read reply to the same command does not confirm a write. + assert.equal(eightBitDoDecodeReply(bytes("01 06 26 11 01"), write), null); +}); + +test("refuses receiver queries outside the known reads", () => { + assert.throws(() => eightBitDoEncodeReceiverRead([0x04, 0x00] as never), RangeError); + assert.throws(() => eightBitDoEncodeReceiverRead([0x07, 0x00] as never), RangeError); + assert.equal(eightBitDoEncodeReceiverRead(EIGHTBITDO_RECEIVER_QUERY.version)[1], 0x02); +}); diff --git a/src/8bitdo/index.ts b/src/8bitdo/index.ts new file mode 100644 index 00000000..fc876ddc --- /dev/null +++ b/src/8bitdo/index.ts @@ -0,0 +1,323 @@ +/** + * 8BitDo Retro R8 Mouse through its 2.4 GHz receiver (`2dc8:5206`). + * + * Sources, kept apart from guesses (see docs/8bitdo-retro-r8.md): + * + * - The vendor tool, 8BitDo Ultimate Software V2 (Windows V1.38), read + * statically: which commands it sends to this receiver, which reply bytes it + * checks, and where it reads each value from. No vendor code is copied here. + * - Read-only replies captured from a Retro R8 NES Edition on Linux + * (receiver firmware with Realtek SDK string "RTK20250227D"), including the + * DPI button stepping the active stage while the replies were watched. + * + * Wire format, on the receiver's vendor collection (usage page 0xFF00, usage + * 0x01), 64-byte unnumbered output and input reports: + * + * - mouse settings: `01 06 01 [args]` reads. The receiver acknowledges + * at once with `21 06 01 … 14` while it forwards the request over the + * air; the mouse's own reply `01 06 11 ` follows a few ms + * later. Only the acknowledgement arrives when the mouse is asleep or + * switched off. The mouse answers ids it does not use with an empty `11` + * reply, so a reply is only trusted when it carries the expected payload; + * - receiver: `06 01` reads; the reply is `26 11 + * `. + * + * Writes use op `04` (`01 06 04 `), the vendor tool's layouts + * for lift-off, the active DPI stage, the DPI table and the polling rate; the + * reply sets bit `0x04` in byte 3. Only those reads and writes are encoded. The + * R8 drops off the receiver on some mouse command ids the vendor tool never + * sends (0x1E and 0x20), and the receiver's `06 04 …` / `06 07 …` frames are + * its flash-erase and reset commands, so nothing else should be sent. + */ + +export const EIGHTBITDO_VENDOR_ID = 0x2dc8; +/** Retro R8 2.4 GHz receiver. */ +export const EIGHTBITDO_R8_RECEIVER_PRODUCT_ID = 0x5206; +/** + * The same mouse over Bluetooth LE. It reports its battery through the + * standard GATT Battery Service, which the operating system reads; the vendor + * channel over Bluetooth is not mapped yet, so no driver claims this id. + */ +export const EIGHTBITDO_R8_BLUETOOTH_PRODUCT_ID = 0x5205; + +export const EIGHTBITDO_PRODUCT_NAMES: ReadonlyMap = new Map([ + [EIGHTBITDO_R8_RECEIVER_PRODUCT_ID, "8BitDo Retro R8 Mouse"], +]); +export const EIGHTBITDO_PRODUCT_IDS: readonly number[] = [...EIGHTBITDO_PRODUCT_NAMES.keys()]; + +export const EIGHTBITDO_USAGE_PAGE = 0xff00; +export const EIGHTBITDO_USAGE = 0x01; +/** Output and input reports are unnumbered. */ +export const EIGHTBITDO_REPORT_ID = 0; +export const EIGHTBITDO_REPORT_SIZE = 64; + +const MOUSE_PREFIX = [0x01, 0x06] as const; +const RECEIVER_PREFIX = 0x06; +const RECEIVER_REPLY_PREFIX = 0x26; +const OP_READ = 0x01; +const OP_WRITE = 0x04; +/** Byte 0 of the receiver's "forwarded to the mouse" acknowledgement. */ +const FORWARDED = 0x21; + +/** Mouse setting commands, read with `01 06 01`. */ +export const EIGHTBITDO_CMD = { + pollingRate: 0x0d, + activeDpi: 0x12, + wheelDirection: 0x23, + wheelSpeed: 0x24, + edition: 0x25, + liftOff: 0x26, + leftHanded: 0x27, + /** Takes one argument: 0 for the X axis, 1 for Y. */ + dpiTable: 0x28, +} as const; + +/** Receiver queries, read with `06 01`. */ +export const EIGHTBITDO_RECEIVER_QUERY = { + /** Payload byte 0 is 1 while the mouse is linked to the receiver. */ + link: [0x03, 0x0a], + /** The receiver's own firmware version; see `eightBitDoParseFirmwareVersion`. */ + version: [0x02, 0x03], +} as const; + +export type EightBitDoMouseCommand = (typeof EIGHTBITDO_CMD)[keyof typeof EIGHTBITDO_CMD]; +export type EightBitDoReceiverQuery = (typeof EIGHTBITDO_RECEIVER_QUERY)[keyof typeof EIGHTBITDO_RECEIVER_QUERY]; + +const READABLE_COMMANDS: ReadonlySet = new Set(Object.values(EIGHTBITDO_CMD)); + +/** 64-byte report that reads one mouse setting. */ +export function eightBitDoEncodeMouseRead(command: EightBitDoMouseCommand, args: readonly number[] = []): Uint8Array { + if (!READABLE_COMMANDS.has(command)) throw new RangeError(`0x${command.toString(16)} is not a known 8BitDo read.`); + if (args.length > EIGHTBITDO_REPORT_SIZE - 4) throw new RangeError("8BitDo reads carry at most 60 argument bytes."); + const report = new Uint8Array(EIGHTBITDO_REPORT_SIZE); + report.set([...MOUSE_PREFIX, command, OP_READ]); + args.forEach((value, i) => { report[4 + i] = value & 0xff; }); + return report; +} + +/** + * 64-byte report that reads the mouse's firmware version: `01 04 04 01`, a + * different class from the settings reads. The reply is `01 04 04 11 …`. + */ +export function eightBitDoEncodeMouseVersionRead(): Uint8Array { + const report = new Uint8Array(EIGHTBITDO_REPORT_SIZE); + report.set([0x01, 0x04, 0x04, OP_READ]); + return report; +} + +/** 64-byte report that queries the receiver itself. */ +export function eightBitDoEncodeReceiverRead(query: EightBitDoReceiverQuery): Uint8Array { + // Other receiver classes erase flash or reset the receiver: only the known reads are encoded. + const known = Object.values(EIGHTBITDO_RECEIVER_QUERY).some(([c, k]) => c === query[0] && k === query[1]); + if (query.length !== 2 || !known) throw new RangeError(`${query.join(",")} is not a known 8BitDo receiver read.`); + const report = new Uint8Array(EIGHTBITDO_REPORT_SIZE); + report.set([RECEIVER_PREFIX, query[0], query[1], OP_READ]); + return report; +} + +/** + * Payload of the reply to `request`, or null when `reply` answers something + * else, is the receiver's forwarding acknowledgement, or is too short. + */ +export function eightBitDoDecodeReply(reply: Uint8Array, request: Uint8Array): Uint8Array | null { + if (reply.length < 4 || request.length < 4) return null; + if (reply[0] === FORWARDED) return null; + const expected = request[0] === RECEIVER_PREFIX ? RECEIVER_REPLY_PREFIX : request[0]; + if (reply[0] !== expected || reply[1] !== request[1] || reply[2] !== request[2]) return null; + // The vendor tool accepts a reply whose byte 3 carries the request's op bit: + // `11` answers a read (op `01`), `14` a write (op `04`). + if (((reply[3] ?? 0) & request[3]!) === 0) return null; + return reply.subarray(4); +} + +/** + * True for the receiver's immediate acknowledgement of a mouse request. It is + * not the answer: keep waiting for the mouse's own reply. + */ +export function eightBitDoIsForwarded(reply: Uint8Array, request: Uint8Array): boolean { + return reply[0] === FORWARDED && reply[1] === request[1] && reply[2] === request[2]; +} + +export function eightBitDoParseLink(payload: Uint8Array): boolean { + return payload[0] === 1; +} + +const u16 = (bytes: Uint8Array, offset: number): number => (bytes[offset] ?? 0) | ((bytes[offset + 1] ?? 0) << 8); + +export interface EightBitDoActiveDpi { + stageCount: number; + /** 0-based. */ + activeStage: number; + dpi: number; +} + +/** ` ` followed by the stage table. */ +export function eightBitDoParseActiveDpi(payload: Uint8Array): EightBitDoActiveDpi | null { + if (payload.length < 4) return null; + const stageCount = payload[0]!; + const activeStage = payload[1]!; + const dpi = u16(payload, 2); + if (stageCount === 0 || activeStage >= stageCount || dpi === 0) return null; + return { stageCount, activeStage, dpi }; +} + +export interface EightBitDoDpiTable { + axis: 0 | 1; + /** Bit n set when stage n is enabled. */ + enabledMask: number; + /** All six stored stages, enabled or not. */ + stages: number[]; +} + +/** ` `. */ +export function eightBitDoParseDpiTable(payload: Uint8Array): EightBitDoDpiTable | null { + if (payload.length < 14) return null; + const axis = payload[0]; + if (axis !== 0 && axis !== 1) return null; + const stages = Array.from({ length: 6 }, (_, i) => u16(payload, 2 + i * 2)); + return { axis, enabledMask: payload[1]!, stages }; +} + +/** Enabled stages in order. */ +export function eightBitDoEnabledStages(table: EightBitDoDpiTable): number[] { + return table.stages.filter((dpi, i) => dpi > 0 && (table.enabledMask & (1 << i)) !== 0); +} + +export interface EightBitDoPolling { + /** Rates the mouse offers, in Hz. */ + rates: number[]; + /** All six stored rate slots, unused ones 0; written back unchanged. */ + slots: number[]; + /** Byte 0 as the mouse reported it (the rate count); written back unchanged. */ + count: number; + /** 0-based index into `rates`. */ + activeIndex: number; + rateHz: number; +} + +/** ` 00 00 `; unused slots are 0. */ +export function eightBitDoParsePolling(payload: Uint8Array): EightBitDoPolling | null { + if (payload.length < 6) return null; + const count = payload[0]!; + const activeIndex = payload[1]!; + const slots = Array.from({ length: 6 }, (_, i) => u16(payload, 4 + i * 2)); + const rates = slots.slice(0, count).filter((hz) => hz > 0); + const rateHz = rates[activeIndex]; + if (rateHz === undefined) return null; + return { rates, slots, count, activeIndex, rateHz }; +} + +/** Lift-off setting: the vendor tool offers 1 (lower) and 2 (higher). */ +export function eightBitDoParseLiftOff(payload: Uint8Array): 1 | 2 | null { + const value = payload[0]; + return value === 1 || value === 2 ? value : null; +} + +/** Shell editions, by the value the vendor tool picks the product picture with. */ +export const EIGHTBITDO_R8_EDITIONS: ReadonlyMap = new Map([ + [0, "Xbox Edition"], + [1, "N Edition"], + [3, "C64 Edition"], + [7, "Forest Edition"], + [8, "GoW Edition"], +]); + +/** + * Firmware version from a mouse (`01 04 04`) or receiver (`06 02 03`) version + * reply: major in payload byte 8, minor in byte 14, shown as "11.03" the way + * the vendor tool and 8BitDo's firmware catalog write it. Null when both are 0 + * or the payload is too short. + */ +export function eightBitDoParseFirmwareVersion(payload: Uint8Array): string | null { + if (payload.length < 15) return null; + const major = payload[8]!; + const minor = payload[14]!; + if (major === 0 && minor === 0) return null; + return `${major}.${String(minor).padStart(2, "0")}`; +} + +/** The edition sits in payload byte 3. */ +export function eightBitDoParseEdition(payload: Uint8Array): string | null { + return EIGHTBITDO_R8_EDITIONS.get(payload[3] ?? -1) ?? null; +} + +// ── Writes ─────────────────────────────────────────────────────────────────── + +/** DPI the vendor tool accepts for the Retro R8: 50 to 26,000 in steps of 50. */ +export const EIGHTBITDO_R8_DPI = { min: 50, max: 26000, step: 50 } as const; +export const EIGHTBITDO_DPI_STAGE_COUNT = 6; + +const WRITABLE_COMMANDS: ReadonlySet = new Set([ + EIGHTBITDO_CMD.liftOff, + EIGHTBITDO_CMD.activeDpi, + EIGHTBITDO_CMD.dpiTable, + EIGHTBITDO_CMD.pollingRate, +]); + +function encodeMouseWrite(command: EightBitDoMouseCommand, payload: readonly number[]): Uint8Array { + if (!WRITABLE_COMMANDS.has(command)) throw new RangeError(`0x${command.toString(16)} is not a known 8BitDo write.`); + const report = new Uint8Array(EIGHTBITDO_REPORT_SIZE); + report.set([...MOUSE_PREFIX, command, OP_WRITE]); + payload.forEach((value, i) => { report[4 + i] = value & 0xff; }); + return report; +} + +const le16 = (value: number) => [value & 0xff, (value >> 8) & 0xff]; + +export function eightBitDoIsValidDpi(dpi: number): boolean { + return Number.isInteger(dpi) && dpi >= EIGHTBITDO_R8_DPI.min && dpi <= EIGHTBITDO_R8_DPI.max + && dpi % EIGHTBITDO_R8_DPI.step === 0; +} + +function assertSlot(slot: number): void { + if (!Number.isInteger(slot) || slot < 0 || slot >= EIGHTBITDO_DPI_STAGE_COUNT) { + throw new RangeError(`DPI stage slot must be 0-${EIGHTBITDO_DPI_STAGE_COUNT - 1}.`); + } +} + +/** Lift-off level, 1 (lower) or 2 (higher): `01 06 26 04 `. */ +export function eightBitDoEncodeLiftOffWrite(level: 1 | 2): Uint8Array { + if (level !== 1 && level !== 2) throw new RangeError("8BitDo lift-off level must be 1 or 2."); + return encodeMouseWrite(EIGHTBITDO_CMD.liftOff, [level]); +} + +/** + * Selects the active stage: `01 06 12 04 06 `, where `dpi` + * is that slot's value in the table. The leading 6 is what the vendor tool + * always sends (the stage count). + */ +export function eightBitDoEncodeActiveDpiWrite(slot: number, dpi: number): Uint8Array { + assertSlot(slot); + if (!eightBitDoIsValidDpi(dpi)) throw new RangeError(`${dpi} DPI is outside 50-26000 in steps of 50.`); + return encodeMouseWrite(EIGHTBITDO_CMD.activeDpi, [EIGHTBITDO_DPI_STAGE_COUNT, slot, ...le16(dpi)]); +} + +/** One axis of the stage table: ` <6 x dpi u16 LE>`. */ +export function eightBitDoEncodeDpiTableWrite(table: EightBitDoDpiTable): Uint8Array { + if (table.stages.length !== EIGHTBITDO_DPI_STAGE_COUNT) throw new RangeError("8BitDo DPI tables have six stages."); + table.stages.forEach((dpi, i) => { + // A disabled stage may hold 0; every enabled one needs a real value. + const enabled = (table.enabledMask & (1 << i)) !== 0; + if (!(eightBitDoIsValidDpi(dpi) || (!enabled && dpi === 0))) { + throw new RangeError(`${dpi} DPI is outside 50-26000 in steps of 50.`); + } + }); + return encodeMouseWrite(EIGHTBITDO_CMD.dpiTable, [ + table.axis, table.enabledMask & 0x3f, ...table.stages.flatMap(le16), + ]); +} + +/** + * Polling: ` 00 00 00 00 <6 x Hz u16 LE>`. The + * write carries the rates two bytes later than the read does, as the vendor + * tool sends them; the rate list itself is written back unchanged. + */ +export function eightBitDoEncodePollingWrite(polling: EightBitDoPolling, activeIndex: number): Uint8Array { + if (polling.slots.length !== 6) throw new RangeError("8BitDo polling carries six rate slots."); + if (!Number.isInteger(activeIndex) || activeIndex < 0 || activeIndex >= polling.rates.length) { + throw new RangeError("Polling rate index is out of range."); + } + return encodeMouseWrite(EIGHTBITDO_CMD.pollingRate, [ + polling.count, activeIndex, 0, 0, 0, 0, ...polling.slots.flatMap(le16), + ]); +} diff --git a/src/drivers/8bitdo/hid.test.ts b/src/drivers/8bitdo/hid.test.ts new file mode 100644 index 00000000..26ab9bb2 --- /dev/null +++ b/src/drivers/8bitdo/hid.test.ts @@ -0,0 +1,282 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { EightBitDoHidClient } from "./hid.ts"; +import { + EIGHTBITDO_R8_BLUETOOTH_PRODUCT_ID, + EIGHTBITDO_R8_RECEIVER_PRODUCT_ID, + EIGHTBITDO_REPORT_SIZE, + EIGHTBITDO_USAGE, + EIGHTBITDO_USAGE_PAGE, + EIGHTBITDO_VENDOR_ID, +} from "../../8bitdo/index.ts"; + +const frame = (hex: string) => { + const out = new Uint8Array(EIGHTBITDO_REPORT_SIZE); + out.set(hex.trim().split(/\s+/).map((b) => Number.parseInt(b, 16))); + return out; +}; + +// Replies read from a Retro R8 N Edition, keyed by the first four request bytes. +const LINKED: Record = { + "06 03 0a 01": "26 03 0a 11 01", + "01 06 12 01": "01 06 12 11 06 01 b0 04 20 03 b0 04 40 06 60 09 80 0c 00 19", + "01 06 28 01": "01 06 28 11 00 3f 20 03 b0 04 40 06 60 09 80 0c 00 19", + "01 06 0d 01": "01 06 0d 11 05 01 00 00 fa 00 f4 01 e8 03 d0 07 a0 0f", + "01 06 26 01": "01 06 26 11 01", + "01 06 25 01": "01 06 25 11 00 00 00 01", + "06 02 03 01": "26 02 03 11 50 00 10 03 02 50 01 00 0a 25 02 27 17 20 0e 01", + "01 04 04 01": "01 04 04 11 50 00 10 03 01 50 01 00 0b 25 12 30 10 50 03", +}; +/** The receiver acknowledges every mouse request at once, before the mouse answers. */ +const FORWARDED = (request: Uint8Array) => + `21 06 ${request[2]!.toString(16).padStart(2, "0")} 01 ${"00 ".repeat(36)}14`; + +type Listener = (event: HIDInputReportEvent) => void; + +function fakeDevice(options: { + replies?: Record; + silent?: boolean; + usagePage?: number; + productId?: number; +} = {}) { + const sent: Uint8Array[] = []; + const listeners = new Set(); + const emit = (data: Uint8Array) => { + const event = { reportId: 0, data: new DataView(data.buffer) } as unknown as HIDInputReportEvent; + for (const listener of [...listeners]) listener(event); + }; + const device = { + vendorId: EIGHTBITDO_VENDOR_ID, + productId: options.productId ?? EIGHTBITDO_R8_RECEIVER_PRODUCT_ID, + productName: "8BitDo Retro R8 Mouse Adapter", + opened: false, + collections: [ + { usagePage: 0x01, usage: 0x02, featureReports: [], inputReports: [], outputReports: [], children: [] }, + { usagePage: options.usagePage ?? EIGHTBITDO_USAGE_PAGE, usage: EIGHTBITDO_USAGE, featureReports: [], inputReports: [], outputReports: [], children: [] }, + ], + open: async () => { (device as { opened: boolean }).opened = true; }, + close: async () => {}, + addEventListener: (_type: string, listener: Listener) => { listeners.add(listener); }, + removeEventListener: (_type: string, listener: Listener) => { listeners.delete(listener); }, + sendReport: async (_reportId: number, data: Uint8Array) => { + const request = new Uint8Array(data); + sent.push(request); + if (options.silent) return; + const key = [...request.subarray(0, 4)].map((b) => b.toString(16).padStart(2, "0")).join(" "); + const answer = (options.replies ?? LINKED)[key]; + // As on hardware: the receiver's acknowledgement first, then (if the + // mouse answers) its reply a few ms later; plus an unrelated report the + // client must skip. + queueMicrotask(() => { + emit(frame("01 06 7f 11 aa")); + if (request[0] === 0x01) emit(frame(FORWARDED(request))); + // A later microtask, not a timer: the suite collapses timers, the + // driver's timeout included. + if (answer) queueMicrotask(() => emit(frame(answer))); + }); + }, + } as unknown as HIDDevice; + return { device, sent }; +} + +test("isSupported needs 8BitDo's VID, the R8 receiver PID and the 0xFF00 collection", () => { + assert.equal(EightBitDoHidClient.isSupported(fakeDevice().device), true); + assert.equal(EightBitDoHidClient.isSupported(fakeDevice({ usagePage: 0xff0b }).device), false); + assert.equal(EightBitDoHidClient.isSupported(fakeDevice({ productId: EIGHTBITDO_R8_BLUETOOTH_PRODUCT_ID }).device), false); +}); + +test("readStatus reports DPI, stages, polling, lift-off and edition from read-only replies", async () => { + const { device, sent } = fakeDevice(); + const status = await new EightBitDoHidClient(device).readStatus(); + assert.equal(status.brand, "8BitDo"); + assert.equal(status.name, "8BitDo Retro R8 Mouse (N Edition)"); + assert.equal(status.dpi, 1200); + assert.deepEqual(status.dpiStages, [800, 1200, 1600, 2400, 3200, 6400]); + assert.equal(status.activeDpiStage, 1); + assert.equal(status.pollingRateHz, 500); + assert.deepEqual(status.supportedPollingRates, [250, 500, 1000, 2000, 4000]); + assert.equal(status.liftOffDistance, "Low"); + assert.equal(status.batteryPercent, null); + assert.equal(status.connectionType, "Wireless"); + assert.equal(status.ui?.valuesVerified, true); + assert.deepEqual(status.firmware, ["Mouse 11.03", "Receiver 10.14"]); + // Every frame sent is a read (op byte 01) of a known command. + for (const report of sent) { + assert.equal(report.length, 64); + assert.equal(report[3], 0x01); + } + const head = (r: Uint8Array) => [...r.subarray(0, 3)].map((b) => b.toString(16).padStart(2, "0")).join(" "); + assert.deepEqual(sent.map(head), [ + "06 03 0a", "06 02 03", "01 06 12", "01 06 28", "01 06 0d", "01 06 26", "01 06 25", "01 04 04", + ]); +}); + +test("readStatus stops after the receiver queries when the mouse is asleep", async () => { + const { device, sent } = fakeDevice({ replies: { + "06 03 0a 01": "26 03 0a 11", + "06 02 03 01": LINKED["06 02 03 01"]!, + } }); + const status = await new EightBitDoHidClient(device).readStatus(); + // Link and receiver version only: nothing goes over the air. + assert.equal(sent.length, 2); + assert.deepEqual(status.firmware, ["Receiver 10.14"]); + assert.equal(status.dpi, 0); + assert.equal(status.ui?.valuesVerified, false); + assert.match(status.ui?.statusNote ?? "", /asleep/); +}); + +test("a mouse that stops answering leaves the values empty instead of throwing", async () => { + const { device } = fakeDevice({ replies: { "06 03 0a 01": "26 03 0a 11 01" } }); + const status = await new EightBitDoHidClient(device).readStatus(); + assert.equal(status.dpi, 0); + assert.equal(status.dpiStages, undefined); + assert.equal(status.pollingRateHz, 0); + assert.equal(status.ui?.valuesVerified, false); +}); + +test("a receiver that never replies times out", async () => { + const { device } = fakeDevice({ silent: true }); + const status = await new EightBitDoHidClient(device).readStatus(); + assert.equal(status.dpi, 0); + assert.match(status.ui?.statusNote ?? "", /asleep/); +}); + +/** + * A stateful R8 behind its receiver: writes change what later reads return, + * the way the hardware did. Replies: the receiver's ack, then the mouse's + * `01 06 11|14` a microtask later. + */ +function statefulDevice(options: { missReadAfterStageChange?: boolean; missFirstReadOf?: number } = {}) { + const state = { + active: 1, + tables: [[800, 1200, 1600, 2400, 3200, 6400], [800, 1200, 1600, 2400, 3200, 6400]], + rates: [250, 500, 1000, 2000, 4000, 0], + rateIndex: 1, + liftOff: 1, + }; + const le = (v: number) => [v & 0xff, (v >> 8) & 0xff]; + const writes: Uint8Array[] = []; + let missNextActiveRead = false; + let missNextReadOf = options.missFirstReadOf ?? null; + const listeners = new Set(); + const emit = (values: number[]) => { + const data = new Uint8Array(EIGHTBITDO_REPORT_SIZE); + data.set(values); + const event = { reportId: 0, data: new DataView(data.buffer) } as unknown as HIDInputReportEvent; + for (const listener of [...listeners]) listener(event); + }; + const answer = (r: Uint8Array): number[] | null => { + if (r[0] === 0x06) return r[1] === 0x03 && r[2] === 0x0a ? [0x26, 0x03, 0x0a, 0x11, 1] : null; + const [, , cmd, op] = r; + if (op === 0x01) { + if (cmd === missNextReadOf) { + missNextReadOf = null; + return null; + } + if (cmd === 0x12 && missNextActiveRead) { + missNextActiveRead = false; + return null; + } + if (cmd === 0x12) return [1, 6, 0x12, 0x11, 6, state.active, ...le(state.tables[0]![state.active]!), ...state.tables[0]!.flatMap(le)]; + if (cmd === 0x28) return [1, 6, 0x28, 0x11, r[4]!, 0x3f, ...state.tables[r[4]!]!.flatMap(le)]; + if (cmd === 0x0d) return [1, 6, 0x0d, 0x11, 5, state.rateIndex, 0, 0, ...state.rates.flatMap(le)]; + if (cmd === 0x26) return [1, 6, 0x26, 0x11, state.liftOff]; + return null; + } + writes.push(new Uint8Array(r)); + if (cmd === 0x26) state.liftOff = r[4]!; + if (cmd === 0x12) { + state.active = r[5]!; + missNextActiveRead = options.missReadAfterStageChange === true; + } + if (cmd === 0x28) state.tables[r[4]!] = Array.from({ length: 6 }, (_, i) => r[6 + i * 2]! | (r[7 + i * 2]! << 8)); + if (cmd === 0x0d) state.rateIndex = r[5]!; + return [1, 6, cmd!, 0x14]; + }; + const device = { + vendorId: EIGHTBITDO_VENDOR_ID, + productId: EIGHTBITDO_R8_RECEIVER_PRODUCT_ID, + productName: "8BitDo Retro R8 Mouse Adapter", + opened: true, + collections: [{ usagePage: EIGHTBITDO_USAGE_PAGE, usage: EIGHTBITDO_USAGE, featureReports: [], inputReports: [], outputReports: [], children: [] }], + open: async () => {}, + close: async () => {}, + addEventListener: (_type: string, listener: Listener) => { listeners.add(listener); }, + removeEventListener: (_type: string, listener: Listener) => { listeners.delete(listener); }, + sendReport: async (_reportId: number, data: Uint8Array) => { + const request = new Uint8Array(data); + const reply = answer(request); + queueMicrotask(() => { + if (request[0] === 0x01) emit([0x21, 0x06, request[2]!, 0x01]); + if (reply) queueMicrotask(() => emit(reply)); + }); + }, + } as unknown as HIDDevice; + return { device, state, writes }; +} + +const head4 = (r: Uint8Array) => [...r.subarray(0, 4)].map((b) => b.toString(16).padStart(2, "0")).join(" "); + +test("setPollingRate writes the index and reads it back", async () => { + const { device, state, writes } = statefulDevice(); + assert.equal(await new EightBitDoHidClient(device).setPollingRate(1000), 1000); + assert.equal(state.rateIndex, 2); + // The rate list itself is written back unchanged. + assert.deepEqual(state.rates, [250, 500, 1000, 2000, 4000, 0]); + assert.deepEqual(writes.map(head4), ["01 06 0d 04"]); + await assert.rejects(new EightBitDoHidClient(device).setPollingRate(8000), /not supported/); +}); + +test("setActiveDpiStage selects a stage and sends its DPI", async () => { + const { device, state, writes } = statefulDevice(); + assert.equal(await new EightBitDoHidClient(device).setActiveDpiStage(3), 3); + assert.equal(state.active, 3); + assert.equal(head4(writes[0]!), "01 06 12 04"); + assert.deepEqual([...writes[0]!.subarray(4, 8)], [6, 3, 0x60, 0x09]); + await assert.rejects(new EightBitDoHidClient(device).setActiveDpiStage(6), /between 1 and 6/); +}); + +test("setDpiStageValue writes both axes and follows the active stage", async () => { + const { device, state, writes } = statefulDevice(); + const client = new EightBitDoHidClient(device); + // Stage 1 (slot 1) is active, so the active DPI is rewritten too. + assert.equal(await client.setDpiStageValue(1, 1300), 1300); + assert.deepEqual(state.tables, [[800, 1300, 1600, 2400, 3200, 6400], [800, 1300, 1600, 2400, 3200, 6400]]); + assert.deepEqual(writes.map(head4), ["01 06 28 04", "01 06 28 04", "01 06 12 04"]); + await assert.rejects(client.setDpiStageValue(1, 1325), /steps of 50/); +}); + +test("setDpi changes the active stage's DPI", async () => { + const { device, state } = statefulDevice(); + assert.equal(await new EightBitDoHidClient(device).setDpi(1100), 1100); + assert.equal(state.tables[0]![1], 1100); +}); + +test("setLiftOffDistance maps Low and High to levels 1 and 2", async () => { + const { device, state } = statefulDevice(); + const client = new EightBitDoHidClient(device); + assert.equal(await client.setLiftOffDistance("High"), "High"); + assert.equal(state.liftOff, 2); + await assert.rejects(client.setLiftOffDistance("Medium"), /Low and High/); +}); + +test("readStatus enables the settings once the mouse answers", async () => { + const { device } = statefulDevice(); + const status = await new EightBitDoHidClient(device).readStatus(); + assert.equal(status.ui?.settingsReady, true); + assert.equal(status.ui?.dpiStageEditor?.maxDpi, 26000); + assert.equal(status.ui?.hideSingleDpi, true); +}); + +test("readStatus retries a settings read the mouse misses", async () => { + const { device } = statefulDevice({ missFirstReadOf: 0x0d }); + const status = await new EightBitDoHidClient(device).readStatus(); + assert.equal(status.pollingRateHz, 500); + assert.equal(status.ui?.settingsReady, true); +}); + +test("a read the mouse misses right after a stage change is retried", async () => { + const { device, state } = statefulDevice({ missReadAfterStageChange: true }); + assert.equal(await new EightBitDoHidClient(device).setActiveDpiStage(0), 0); + assert.equal(state.active, 0); +}); diff --git a/src/drivers/8bitdo/hid.ts b/src/drivers/8bitdo/hid.ts new file mode 100644 index 00000000..ea68f052 --- /dev/null +++ b/src/drivers/8bitdo/hid.ts @@ -0,0 +1,316 @@ +import type { MouseStatus } from "../mouse-types.ts"; +import { + EIGHTBITDO_CMD, + EIGHTBITDO_DPI_STAGE_COUNT, + EIGHTBITDO_R8_DPI, + EIGHTBITDO_PRODUCT_IDS, + EIGHTBITDO_PRODUCT_NAMES, + EIGHTBITDO_RECEIVER_QUERY, + EIGHTBITDO_REPORT_ID, + EIGHTBITDO_USAGE, + EIGHTBITDO_USAGE_PAGE, + EIGHTBITDO_VENDOR_ID, + eightBitDoDecodeReply, + eightBitDoEncodeActiveDpiWrite, + eightBitDoEncodeDpiTableWrite, + eightBitDoEncodeLiftOffWrite, + eightBitDoEncodePollingWrite, + eightBitDoIsValidDpi, + eightBitDoEnabledStages, + eightBitDoEncodeMouseRead, + eightBitDoEncodeMouseVersionRead, + eightBitDoEncodeReceiverRead, + eightBitDoParseActiveDpi, + eightBitDoParseDpiTable, + eightBitDoParseEdition, + eightBitDoParseFirmwareVersion, + eightBitDoParseLiftOff, + eightBitDoParseLink, + eightBitDoParsePolling, + type EightBitDoDpiTable, +} from "../../8bitdo/index.ts"; + +type LiftOff = NonNullable; + +/** + * The receiver answers within a few ms; the mouse's answer travels over the air + * and reached Bridge's node-hid helper 50–210 ms after the acknowledgement. + */ +const REPLY_TIMEOUT_MS = 1000; +/** + * Right after a stage change the mouse can miss the next read (seen once on a + * Retro R8 while restoring the active stage), so settings reads retry. + */ +const READ_ATTEMPTS = 3; +const READ_RETRY_DELAY_MS = 100; + +/** + * 8BitDo Retro R8 through its 2.4 GHz receiver (see `@openmouse/protocol/8bitdo`). + * Reads link, active DPI, the DPI stage table, polling rate, lift-off, edition + * and firmware versions. Writes the polling rate, the active stage, stage + * values and lift-off with the vendor tool's frames, and reads every write + * back before reporting it. + */ +export class EightBitDoHidClient { + readonly device: HIDDevice; + private queue: Promise = Promise.resolve(); + + constructor(device: HIDDevice) { + this.device = device; + } + + static isSupported(device: HIDDevice): boolean { + if (device.vendorId !== EIGHTBITDO_VENDOR_ID) return false; + if (!EIGHTBITDO_PRODUCT_IDS.includes(device.productId)) return false; + const search = (collection: HIDCollectionInfo): boolean => + (collection.usagePage === EIGHTBITDO_USAGE_PAGE && collection.usage === EIGHTBITDO_USAGE) + || collection.children.some(search); + return device.collections.some(search); + } + + getDpiOptions(): number[] { + const options: number[] = []; + for (let dpi = EIGHTBITDO_R8_DPI.min; dpi <= EIGHTBITDO_R8_DPI.max; dpi += EIGHTBITDO_R8_DPI.step) options.push(dpi); + return options; + } + + async open(): Promise { + if (!this.device.opened) await this.device.open(); + } + + async close(): Promise { + if (this.device.opened) await this.device.close(); + } + + async readStatus(): Promise { + await this.open(); + const name = EIGHTBITDO_PRODUCT_NAMES.get(this.device.productId) ?? "8BitDo mouse"; + const link = await this.request(eightBitDoEncodeReceiverRead(EIGHTBITDO_RECEIVER_QUERY.link)); + const linked = link !== null && eightBitDoParseLink(link); + // The receiver answers this itself, so it is read even while the mouse sleeps. + const receiverVersion = await this.request(eightBitDoEncodeReceiverRead(EIGHTBITDO_RECEIVER_QUERY.version)); + const receiverFirmware = receiverVersion ? eightBitDoParseFirmwareVersion(receiverVersion) : null; + + const base: MouseStatus = { + brand: "8BitDo", + name, + ui: { + family: "8bitdo", + settingsReady: linked, + valuesVerified: false, + hideUnsupportedPollingRates: true, + hideProcessingCard: true, + hideSignalCard: true, + hideSleepCard: true, + defaultDisplayName: name, + dpiStageEditor: { + maxStages: EIGHTBITDO_DPI_STAGE_COUNT, + countEditable: false, + minDpi: EIGHTBITDO_R8_DPI.min, + maxDpi: EIGHTBITDO_R8_DPI.max, + stepDpi: EIGHTBITDO_R8_DPI.step, + }, + // The R8 has no DPI outside its six stages (setDpi edits the active + // one), so the panel offers the stage editor alone. + hideSingleDpi: true, + statusNote: linked + ? "The receiver does not report the battery; over Bluetooth the system shows it." + : "The receiver is connected but the mouse is asleep or switched off. Move it to wake it.", + }, + batteryPercent: null, + batteryState: "Unknown", + dpi: 0, + pollingRateHz: 0, + activeProfile: null, + liftOffDistance: null, + connectionType: "Wireless", + connectionDetail: "2.4 GHz receiver", + firmware: receiverFirmware ? [`Receiver ${receiverFirmware}`] : [], + }; + if (!linked) return base; + + // The mouse sometimes misses the first read after a write, and the panel + // reads the status right after each one, so the values it checks retry. + const active = await this.readMouseRetrying(EIGHTBITDO_CMD.activeDpi); + const table = await this.readMouseRetrying(EIGHTBITDO_CMD.dpiTable, [0]); + const polling = await this.readMouseRetrying(EIGHTBITDO_CMD.pollingRate); + const liftOff = await this.readMouseRetrying(EIGHTBITDO_CMD.liftOff); + const edition = await this.readMouse(EIGHTBITDO_CMD.edition); + const mouseVersion = await this.request(eightBitDoEncodeMouseVersionRead()); + + const activeDpi = active ? eightBitDoParseActiveDpi(active) : null; + const dpiTable = table ? eightBitDoParseDpiTable(table) : null; + const pollingRate = polling ? eightBitDoParsePolling(polling) : null; + const liftOffLevel = liftOff ? eightBitDoParseLiftOff(liftOff) : null; + const editionName = edition ? eightBitDoParseEdition(edition) : null; + const mouseFirmware = mouseVersion ? eightBitDoParseFirmwareVersion(mouseVersion) : null; + const stages = dpiTable ? eightBitDoEnabledStages(dpiTable) : []; + // The mouse counts its active stage over all six slots; dpiStages lists + // only the enabled ones. + const enabledSlots = dpiTable + ? dpiTable.stages.map((_, i) => i).filter((i) => dpiTable.stages[i]! > 0 && (dpiTable.enabledMask & (1 << i)) !== 0) + : []; + const activeDpiStage = activeDpi ? enabledSlots.indexOf(activeDpi.activeStage) : -1; + + return { + ...base, + name: editionName ? `${name} (${editionName})` : name, + ui: { + ...base.ui, + valuesVerified: activeDpi !== null && pollingRate !== null, + settingsReady: activeDpi !== null && dpiTable !== null && pollingRate !== null, + }, + dpi: activeDpi?.dpi ?? 0, + ...(stages.length > 0 ? { dpiStages: stages } : {}), + ...(activeDpiStage >= 0 ? { activeDpiStage } : {}), + pollingRateHz: pollingRate?.rateHz ?? 0, + ...(pollingRate ? { supportedPollingRates: pollingRate.rates } : {}), + liftOffDistance: liftOffLevel === 1 ? "Low" : liftOffLevel === 2 ? "High" : null, + supportedLiftOffDistances: ["Low", "High"], + // "Mouse …" first: it is the version that matters for updates. + firmware: [...(mouseFirmware ? [`Mouse ${mouseFirmware}`] : []), ...base.firmware], + }; + } + + async setPollingRate(pollingRateHz: number): Promise { + const polling = await this.readPolling(); + const index = polling.rates.indexOf(pollingRateHz); + if (index < 0) throw new Error(`${pollingRateHz} Hz is not supported; the mouse offers ${polling.rates.join(", ")} Hz.`); + await this.write(eightBitDoEncodePollingWrite(polling, index), "polling rate"); + const confirmed = await this.readPolling(); + if (confirmed.rateHz !== pollingRateHz) throw new Error(`The mouse kept ${confirmed.rateHz} Hz instead of ${pollingRateHz} Hz.`); + return confirmed.rateHz; + } + + async setLiftOffDistance(liftOffDistance: LiftOff): Promise { + const level = liftOffDistance === "Low" ? 1 : liftOffDistance === "High" ? 2 : null; + if (level === null) throw new Error(`${liftOffDistance} lift-off is not available; the R8 offers Low and High.`); + await this.write(eightBitDoEncodeLiftOffWrite(level), "lift-off"); + const payload = await this.readMouseRetrying(EIGHTBITDO_CMD.liftOff); + const confirmed = payload ? eightBitDoParseLiftOff(payload) : null; + if (confirmed !== level) throw new Error("The mouse did not keep the new lift-off distance."); + return liftOffDistance; + } + + /** Selects the active stage, 0-based over the enabled stages (as `dpiStages` lists them). */ + async setActiveDpiStage(stage: number): Promise { + const table = await this.readTable(0); + const slot = this.slotOf(table, stage); + await this.write(eightBitDoEncodeActiveDpiWrite(slot, table.stages[slot]!), "active DPI stage"); + const active = await this.readActive(); + if (active.activeStage !== slot) throw new Error("The mouse did not switch to the new DPI stage."); + return stage; + } + + /** Sets one stage's DPI on both axes; the active DPI follows when it is that stage. */ + async setDpiStageValue(stage: number, dpi: number): Promise { + if (!eightBitDoIsValidDpi(dpi)) { + throw new Error(`DPI must be ${EIGHTBITDO_R8_DPI.min}-${EIGHTBITDO_R8_DPI.max} in steps of ${EIGHTBITDO_R8_DPI.step}.`); + } + const tableX = await this.readTable(0); + const tableY = await this.readTable(1); + const slot = this.slotOf(tableX, stage); + for (const table of [tableX, tableY]) { + const stages = [...table.stages]; + stages[slot] = dpi; + await this.write(eightBitDoEncodeDpiTableWrite({ ...table, stages }), "DPI stage"); + } + const active = await this.readActive(); + if (active.activeStage === slot) await this.write(eightBitDoEncodeActiveDpiWrite(slot, dpi), "active DPI"); + const confirmed = await this.readTable(0); + if (confirmed.stages[slot] !== dpi) throw new Error(`The mouse kept ${confirmed.stages[slot]} DPI instead of ${dpi}.`); + return dpi; + } + + /** Changes the DPI of the active stage. */ + async setDpi(dpi: number): Promise { + const table = await this.readTable(0); + const active = await this.readActive(); + const stage = this.enabledSlots(table).indexOf(active.activeStage); + if (stage < 0) throw new Error("The active DPI stage is not one of the enabled stages."); + return await this.setDpiStageValue(stage, dpi); + } + + private enabledSlots(table: EightBitDoDpiTable): number[] { + return table.stages.map((_, i) => i).filter((i) => table.stages[i]! > 0 && (table.enabledMask & (1 << i)) !== 0); + } + + private slotOf(table: EightBitDoDpiTable, stage: number): number { + const slots = this.enabledSlots(table); + const slot = Number.isInteger(stage) ? slots[stage] : undefined; + if (slot === undefined) throw new Error(`DPI stage must be between 1 and ${slots.length}.`); + return slot; + } + + /** A settings read that retries when the mouse does not answer. */ + private async readMouseRetrying( + command: (typeof EIGHTBITDO_CMD)[keyof typeof EIGHTBITDO_CMD], + args: readonly number[] = [], + ): Promise { + for (let attempt = 1; attempt <= READ_ATTEMPTS; attempt += 1) { + const payload = await this.readMouse(command, args); + if (payload) return payload; + if (attempt < READ_ATTEMPTS) await new Promise((resolve) => setTimeout(resolve, READ_RETRY_DELAY_MS)); + } + return null; + } + + private async readTable(axis: 0 | 1): Promise { + const payload = await this.readMouseRetrying(EIGHTBITDO_CMD.dpiTable, [axis]); + const table = payload ? eightBitDoParseDpiTable(payload) : null; + if (!table || table.axis !== axis) throw new Error("The mouse did not report its DPI stages. Move it to wake it and try again."); + return table; + } + + private async readActive() { + const payload = await this.readMouseRetrying(EIGHTBITDO_CMD.activeDpi); + const active = payload ? eightBitDoParseActiveDpi(payload) : null; + if (!active) throw new Error("The mouse did not report its active DPI. Move it to wake it and try again."); + return active; + } + + private async readPolling() { + const payload = await this.readMouseRetrying(EIGHTBITDO_CMD.pollingRate); + const polling = payload ? eightBitDoParsePolling(payload) : null; + if (!polling) throw new Error("The mouse did not report its polling rate. Move it to wake it and try again."); + return polling; + } + + /** Sends one write and requires the mouse's `01 06 14` confirmation. */ + private async write(report: Uint8Array, what: string): Promise { + if ((await this.request(report)) === null) throw new Error(`The mouse did not confirm the ${what} change.`); + } + + private readMouse(command: (typeof EIGHTBITDO_CMD)[keyof typeof EIGHTBITDO_CMD], args: readonly number[] = []): Promise { + return this.request(eightBitDoEncodeMouseRead(command, args)); + } + + /** + * Sends one report and resolves with the payload of the reply that matches + * it, or null on a send failure or a timeout. The receiver's immediate + * `21 06 ` acknowledgement is skipped like any other unrelated report: + * the mouse's reply follows it a few ms later, or never when it is asleep. + * Requests run one at a time so replies cannot be confused. + */ + private request(report: Uint8Array): Promise { + const run = this.queue.then(() => new Promise((resolve) => { + let timer: ReturnType | undefined; + const finish = (value: Uint8Array | null) => { + if (timer !== undefined) clearTimeout(timer); + this.device.removeEventListener("inputreport", onReport); + resolve(value); + }; + const onReport = (event: HIDInputReportEvent) => { + if (event.reportId !== EIGHTBITDO_REPORT_ID) return; + const bytes = new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength); + const payload = eightBitDoDecodeReply(bytes, report); + if (payload) finish(new Uint8Array(payload)); + }; + this.device.addEventListener("inputreport", onReport); + timer = setTimeout(() => finish(null), REPLY_TIMEOUT_MS); + this.device.sendReport(EIGHTBITDO_REPORT_ID, report).catch(() => finish(null)); + })); + this.queue = run.catch(() => undefined); + return run; + } +} diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index bb9d577a..3abc4861 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -259,7 +259,7 @@ export interface MouseStatus { dynamicDpi: KeychronDynamicDpi | null; factoryReset: boolean; }; - brand: "RAWM" | "Motospeed" | "Logitech" | "Pulsar" | "Endgame Gear" | "WLMouse" | "G-Wolves" | "Lamzu" | "CRDRAKO" | "Attack Shark" | "LunaFury" | "Vancer" | "Orbital" | "Razer" | "Teevolution" | "ATK" | "VXE" | "VGN" | "VAXEE" | "Finalmouse" | "Keychron" | "moddoMOUSE" | "Ninjutso" | "Zaunkoenig" | "Fantech" | "Wooting" | "WALLHACK" | "SteelSeries" | "Glorious" | "MCHOSE" | "K-snake" | "Noir Gear" | "Lingbao" | "GearHub" | "AJAZZ" | "Corsair" | "Microsoft" | "Dareu" | "Redragon" | "UtechSmart" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "AULA" | "Sades" | "Xiaomi" | "LEOBOG" | "Kmart" | "Cosmic Byte" | "Fallen" | "Zaopin"; + brand: "RAWM" | "Motospeed" | "Logitech" | "Pulsar" | "Endgame Gear" | "WLMouse" | "G-Wolves" | "Lamzu" | "CRDRAKO" | "Attack Shark" | "LunaFury" | "Vancer" | "Orbital" | "Razer" | "Teevolution" | "ATK" | "VXE" | "VGN" | "VAXEE" | "Finalmouse" | "Keychron" | "moddoMOUSE" | "Ninjutso" | "Zaunkoenig" | "Fantech" | "Wooting" | "WALLHACK" | "SteelSeries" | "Glorious" | "MCHOSE" | "K-snake" | "Noir Gear" | "Lingbao" | "GearHub" | "AJAZZ" | "Corsair" | "Microsoft" | "Dareu" | "Redragon" | "UtechSmart" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "AULA" | "Sades" | "Xiaomi" | "LEOBOG" | "Kmart" | "Cosmic Byte" | "Fallen" | "Zaopin" | "8BitDo"; name: string; /** Optional LunaFury controls, populated only after successful device reads. */ lunafury?: import("../lamzu/lunafury.js").LunaFurySettings; diff --git a/src/drivers/registry.test.ts b/src/drivers/registry.test.ts index b8e247ff..e6a76bd1 100644 --- a/src/drivers/registry.test.ts +++ b/src/drivers/registry.test.ts @@ -24,6 +24,7 @@ import { } from "@openmouse/protocol/delux"; import { COOLERMASTER_PRODUCT_IDS } from "@openmouse/protocol/coolermaster"; import { KMART_PRODUCT_IDS, KMART_USAGE, KMART_USAGE_PAGE, KMART_VENDOR_ID } from "@openmouse/protocol/kmart"; +import { EIGHTBITDO_PRODUCT_IDS, EIGHTBITDO_USAGE, EIGHTBITDO_USAGE_PAGE, EIGHTBITDO_VENDOR_ID } from "../8bitdo/index.ts"; import { REDGEAR_X13_VENDOR_ID, REDGEAR_X13_PRODUCT_ID, @@ -86,6 +87,16 @@ test("Kmart picker filters use the protocol identity constants", () => { ); }); +test("8BitDo picker filters ask for the receiver's vendor collection only", () => { + assert.equal(VENDOR_ID.eightBitDo, EIGHTBITDO_VENDOR_ID); + assert.deepEqual( + SUPPORTED_HID_FILTERS.filter((filter) => filter.vendorId === EIGHTBITDO_VENDOR_ID), + EIGHTBITDO_PRODUCT_IDS.map((productId) => ({ + vendorId: EIGHTBITDO_VENDOR_ID, productId, usagePage: EIGHTBITDO_USAGE_PAGE, usage: EIGHTBITDO_USAGE, + })), + ); +}); + const DEVICES_DIR = dirname(fileURLToPath(import.meta.url)); const REPORT_IDS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 0x09, 0x0e, 0x0f, 0x10, 0x11, 0x20, 0x51, 0xa1, 0xb3, 0xb4, 0xb5]; diff --git a/src/drivers/registry.ts b/src/drivers/registry.ts index da9b9eba..1772e249 100644 --- a/src/drivers/registry.ts +++ b/src/drivers/registry.ts @@ -39,6 +39,7 @@ import { RazerViperV4ProHidClient } from "./razer/viper-v4-pro-hid.ts"; import { TeevolutionHidClient } from "./teevolution/hid.ts"; import { VgnF2HidClient } from "./vgn/hid.ts"; import { KmartHidClient } from "./kmart/hid.ts"; +import { EightBitDoHidClient } from "./8bitdo/hid.ts"; import { VaxeeHidClient } from "./vaxee/hid.ts"; import { WallhackKeyboardHidClient } from "./wallhack/keyboard-hid.ts"; import { WallhackMouseHidClient } from "./wallhack/mouse-hid.ts"; @@ -114,7 +115,7 @@ import { InstantA825HidClient } from "./instant/a825-hid.ts"; import { XiaomiHidClient } from "./xiaomi/hid.ts"; export type PulsarClient = PulsarHidClient | PulsarProHidClient | PulsarXs1HidClient; -export type SupportedClient = RawmHidClient | MotospeedHidClient | LogitechHidppClient | PulsarClient | EggOp1HidClient | EggOtHidClient | EggWeHidClient | FinalmouseHidClient | WLMouseHidClient | WLMouseBeastX4kHidClient | LamzuHidClient | LamzuAtlantisHidClient | OrbitalHidClient | RazerHidClient | RazerViperHidClient | RazerViperMiniHidClient | RazerViperV4ProHidClient | RazerCobraHidClient | TeevolutionHidClient | AtkHidClient | AtkBitmouseHidClient | VgnF2HidClient | VaxeeHidClient | Keychron8kHidClient | Keychron1kHidClient | Keychron4kHidClient | Keychron8kNordicHidClient | KeychronNapeHidClient | ModdoHidClient | NinjutsoHidClient | ZaunkoenigHidClient | CorsairHidClient | CorsairBragiHidClient | AttackSharkHidClient | AttackSharkCompxHidClient | FantechHidClient | GearHubHidClient | WootingHidClient | WallhackMouseHidClient | WallhackKeyboardHidClient | GWolvesHidClient | GWolvesXviHidClient | GWolvesXviNewHidClient | SteelSeriesRival3HidClient | SteelSeriesAerox3HidClient | SteelSeriesAerox3WirelessHidClient | SteelSeriesRival3WirelessHidClient | SteelSeriesAerox5HidClient | SteelSeriesAerox5WirelessHidClient | SteelSeriesRival650HidClient | SteelSeriesAerox9WirelessHidClient | SteelSeriesRival310HidClient | SteelSeriesPrimePlusHidClient | SteelSeriesPrimeMiniWirelessHidClient | SteelSeriesSenseiTenHidClient | SteelSeriesSenseiRivalProHidClient | SteelSeriesSensei310HidClient | SteelSeriesPrimeMiniHidClient | SteelSeriesRival5HidClient | SteelSeriesRival3Gen2HidClient | SteelSeriesRival3WirelessV2HidClient | SteelSeriesAerox3WirelessGen2HidClient | SteelSeriesRival600HidClient | SteelSeriesRival100HidClient | SteelSeriesRival110HidClient | SteelSeriesRival300HidClient | SteelSeriesSenseiRawHidClient | GloriousHidClient | GloriousClassicHidClient | GloriousCore2HidClient | GloriousSinowealthHidClient | MchoseHidClient | MchoseDockHidClient | MchoseA5ProMaxHidClient | KsnakeHidClient | MicrosoftHidClient | DareuHidClient | RedragonHidClient | UtechsmartVenusHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | ZaopinHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient | InstantA825HidClient | XiaomiHidClient | LeobogGm3HidClient | Sinowealth520HidClient | KmartHidClient; +export type SupportedClient = RawmHidClient | MotospeedHidClient | LogitechHidppClient | PulsarClient | EggOp1HidClient | EggOtHidClient | EggWeHidClient | FinalmouseHidClient | WLMouseHidClient | WLMouseBeastX4kHidClient | LamzuHidClient | LamzuAtlantisHidClient | OrbitalHidClient | RazerHidClient | RazerViperHidClient | RazerViperMiniHidClient | RazerViperV4ProHidClient | RazerCobraHidClient | TeevolutionHidClient | AtkHidClient | AtkBitmouseHidClient | VgnF2HidClient | VaxeeHidClient | Keychron8kHidClient | Keychron1kHidClient | Keychron4kHidClient | Keychron8kNordicHidClient | KeychronNapeHidClient | ModdoHidClient | NinjutsoHidClient | ZaunkoenigHidClient | CorsairHidClient | CorsairBragiHidClient | AttackSharkHidClient | AttackSharkCompxHidClient | FantechHidClient | GearHubHidClient | WootingHidClient | WallhackMouseHidClient | WallhackKeyboardHidClient | GWolvesHidClient | GWolvesXviHidClient | GWolvesXviNewHidClient | SteelSeriesRival3HidClient | SteelSeriesAerox3HidClient | SteelSeriesAerox3WirelessHidClient | SteelSeriesRival3WirelessHidClient | SteelSeriesAerox5HidClient | SteelSeriesAerox5WirelessHidClient | SteelSeriesRival650HidClient | SteelSeriesAerox9WirelessHidClient | SteelSeriesRival310HidClient | SteelSeriesPrimePlusHidClient | SteelSeriesPrimeMiniWirelessHidClient | SteelSeriesSenseiTenHidClient | SteelSeriesSenseiRivalProHidClient | SteelSeriesSensei310HidClient | SteelSeriesPrimeMiniHidClient | SteelSeriesRival5HidClient | SteelSeriesRival3Gen2HidClient | SteelSeriesRival3WirelessV2HidClient | SteelSeriesAerox3WirelessGen2HidClient | SteelSeriesRival600HidClient | SteelSeriesRival100HidClient | SteelSeriesRival110HidClient | SteelSeriesRival300HidClient | SteelSeriesSenseiRawHidClient | GloriousHidClient | GloriousClassicHidClient | GloriousCore2HidClient | GloriousSinowealthHidClient | MchoseHidClient | MchoseDockHidClient | MchoseA5ProMaxHidClient | KsnakeHidClient | MicrosoftHidClient | DareuHidClient | RedragonHidClient | UtechsmartVenusHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | ZaopinHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient | InstantA825HidClient | XiaomiHidClient | LeobogGm3HidClient | Sinowealth520HidClient | KmartHidClient | EightBitDoHidClient; export interface DeviceDriver { brand: string; supports(device: HIDDevice): boolean; @@ -171,6 +172,8 @@ export const DEVICE_DRIVERS: readonly DeviceDriver[] = [ { brand: "VAXEE", supports: (device) => VaxeeHidClient.isSupported(device), create: (device) => new VaxeeHidClient(device), score: () => 7 }, // XCTECH 0x248a (Kmart 43499755 / Delux M800 Pro): PIDs 0x5b2e/0x5b2f with the 0xff00 report-0x0c collection. { brand: "Kmart", supports: (device) => KmartHidClient.isSupported(device), create: (device) => new KmartHidClient(device), score: () => 7 }, + // 8BitDo Retro R8 receiver (2dc8:5206), its 0xFF00/0x01 vendor collection; read-only. + { brand: "8BitDo", supports: (device) => EightBitDoHidClient.isSupported(device), create: (device) => new EightBitDoHidClient(device), score: () => 7 }, { brand: "Logitech", supports: (device) => LogitechHidppClient.isSupported(device), create: (device) => new LogitechHidppClient(device), score: (device) => LogitechHidppClient.supportScore(device) }, { brand: "WLMouse", supports: (device) => WLMouseBeastX4kHidClient.isSupported(device), create: (device) => new WLMouseBeastX4kHidClient(device), score: () => 6 }, { brand: "WLMouse", supports: (device) => WLMouseHidClient.isSupported(device), create: (device) => new WLMouseHidClient(device), score: () => 5 }, diff --git a/src/drivers/vendors.ts b/src/drivers/vendors.ts index 079e9bcd..c8c03ba8 100644 --- a/src/drivers/vendors.ts +++ b/src/drivers/vendors.ts @@ -29,6 +29,7 @@ import { GLORIOUS_SINOWEALTH_PRODUCTS } from "../glorious-sinowealth/index.ts"; import { EGG_WE_HID_FILTERS } from "./endgame/egg-we-control.ts"; import { HITSCAN_PRODUCTS, HITSCAN_VENDOR_ID, HITSCAN_XVI_PRODUCTS } from "@openmouse/protocol/hitscan"; import { KMART_PRODUCT_IDS, KMART_USAGE, KMART_USAGE_PAGE, KMART_VENDOR_ID } from "@openmouse/protocol/kmart"; +import { EIGHTBITDO_PRODUCT_IDS, EIGHTBITDO_USAGE, EIGHTBITDO_USAGE_PAGE, EIGHTBITDO_VENDOR_ID } from "../8bitdo/index.ts"; import { VAXEE_PRODUCT_IDS, VAXEE_USAGE, VAXEE_USAGE_PAGE, VAXEE_VENDOR_ID } from "@openmouse/protocol/vaxee"; import { GEARHUB_BLUETOOTH_USAGE, @@ -207,6 +208,7 @@ export const VENDOR_ID = { ajazz: 0x1a2c, vaxee: VAXEE_VENDOR_ID, kmart: KMART_VENDOR_ID, + eightBitDo: EIGHTBITDO_VENDOR_ID, asus: ASUS_VENDOR_ID, ryunix: RYUNIX_VENDOR_ID, // Amkette's XS series shares the 0x04F3 OEM firmware and IDs with Ryunix; the @@ -1030,6 +1032,11 @@ export const KMART_HID_FILTERS: HIDDeviceFilter[] = KMART_PRODUCT_IDS.map((produ vendorId: KMART_VENDOR_ID, productId, usagePage: KMART_USAGE_PAGE, usage: KMART_USAGE, })); +/** 8BitDo Retro R8 receiver: its 0xFF00 vendor collection only, never the mouse/keyboard ones. */ +export const EIGHTBITDO_HID_FILTERS: HIDDeviceFilter[] = EIGHTBITDO_PRODUCT_IDS.map((productId) => ({ + vendorId: EIGHTBITDO_VENDOR_ID, productId, usagePage: EIGHTBITDO_USAGE_PAGE, usage: EIGHTBITDO_USAGE, +})); + /** * Xiaomi Mi Gaming Mouse, wired (0x5009) and wireless (0x500b). No HID * descriptor has been captured, so the usage page is unknown; the driver @@ -1058,6 +1065,7 @@ export const SUPPORTED_HID_FILTERS: HIDDeviceFilter[] = [ })), ...VAXEE_HID_FILTERS, ...KMART_HID_FILTERS, + ...EIGHTBITDO_HID_FILTERS, ...ASUS_HID_FILTERS, ...DAREU_HID_FILTERS, ...REDRAGON_HID_FILTERS, diff --git a/src/index.ts b/src/index.ts index f4fbab1b..b4095a73 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,6 +34,7 @@ export * as ksnake from "./ksnake/index.js"; export * as hyperx from "./hyperx/index.js"; export * as valkyrie from "./valkyrie/index.js"; export * as kmart from "./kmart/index.js"; +export * as eightBitDo from "./8bitdo/index.js"; export * as vaxee from "./vaxee/index.js"; export * as incott from "./incott/index.js"; export * as instant from "./instant/index.js";