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
12 changes: 11 additions & 1 deletion src/drivers/8bitdo/hid.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ 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/);
// Not the asleep note: moving the mouse does not fix a silent receiver.
assert.match(status.ui?.statusNote ?? "", /receiver did not answer/);
});

/**
Expand Down Expand Up @@ -275,6 +276,15 @@ test("readStatus retries a settings read the mouse misses", async () => {
assert.equal(status.ui?.settingsReady, true);
});

test("concurrent stage edits each keep their change", async () => {
const { device, state } = statefulDevice();
const client = new EightBitDoHidClient(device);
// Each one rewrites the whole table, so interleaved they would undo each other.
assert.deepEqual(await Promise.all([client.setDpiStageValue(0, 900), client.setDpiStageValue(5, 6000)]), [900, 6000]);
assert.deepEqual(state.tables[0], [900, 1200, 1600, 2400, 3200, 6000]);
assert.deepEqual(state.tables[1], [900, 1200, 1600, 2400, 3200, 6000]);
});

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);
Expand Down
95 changes: 61 additions & 34 deletions src/drivers/8bitdo/hid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const READ_RETRY_DELAY_MS = 100;
export class EightBitDoHidClient {
readonly device: HIDDevice;
private queue: Promise<unknown> = Promise.resolve();
private settingsQueue: Promise<unknown> = Promise.resolve();

constructor(device: HIDDevice) {
this.device = device;
Expand Down Expand Up @@ -115,7 +116,10 @@ export class EightBitDoHidClient {
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.",
: link === null
// No reply at all is a receiver problem, which moving the mouse does not fix.
? "The receiver did not answer. Unplug it and plug it back in."
: "The receiver is connected but the mouse is asleep or switched off. Move it to wake it.",
},
batteryPercent: null,
batteryState: "Unknown",
Expand Down Expand Up @@ -172,38 +176,70 @@ export class EightBitDoHidClient {
};
}

async setPollingRate(pollingRateHz: number): Promise<number> {
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;
setPollingRate(pollingRateHz: number): Promise<number> {
return this.exclusive(async () => {
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<LiftOff> {
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;
setLiftOffDistance(liftOffDistance: LiftOff): Promise<LiftOff> {
return this.exclusive(async () => {
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<number> {
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;
setActiveDpiStage(stage: number): Promise<number> {
return this.exclusive(async () => {
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<number> {
setDpiStageValue(stage: number, dpi: number): Promise<number> {
return this.exclusive(() => this.writeStageValue(stage, dpi));
}

/** Changes the DPI of the active stage. */
setDpi(dpi: number): Promise<number> {
return this.exclusive(async () => {
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.writeStageValue(stage, dpi);
});
}

/**
* Runs one read-modify-write-verify setting change at a time. The setters
* rewrite whole DPI tables, so two interleaved ones could undo each other;
* `request` alone only keeps single reports apart.
*/
private exclusive<T>(operation: () => Promise<T>): Promise<T> {
const run = this.settingsQueue.then(operation);
this.settingsQueue = run.catch(() => undefined);
return run;
}

private async writeStageValue(stage: number, dpi: number): Promise<number> {
if (!eightBitDoIsValidDpi(dpi)) {
throw new Error(`DPI must be ${EIGHTBITDO_R8_DPI.min}-${EIGHTBITDO_R8_DPI.max} in steps of ${EIGHTBITDO_R8_DPI.step}.`);
}
Expand All @@ -222,15 +258,6 @@ export class EightBitDoHidClient {
return dpi;
}

/** Changes the DPI of the active stage. */
async setDpi(dpi: number): Promise<number> {
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);
}
Expand Down