Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 50 additions & 26 deletions native-hid/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,46 @@ duplicated or reimplemented here.

## How dispatch works

`brands.mjs` maps a `MouseStatus.brand` string (Bridge's saved profile
`device.id` is `"<brand>:<name>"`, matching what the OpenMouse web app
writes) to that brand's HID vendor id(s) and its candidate driver class(es),
in the same order `mouse-protocol/src/drivers/registry.ts` tries them.

`apply.mjs` doesn't replicate WebHID's report-descriptor-based
`isSupported()` auto-detection (this adapter reports `collections: []` —
real report-descriptor parsing isn't implemented). Instead, since Bridge
already knows the brand from the saved profile, it opens each HID interface
for that brand's vendor id(s) and tries each candidate class directly:
`client.open()` then `client.readStatus()` — a cheap, read-only call every
`SupportedClient` implements — as a probe. The first class that doesn't
throw is treated as correct, and `setDpi()`/`setPollingRate()` are called on
it.
Drivers are chosen the way the control panel chooses them: by
`@openmouse/protocol`'s own registry (`DEVICE_DRIVERS`, first `supports()`
match wins), so every brand the panel supports is covered, and a new brand
in the protocol package needs no change here.

The registry's `supports()` checks need what WebHID gives the panel: each
device's collections, parsed from its report descriptors. node-hid cannot
read descriptors, so Bridge does it (`describe_devices` in `src/hid.rs`, the
same grouping and parser as the panel's own Bridge transport) and sends the
described devices with each request:

1. Once per run, Bridge asks for the registry's `SUPPORTED_HID_FILTERS`
(`{"action": "filters"}`), the filters the panel requests devices with.
Bridge only ever opens a device one of them matches, and only to read its
descriptors, so hardware that shares a mouse maker's chip vendor id (a
motherboard's RGB controller, a touchpad) is never touched.
2. When the devices on the bus change, Bridge asks which brand the registry
files each under (`{"action": "identify", "devices": [...]}`). Those are
the mice it lists.
3. A status or apply request carries the described devices of that brand
(`"devices": [...]`). `registry.mjs` builds the registry's client for each
on a `DescribedDeviceAdapter`, which sends a report down only the
collection whose descriptor declares it, padded to the declared size as
Chrome does (Windows refuses a feature report of any other length), and
reads feature reports at their declared size. `client.open()` then
`client.readStatus()` — a cheap, read-only call every `SupportedClient`
implements — probe it before anything is written. When a profile's brand
is not the one the registry files its mouse under (`"Attack Shark"` saved
for hardware filed as `"Delux"`), Bridge sends `"matchStatusBrand": true`
and every supported device, and the helper keeps the one whose status
reports the brand.

For a status read, `select-client.mjs` prefers a device whose status includes
a battery, so a receiver's battery-less interfaces never hide the mouse's.
Settings writes take the first device that answers.

Without `devices` in the request (Node.js could not load the registry, or
Zaunkoenig's acknowledged automation, which identifies its endpoint by
node-hid path), the helper falls back to `brands.mjs`: a brand's vendor ids
and candidate classes, every interface tried in turn.

The Attack Shark X11 family is the partial exception. Its settings channel is not
visible through WebHID, so `apply.mjs` first checks for VID `0x1d57`, PIDs
Expand All @@ -48,12 +74,10 @@ fall through to the generic `AttackSharkHidClient` path, which drives the 0x04
six-stage table for model `0x55` (mouse-protocol #174), preserving the stages
the request does not touch.

A brand entry can also narrow which interfaces are opened: `productIds` keeps
only its own products on a shared vendor id, and `usagePage` opens only an
interface's collections on that page. The Scyrox entry uses both: CompX's
vendor id `0x3554` carries several brands, and the Scyrox V8's dongle stops
answering on its `0xff02` config collection on Windows while its sibling
vendor collections are open and read.
The Scyrox V8's dongle stops answering on its `0xff02` config collection on
Windows while its sibling vendor collections are open and read, so only that
collection is opened for Scyrox (`ONLY_USAGE_PAGE` in `registry.mjs`, and the
`usagePage` of its `brands.mjs` entry for the fallback).

## Button listener

Expand Down Expand Up @@ -122,9 +146,9 @@ runtime first and falls back to `node` on `PATH`, so local development
read 1,600 DPI and 2,000 Hz, while one on every interface-1 collection got
no answer. The full `apply.mjs` path still needs a run on that mouse, and
an `@openmouse/protocol` release with the V8 in its Scyrox catalog.
- Other adapter and dispatch paths are structurally tested (module resolution,
exit codes and control flow) and still require validation on their respective
hardware.
- G-Wolves is deliberately left out of `brands.mjs`: it isn't a finished,
exported driver in `mouse-protocol` yet (untracked source, no
`package.json` export, no `registry.ts` entry as of this writing).
- The registry path was hardware-verified on Windows with a Keychron G6 HE
8K on its TurboLink 8K receiver (battery, DPI and polling read), an Endgame
Gear OP1 8k (DPI and polling read; its `0xa0` config report comes back with
`0x00` in the id slot), and a Wooting 60HE+ (identified and read).
- Other brands are covered by the registry's own `supports()` checks and the
adapter's tests, and still require validation on their hardware.
45 changes: 38 additions & 7 deletions native-hid/src/apply.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import { BRAND_DRIVERS, brandKey } from "./brands.mjs";
import { applyX11PollingRate, x11DeviceInfos } from "./attack-shark-x11.mjs";
import { candidateDevices, probeVerifiedDevice } from "./hid-device-adapter.mjs";
import { selectClient } from "./select-client.mjs";
import { identify, knowsBrand, loadRegistry, registryPairs } from "./registry.mjs";
import { devices } from "node-hid";
import { automate } from "./automation.mjs";

Expand Down Expand Up @@ -69,15 +70,18 @@ function withTimeout(promise, ms, label) {
* the device) on any failure, so the caller can move on to the next
* candidate. */
async function probe(device, candidate) {
const module = await import(candidate.module);
const Client = module[candidate.exportName];
const client = new Client(device);
// Registry candidates come with their client built; brands.mjs ones name a
// class to import.
const client = candidate.client ?? new (await import(candidate.module))[candidate.exportName](device);
try {
await withTimeout(client.open(), PROBE_TIMEOUT_MS, `${candidate.exportName}.open()`);
// Every SupportedClient implements readStatus() (mouse-protocol's
// shared client contract) — a cheap, read-only way to confirm this is
// really the right class for this interface before writing anything.
const status = await withTimeout(client.readStatus(), PROBE_TIMEOUT_MS, `${candidate.exportName}.readStatus()`);
if (candidate.requireBrand !== undefined && brandKey(status?.brand ?? "") !== candidate.requireBrand) {
throw new Error(`reports itself as ${status?.brand ?? "an unknown brand"}`);
}
return { client, status };
} catch (error) {
await device.close().catch(() => undefined);
Expand All @@ -87,6 +91,23 @@ async function probe(device, candidate) {

async function main() {
const input = JSON.parse(await readStdin());

// ── Device registry ─────────────────────────────────────────────────
// Bridge asks once for the filters that decide which devices it may open,
// then, whenever the devices on the bus change, which brand the registry
// files each of them under.
if (input.action === "filters") {
const { filters } = await loadRegistry();
process.stdout.write(JSON.stringify({ filters }));
process.exit(EXIT_APPLIED);
}
if (input.action === "identify") {
const { drivers } = await loadRegistry();
const described = Array.isArray(input.devices) ? input.devices : [];
process.stdout.write(JSON.stringify({ devices: identify(drivers, described) }));
process.exit(EXIT_APPLIED);
}

const brand = typeof input.brand === "string" ? input.brand : "";
const normalizedBrand = brandKey(brand);
const entry = BRAND_DRIVERS[normalizedBrand];
Expand All @@ -98,7 +119,11 @@ async function main() {
process.stdout.write(JSON.stringify(reply));
process.exit(EXIT_APPLIED);
}
if (!entry) {
// With `devices`, Bridge described the bus and the registry picks the
// driver; without them (an older request shape) brands.mjs does.
const registry = Array.isArray(input.devices) ? await loadRegistry() : null;
const knownBrand = registry ? knowsBrand(registry.drivers, brand) || Boolean(entry) : Boolean(entry);
if (!knownBrand && !input.matchStatusBrand) {
console.error(`[native-hid] no driver registered for brand "${brand}"`);
process.exit(EXIT_NO_DRIVER);
}
Expand All @@ -116,11 +141,17 @@ async function main() {
}
}

const pairs = entry.vendorIds.flatMap((vendorId) =>
candidateDevices(vendorId, entry).flatMap((device) => entry.classes.map((candidate) => ({ device, candidate }))),
);
const pairs = registry
? registryPairs(registry.drivers, input.devices, brand, { matchStatusBrand: input.matchStatusBrand === true })
: entry.vendorIds.flatMap((vendorId) =>
candidateDevices(vendorId, entry).flatMap((device) => entry.classes.map((candidate) => ({ device, candidate }))),
);
const { client, status, attempts } = await selectClient(pairs, probe, { preferBattery: input.action === "status" });

if (!client && !knownBrand) {
console.error(`[native-hid] no device reports itself as ${brand}.`);
process.exit(EXIT_NO_DRIVER);
}
if (!client) {
console.error(
`[native-hid] no ${brand} device answered.` + (attempts.length ? ` Tried:\n ${attempts.join("\n ")}` : " No matching HID interface was found."),
Expand Down
16 changes: 8 additions & 8 deletions native-hid/src/brands.mjs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
// The fallback dispatch table. Bridge normally sends the devices it described
// and the protocol package's own registry picks the driver (registry.mjs); this
// table is used only for a request without them — when the registry could not
// be loaded, and for Zaunkoenig's acknowledged automation (automation.mjs).
//
// Maps a MouseStatus `brand` string (mouse-protocol/src/drivers/mouse-types.ts)
// to the HID vendor id(s) to enumerate and the candidate driver classes to
// try constructing against each interface found, in the same order
// mouse-protocol/src/drivers/registry.ts's DEVICE_DRIVERS lists them for
// that brand (first-match-wins there; here, first class whose open() +
// readStatus() probe succeeds wins — see apply.mjs).
//
// Deliberately excluded:
// - "Pulsar": Bridge has a dependency-free native Rust driver for it
// (src/drivers/pulsar.rs) that claims the brand before this helper is ever
// invoked — see src/drivers/mod.rs.
// - G-Wolves: not yet a finished, exported driver in the local mouse-protocol
// checkout (untracked src/g-wolves/, src/drivers/g-wolves/, no package.json
// export or registry.ts entry as of this writing) — add it here once it
// ships upstream.
// "Pulsar" is left out: Bridge has a dependency-free native Rust driver for it
// (src/drivers/pulsar.rs) that claims the brand before this helper is ever
// invoked — see src/drivers/mod.rs.
//
// Vendor ids are copied from mouse-protocol/src/drivers/vendors.ts and each
// driver's own `isSupported()`; class import paths use the package's
Expand Down
151 changes: 151 additions & 0 deletions native-hid/src/hid-device-adapter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,157 @@ export function candidateDevices(vendorId, hints = {}, list = devices) {
});
}

/** Whether Bridge parsed the path's descriptor: it declares some report. */
function declaresReports(path) {
return ["inputReports", "outputReports", "featureReports"].some((kind) => Object.keys(path[kind] ?? {}).length > 0);
}

/** A collection only the operating system may read: a standard mouse or
* keyboard (see candidateDevices()). */
function isStandardOnly(path) {
return (
path.collections.length > 0 &&
path.collections.every((collection) => collection.usagePage === 1 && [1, 2, 6].includes(collection.usage))
);
}

/**
* One device as Bridge described it (src/hid.rs, `DescribedDevice`): the
* WebHID view the control panel would get — the same grouping and the
* collections parsed from the report descriptors — plus each collection's
* path and the payload size of every report it declares.
*
* Unlike HidDeviceAdapter it sends a report down only the path whose
* descriptor declares it, padded to the declared size as Chrome's WebHID
* does (Windows refuses a feature report of the wrong length), and reads a
* feature report at its declared size. A path with no declared reports
* (Razer, whose descriptors Bridge does not read) gets HidDeviceAdapter's
* behaviour: any path, a generous read buffer.
*/
export class DescribedDeviceAdapter extends HidDeviceAdapter {
/**
* @param {object} described - one entry of the request's `devices`.
* @param {{ onlyUsagePage?: number, Handle?: typeof HID }} [options] -
* `onlyUsagePage` opens only the paths with a collection on that page,
* for receivers that stop answering while a sibling collection is read
* (Scyrox, see candidateDevices()).
*/
constructor(described, { onlyUsagePage, Handle = HID } = {}) {
const usable = described.paths.filter((path) => !isStandardOnly(path));
const narrowed =
onlyUsagePage === undefined
? usable
: usable.filter((path) => path.collections.some((collection) => collection.usagePage === onlyUsagePage));
const paths = narrowed.length > 0 ? narrowed : usable;
super(
paths.map((path) => ({
path: path.path,
vendorId: described.vendorId,
productId: described.productId,
product: described.productName,
})),
null,
Handle,
);
this.vendorId = described.vendorId;
this.productId = described.productId;
this.productName = described.productName ?? "";
this.collections = described.collections ?? [];
this._paths = paths;
/** Open handles, each with the path it belongs to. */
this._open = [];
}

async open() {
if (this.opened) return;
let lastError = null;
for (const path of this._paths) {
try {
const device = new this._Handle(path.path, OPEN_OPTIONS);
// Listening starts node-hid's read loop. On a path that declares
// reports but no input report (the OP1 8k's feature-only 0xff01
// collection) Windows fails every read, and node-hid gives up on the
// handle, taking the feature reports down with it.
if (!declaresReports(path) || Object.keys(path.inputReports ?? {}).length > 0) {
device.on("data", this._onData);
}
device.on("error", this._onError);
this._open.push({ path, device });
} catch (error) {
lastError = error;
}
}
if (this._open.length === 0) {
throw lastError ?? new Error("Could not open any HID device path");
}
this._devices = this._open.map(({ device }) => device);
this.opened = true;
}

async close() {
await super.close();
this._open = [];
}

async sendReport(reportId, data) {
this._send(reportId, data, "outputReports", (device, frame) => device.write(frame));
}

async sendFeatureReport(reportId, data) {
this._send(reportId, data, "featureReports", (device, frame) => device.sendFeatureReport(frame));
}

async receiveFeatureReport(reportId) {
this._requireOpen();
const declaring = this._declaring(reportId, "featureReports");
const targets = declaring.length > 0 ? declaring : this._open;
let lastError;
for (const { path, device } of targets) {
// The declared payload plus the id byte; 91 covers Razer's 90-byte
// reports where nothing is declared (see HidDeviceAdapter).
const length = declaring.length > 0 ? path.featureReports[reportId] + 1 : 91;
try {
const raw = Uint8Array.from(device.getFeatureReport(reportId, length));
// A declared report's first byte is its id slot, whatever hidapi left
// in it (the OP1 8k's 0xa0 comes back as 0x00 on Windows), as Bridge's
// own transport treats it (`report_payload` in src/hid.rs).
const payload =
declaring.length > 0 || (raw.length > 1 && raw[0] === reportId) ? raw.subarray(1) : raw;
return new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
} catch (error) {
lastError = error;
}
}
throw lastError ?? new Error("No HID interface answered the feature report request.");
}

/** The open paths whose descriptor declares `reportId` of `kind`. */
_declaring(reportId, kind) {
return this._open.filter(({ path }) => path[kind]?.[reportId] !== undefined);
}

/** Sends to the first declaring path that takes the report (any path when
* none declares it), so a command reaches the device once. */
_send(reportId, data, kind, write) {
this._requireOpen();
const declaring = this._declaring(reportId, kind);
const targets = declaring.length > 0 ? declaring : this._open;
let lastError;
for (const { path, device } of targets) {
const frame = this._frame(reportId, data);
const declared = path[kind]?.[reportId];
while (declared !== undefined && frame.length < declared + 1) frame.push(0);
try {
write(device, frame);
return;
} catch (error) {
lastError = error;
}
}
throw lastError ?? new Error("No HID interface accepted the report.");
}
}

export async function probeVerifiedDevice(info, identity, probe, Handle = HID) {
const device = new HidDeviceAdapter([info], identity, Handle);
try {
Expand Down
Loading
Loading