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
20 changes: 5 additions & 15 deletions native-hid/src/apply.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ globalThis.window ??= globalThis;
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 { devices } from "node-hid";
import { automate } from "./automation.mjs";

Expand Down Expand Up @@ -115,21 +116,10 @@ async function main() {
}
}

const attempts = [];
let client = null;
let status = null;
outer: for (const vendorId of entry.vendorIds) {
for (const device of candidateDevices(vendorId, entry)) {
for (const candidate of entry.classes) {
try {
({ client, status } = await probe(device, candidate));
break outer;
} catch (error) {
attempts.push(`${candidate.exportName} on ${device.productName || "unknown device"}: ${error.message}`);
}
}
}
}
const pairs = 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) {
console.error(
Expand Down
8 changes: 7 additions & 1 deletion native-hid/src/brands.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,13 @@ export const BRAND_DRIVERS = {
},
keychron: {
vendorIds: [0x3434],
classes: [client("@openmouse/protocol/drivers/keychron/hid", "KeychronHidClient")],
classes: [
client("@openmouse/protocol/drivers/keychron/mouse-8k-hid", "Keychron8kHidClient"),
client("@openmouse/protocol/drivers/keychron/mouse-1k-hid", "Keychron1kHidClient"),
client("@openmouse/protocol/drivers/keychron/mouse-4k-hid", "Keychron4kHidClient"),
client("@openmouse/protocol/drivers/keychron/mouse-8k-nordic-hid", "Keychron8kNordicHidClient"),
client("@openmouse/protocol/drivers/keychron/nape-hid", "KeychronNapeHidClient"),
],
},
fantech: {
vendorIds: [0x3151],
Expand Down
77 changes: 77 additions & 0 deletions native-hid/src/select-client.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Picks which interface and driver class of a brand to talk to.
//
// Settings writes take the first pair that answers, so a request always
// changes the same mouse it always did.
//
// A status read prefers an answer with a battery. A receiver can expose
// several interfaces that a driver class opens and reads without error, but
// only one of them carries the mouse's battery: the Keychron TurboLink 8K
// answers Keychron8kHidClient on its consumer, vendor 0xffc1 and 0x8c
// interfaces, and only 0xffc1 reports the G6 HE 8K's battery. Taking the first
// answer would report no battery at all, so an answer with a battery wins, and
// the first answer's status is used when none has one (a wired mouse, for
// instance).
//
// Once a class has answered, only that class is tried on the remaining
// interfaces: the class is known to fit the device, and trying every other
// class on every interface could take long enough (each failed probe may
// wait out its timeout) to run past Bridge's limit on the helper. That
// search also has a budget of its own, so stalled sibling interfaces cannot
// hold up a read whose status is already in hand.
//
// A battery-less answer is closed before probing on rather than held open:
// some receivers stop answering on one collection while a sibling is read
// (see candidateDevices()). Its status is kept, so it is never read twice.

/** How long a status read keeps looking for a battery after a first answer
* without one. Bridge stops the helper after 10 s. */
const BATTERY_SEARCH_MS = 4000;

/**
* @param {Array<{ device: object, candidate: object }>} pairs - every
* (interface, driver class) combination, in preference order.
* @param {(device: object, candidate: object) => Promise<{ client: object, status: object }>} probe
* opens and reads one pair; rejects (and leaves the device closed) on failure.
* @param {{ preferBattery?: boolean, batterySearchMs?: number }} [options] -
* `preferBattery` for status reads only: the returned client may then be
* closed already, and only its status is to be used.
* @returns {Promise<{ client: object | null, status: object | null, attempts: string[] }>}
*/
export async function selectClient(pairs, probe, { preferBattery = false, batterySearchMs = BATTERY_SEARCH_MS } = {}) {
const attempts = [];
let fallback = null;
let deadline = Infinity;
for (const { device, candidate } of pairs) {
if (fallback && (candidate.exportName !== fallback.candidate.exportName || device === fallback.device)) continue;
const remaining = deadline - Date.now();
if (remaining <= 0) break;
let found;
try {
found = await (fallback ? within(probe(device, candidate), remaining) : probe(device, candidate));
} catch (error) {
attempts.push(`${candidate.exportName} on ${device.productName || "unknown device"}: ${error.message}`);
continue;
}
if (!preferBattery || hasBattery(found.status)) return { ...found, attempts };
if (!fallback) {
fallback = { device, candidate, ...found };
deadline = Date.now() + batterySearchMs;
}
await found.client.close?.().catch(() => undefined);
await device.close?.().catch(() => undefined);
}
if (fallback) return { client: fallback.client, status: fallback.status, attempts };
return { client: null, status: null, attempts };
}

function within(promise, ms) {
let timer;
const timeout = new Promise((_resolve, reject) => {
timer = setTimeout(() => reject(new Error(`no answer within the ${ms} ms left for a battery search`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}

function hasBattery(status) {
return typeof status?.batteryPercent === "number" && Number.isFinite(status.batteryPercent);
}
143 changes: 143 additions & 0 deletions native-hid/src/select-client.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { test } from "node:test";
import assert from "node:assert/strict";

import { selectClient } from "./select-client.mjs";
import { BRAND_DRIVERS } from "./brands.mjs";

function fakeDevice(name) {
return { productName: name, closed: 0, close: async function () { this.closed += 1; } };
}

const candidate = (exportName) => ({ exportName });
const status = { preferBattery: true };


/** A probe that answers from `replies`, keyed by device name. */
function probeFrom(replies, log = []) {
return async (device, which) => {
log.push(device.productName);
const reply = replies[device.productName];
if (reply instanceof Error) throw reply;
return { client: { close: async () => undefined, which }, status: reply };
};
}

test("an interface with a battery wins over an earlier one without", async () => {
const consumer = fakeDevice("consumer");
const vendor = fakeDevice("vendor");
const result = await selectClient(
[
{ device: consumer, candidate: candidate("A") },
{ device: vendor, candidate: candidate("A") },
],
probeFrom({ consumer: { batteryPercent: null }, vendor: { batteryPercent: 22 } }),
status,
);
assert.equal(result.status.batteryPercent, 22);
// The battery-less interface was let go before the next one was read.
assert.equal(consumer.closed, 1);
});

test("the first answer's status is used when no interface reports a battery", async () => {
const log = [];
const result = await selectClient(
[
{ device: fakeDevice("first"), candidate: candidate("A") },
{ device: fakeDevice("second"), candidate: candidate("A") },
],
probeFrom({ first: { batteryPercent: null, dpi: 800 }, second: { batteryPercent: null, dpi: 1600 } }, log),
status,
);
assert.equal(result.status.dpi, 800);
// Its status was kept, so it is not read a second time.
assert.deepEqual(log, ["first", "second"]);
});

test("settings writes take the first mouse that answers, battery or not", async () => {
const log = [];
const result = await selectClient(
[
{ device: fakeDevice("first"), candidate: candidate("A") },
{ device: fakeDevice("second"), candidate: candidate("A") },
],
probeFrom({ first: { batteryPercent: null, dpi: 800 }, second: { batteryPercent: 60, dpi: 1600 } }, log),
);
assert.equal(result.status.dpi, 800);
assert.deepEqual(log, ["first"]);
});

test("the battery search stops at its budget when a sibling interface stalls", async () => {
const started = Date.now();
const result = await selectClient(
[
{ device: fakeDevice("first"), candidate: candidate("A") },
{ device: fakeDevice("stalled"), candidate: candidate("A") },
{ device: fakeDevice("never"), candidate: candidate("A") },
],
async (device) => {
if (device.productName === "stalled") return new Promise(() => {});
if (device.productName === "never") throw new Error("must not be reached");
return { client: { close: async () => undefined }, status: { batteryPercent: null, dpi: 800 } };
},
{ preferBattery: true, batterySearchMs: 50 },
);
assert.ok(Date.now() - started < 1000);
assert.equal(result.status.dpi, 800);
assert.match(result.attempts[0], /^A on stalled: no answer within/);
assert.equal(result.attempts.length, 1);
});

test("after a battery-less answer only that class is tried on other interfaces", async () => {
const tried = [];
const first = fakeDevice("first");
const second = fakeDevice("second");
const [a, b] = [candidate("A"), candidate("B")];
const result = await selectClient(
[
{ device: first, candidate: a },
{ device: first, candidate: b },
{ device: second, candidate: b },
{ device: second, candidate: a },
],
async (device, which) => {
tried.push(`${which.exportName}@${device.productName}`);
return { client: { close: async () => undefined }, status: { batteryPercent: device === second ? 40 : null } };
},
status,
);
assert.equal(result.status.batteryPercent, 40);
assert.deepEqual(tried, ["A@first", "A@second"]);
});

test("a battery answer stops the search", async () => {
const log = [];
await selectClient(
[
{ device: fakeDevice("first"), candidate: candidate("A") },
{ device: fakeDevice("second"), candidate: candidate("A") },
],
probeFrom({ first: { batteryPercent: 50 }, second: { batteryPercent: 60 } }, log),
status,
);
assert.deepEqual(log, ["first"]);
});

test("failures are reported when nothing answers", async () => {
const result = await selectClient(
[{ device: fakeDevice("only"), candidate: candidate("A") }],
probeFrom({ only: new Error("no reply") }),
);
assert.equal(result.client, null);
assert.deepEqual(result.attempts, ["A on only: no reply"]);
});

test("every driver class a brand names exists in the protocol package", async () => {
// Some driver modules touch `window` when loaded, as apply.mjs allows for.
globalThis.window ??= globalThis;
for (const [brand, entry] of Object.entries(BRAND_DRIVERS)) {
for (const { module, exportName } of entry.classes) {
const loaded = await import(module);
assert.equal(typeof loaded[exportName], "function", `${brand}: ${module} has no ${exportName}`);
}
}
});
Loading