Repository navigation
Add Kmart 43499755 wireless gaming mouse driver #292
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import assert from "node:assert/strict"; | ||
| import test from "node:test"; | ||
| import { KmartHidClient } from "./hid.ts"; | ||
| import { KMART_COMMAND, KMART_REPORT_ID } from "@openmouse/protocol/kmart"; | ||
|
|
||
| function device(options: { | ||
| asleep?: boolean; ignoreWrites?: boolean; sensor?: number; productId?: number; stageByte?: number; | ||
| staleReplies?: number; interval?: number; onSend?: () => Promise<void>; | ||
| } = {}) { | ||
| let interval = options.interval ?? 8; | ||
| let stageByte = options.stageByte ?? 0x36; | ||
| let stale = options.staleReplies ?? 0; | ||
| let pending: Uint8Array | null = null; | ||
| const writes: Uint8Array[] = []; | ||
| const hid = { | ||
| vendorId: 0x248a, | ||
| productId: options.productId ?? 0x5b2f, | ||
| productName: "Wireless-Receiver", | ||
| opened: false, | ||
| collections: [{ | ||
| usagePage: 0xff00, usage: 1, children: [], | ||
| featureReports: [{ reportId: KMART_REPORT_ID, items: [{ reportSize: 8, reportCount: 32 }] }], | ||
| }], | ||
| async open() { this.opened = true; }, | ||
| async close() { this.opened = false; }, | ||
| async sendFeatureReport(reportId: number, data: BufferSource) { | ||
| assert.equal(reportId, KMART_REPORT_ID); | ||
| pending = new Uint8Array(data as Uint8Array); | ||
| writes.push(pending); | ||
| await options.onSend?.(); | ||
| if (pending[4] === 1 && !options.ignoreWrites) { | ||
| if (pending[1] === KMART_COMMAND.pollingInterval) interval = pending[6]!; | ||
| if (pending[1] === KMART_COMMAND.dpiStages) stageByte = pending[6]!; | ||
| } | ||
| }, | ||
| async receiveFeatureReport(reportId: number) { | ||
| assert.equal(reportId, KMART_REPORT_ID); | ||
| assert.ok(pending); | ||
| // WebHID on some platforms prefixes the report ID; exercise that path. | ||
| const reply = new Uint8Array(33); | ||
| reply.set([0x0c, 0x01, 0x20, options.asleep ? 2 : 0, stale-- > 0 ? (pending[3]! + 1) & 0xff : pending[3]!, 0x01, 0x10, 0x00, 0x4d, 0x33, 0x36, 0x31, 0x32, | ||
| 0x01, 0x11, options.sensor ?? 0x25, stageByte, interval, 0x58, 0x00, 0xff, options.asleep ? 0 : 1]); | ||
| return new DataView(reply.buffer); | ||
| }, | ||
| } as unknown as HIDDevice; | ||
| return { hid, writes }; | ||
| } | ||
|
|
||
| test("Kmart recognizes only the vendor feature collection", () => { | ||
| const { hid } = device(); | ||
| assert.equal(KmartHidClient.isSupported(hid), true); | ||
| assert.equal(KmartHidClient.isSupported({ ...hid, productId: 0x5b30 } as HIDDevice), false); | ||
| assert.equal(KmartHidClient.isSupported({ ...hid, collections: [{ usagePage: 1, usage: 2, children: [], featureReports: [] }] } as unknown as HIDDevice), false); | ||
| }); | ||
|
|
||
| test("Kmart status reports battery, polling and the remembered stage DPI", async () => { | ||
| const client = new KmartHidClient(device().hid); | ||
| const status = await client.readStatus(); | ||
| assert.equal(status.brand, "Kmart"); | ||
| assert.equal(status.batteryPercent, 88); | ||
| assert.equal(status.batteryState, "Discharging"); | ||
| assert.equal(status.pollingRateHz, 125); | ||
| assert.equal(status.dpi, 1600); | ||
| assert.equal(status.connectionType, "Wireless"); | ||
| }); | ||
|
|
||
| test("Kmart polling writes verify against read-back", async () => { | ||
| const { hid, writes } = device(); | ||
| const client = new KmartHidClient(hid); | ||
| assert.equal(await client.setPollingRate(1000), 1000); | ||
| assert.ok(writes.some((report) => report[1] === KMART_COMMAND.pollingInterval && report[6] === 1)); | ||
| await assert.rejects(() => new KmartHidClient(device({ ignoreWrites: true }).hid).setPollingRate(500), /did not persist/); | ||
| await assert.rejects(() => client.setPollingRate(2000), RangeError); | ||
| }); | ||
|
|
||
| test("Kmart DPI writes the full stage table and keeps untouched stages", async () => { | ||
| const { hid, writes } = device(); | ||
| const client = new KmartHidClient(hid); | ||
| assert.equal(await client.setDpi(1200), 1200); | ||
| const dpiWrite = writes.find((report) => report[1] === KMART_COMMAND.dpiStages)!; | ||
| assert.deepEqual([...dpiWrite.slice(4, 20)], [1, 18, 0x36, 0x3f, 3, 0, 7, 0, 11, 0, 0x17, 0, 0x1f, 0, 0x34, 0]); | ||
| assert.equal((await client.readStatus()).dpi, 1200); | ||
| await assert.rejects(() => client.setDpi(1250), RangeError); | ||
| }); | ||
|
|
||
| test("Kmart refuses writes while the mouse sleeps or on an unverified sensor", async () => { | ||
| const asleep = device({ asleep: true }); | ||
| await assert.rejects(() => new KmartHidClient(asleep.hid).setPollingRate(1000), /asleep/); | ||
| assert.equal(asleep.writes.some((report) => report[4] === 1), false); | ||
| await assert.rejects(() => new KmartHidClient(device({ sensor: 0x04 }).hid).setDpi(800), /no verified DPI table/); | ||
| }); | ||
|
|
||
| test("Kmart DPI writes keep the device's enabled-stage count", async () => { | ||
| const { hid, writes } = device({ stageByte: 0x34 }); | ||
| await new KmartHidClient(hid).setDpi(1200); | ||
| const dpiWrite = writes.find((report) => report[1] === KMART_COMMAND.dpiStages)!; | ||
| assert.deepEqual([...dpiWrite.slice(6, 8)], [0x34, 0x0f]); | ||
| }); | ||
|
|
||
| test("Kmart wired PID is not gated on the link byte and reports USB", async () => { | ||
| const wired = device({ productId: 0x5b2e, asleep: true }); | ||
| const client = new KmartHidClient(wired.hid); | ||
| assert.equal(KmartHidClient.isSupported(wired.hid), true); | ||
| assert.equal(await client.setPollingRate(1000), 1000); | ||
| assert.equal((await client.readStatus()).connectionType, "Wired"); | ||
| }); | ||
|
|
||
| test("Kmart readStatus reports an asleep receiver without throwing", async () => { | ||
| const status = await new KmartHidClient(device({ asleep: true }).hid).readStatus(); | ||
| assert.equal(status.connectionDetail, "2.4 GHz receiver (mouse asleep)"); | ||
| }); | ||
|
|
||
| test("Kmart readStatus does not present an unknown polling interval as 125 Hz", async () => { | ||
| await assert.rejects(() => new KmartHidClient(device({ interval: 3 }).hid).readStatus(), /polling interval/); | ||
| }); | ||
|
|
||
| test("Kmart status retries stale sequence replies and gives up eventually", async () => { | ||
| const { hid, writes } = device({ staleReplies: 1 }); | ||
| assert.equal((await new KmartHidClient(hid).readStatus()).batteryPercent, 88); | ||
| assert.equal(writes.length, 2); | ||
| await assert.rejects(() => new KmartHidClient(device({ staleReplies: 10 }).hid).readStatus(), /did not match/); | ||
| }); | ||
|
|
||
| test("Kmart close waits for an in-flight operation", async () => { | ||
| let release!: () => void; | ||
| const gate = new Promise<void>((resolve) => { release = resolve; }); | ||
| const { hid } = device({ onSend: () => gate }); | ||
| const client = new KmartHidClient(hid); | ||
| const read = client.readStatus(); | ||
| const closed = client.close(); | ||
| await new Promise((resolve) => setTimeout(resolve, 20)); | ||
| assert.equal(hid.opened, true); | ||
| release(); | ||
| await read; | ||
| await closed; | ||
| assert.equal(hid.opened, false); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| import type { MouseStatus } from "../mouse-types.ts"; | ||
| import { | ||
| KMART_COMMAND, KMART_DPI_STAGE_COUNT, KMART_PMW3325_DPI_VALUES, KMART_POLLING_RATES, KMART_PRODUCT_IDS, | ||
| KMART_RECEIVER_PRODUCT_ID, KMART_REPORT_ID, KMART_SENSOR_PMW3325, KMART_USAGE, KMART_USAGE_PAGE, | ||
| KMART_VENDOR_ID, kmartDecodeStatus, kmartDpiStagesData, kmartPayload, kmartPollingInterval, kmartRequest, | ||
| type KmartStatus, | ||
| } from "@openmouse/protocol/kmart"; | ||
|
|
||
| const PRODUCT_IDS = new Set<number>(KMART_PRODUCT_IDS); | ||
| /** The configurator waits 10 ms before reading a reply and 60 ms after a write. */ | ||
| const READ_PAUSE_MS = 10; | ||
| const WRITE_PAUSE_MS = 60; | ||
| const STATUS_ATTEMPTS = 3; | ||
| /** The mouse keeps no readable copy of its DPI ladder, so the driver remembers the last one it wrote. */ | ||
| const DEFAULT_STAGES = [400, 800, 1600, 2400, 3200, 6400]; | ||
|
|
||
| function hasControlCollection(collections: readonly HIDCollectionInfo[]): boolean { | ||
| return collections.some((collection) => | ||
| (collection.usagePage === KMART_USAGE_PAGE && collection.usage === KMART_USAGE | ||
| && collection.featureReports.some((report) => report.reportId === KMART_REPORT_ID)) | ||
| || hasControlCollection(collection.children)); | ||
| } | ||
|
|
||
| const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)); | ||
|
|
||
| /** Feature-report client for the Kmart 43499755 wireless gaming mouse. */ | ||
| export class KmartHidClient { | ||
| readonly device: HIDDevice; | ||
| private queue: Promise<unknown> = Promise.resolve(); | ||
| private sequence = 0; | ||
| private stages: number[] = [...DEFAULT_STAGES]; | ||
|
|
||
| constructor(device: HIDDevice) { this.device = device; } | ||
|
|
||
| static isSupported(device: HIDDevice): boolean { | ||
| return device.vendorId === KMART_VENDOR_ID | ||
| && PRODUCT_IDS.has(device.productId) | ||
| // Native adapters report no collections; WebHID must expose the vendor feature report. | ||
| && (device.collections.length === 0 || hasControlCollection(device.collections)); | ||
| } | ||
|
|
||
| get pollIntervalMs(): number { return 30_000; } | ||
|
|
||
| getDpiOptions(): number[] { return [...KMART_PMW3325_DPI_VALUES]; } | ||
|
|
||
| getSupportedPollingRates(): number[] { return [...KMART_POLLING_RATES]; } | ||
|
|
||
| async open(): Promise<void> { | ||
| if (!KmartHidClient.isSupported(this.device)) throw new Error("Kmart configuration collection is unavailable."); | ||
| if (!this.device.opened) await this.device.open(); | ||
| } | ||
|
|
||
| async close(): Promise<void> { | ||
| await this.run(async () => { if (this.device.opened) await this.device.close(); }); | ||
| } | ||
| async startNotifications(_onChange?: () => void): Promise<boolean> { return false; } | ||
|
|
||
| async readStatus(): Promise<MouseStatus> { | ||
| return this.run(async () => { | ||
| const status = await this.queryStatus(); | ||
| // MouseStatus has no unknown polling rate, so fail rather than invent 125 Hz. | ||
| if (status.pollingRateHz === null) throw new Error("Kmart reported an unrecognised polling interval."); | ||
| const receiver = this.device.productId === KMART_RECEIVER_PRODUCT_ID; | ||
| const stage = Math.min(status.activeStage, this.stages.length - 1); | ||
| return { | ||
| brand: "Kmart", | ||
| name: "Kmart Wireless Gaming Mouse", | ||
| batteryPercent: status.batteryPercent, | ||
| batteryState: status.chargeState === 1 ? "Charging" : status.chargeState === 2 ? "Full" : "Discharging", | ||
| dpi: this.stages[stage]!, | ||
| pollingRateHz: status.pollingRateHz, | ||
| supportedPollingRates: this.getSupportedPollingRates(), | ||
| activeProfile: null, | ||
| connectionType: receiver ? "Wireless" : "Wired", | ||
| connectionDetail: receiver ? (status.linked ? "2.4 GHz receiver" : "2.4 GHz receiver (mouse asleep)") : "USB", | ||
| liftOffDistance: null, | ||
| firmware: [status.firmwareTag], | ||
| ui: { | ||
| family: "kmart", | ||
| hideUnsupportedPollingRates: true, | ||
| hideProcessingCard: true, | ||
| hideSignalCard: true, | ||
| hideSleepCard: true, | ||
| defaultDisplayName: "Kmart Wireless Gaming Mouse", | ||
| }, | ||
| }; | ||
| }); | ||
| } | ||
|
|
||
| /** Sets the active stage's DPI, keeping the other stages the driver last wrote. */ | ||
| async setDpi(dpi: number): Promise<number> { | ||
| if (!KMART_PMW3325_DPI_VALUES.includes(dpi)) throw new RangeError(`DPI ${dpi} is not supported by this mouse.`); | ||
| return this.run(async () => { | ||
| const status = await this.requireLinked(); | ||
| if (status.sensor !== KMART_SENSOR_PMW3325) { | ||
| throw new Error(`Kmart sensor 0x${status.sensor.toString(16)} has no verified DPI table.`); | ||
| } | ||
| // Keep the device's own enabled-stage count instead of forcing all six on. | ||
| const enabled = status.enabledStageCount >= 1 && status.enabledStageCount <= KMART_DPI_STAGE_COUNT | ||
| ? status.enabledStageCount : KMART_DPI_STAGE_COUNT; | ||
| const stage = Math.min(status.activeStage, enabled - 1); | ||
| const stages = [...this.stages]; | ||
| stages[stage] = dpi; | ||
| await this.write(KMART_COMMAND.dpiStages, kmartDpiStagesData(stages, stage, enabled)); | ||
| this.stages = stages; | ||
| return dpi; | ||
|
Comment on lines
+93
to
+106
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| }); | ||
| } | ||
|
|
||
| async setPollingRate(rate: number): Promise<number> { | ||
| const interval = kmartPollingInterval(rate); | ||
| return this.run(async () => { | ||
| await this.requireLinked(); | ||
| await this.write(KMART_COMMAND.pollingInterval, [interval]); | ||
| const confirmed = (await this.queryStatus()).pollingRateHz; | ||
| if (confirmed !== rate) throw new Error("Kmart polling-rate write did not persist."); | ||
| return rate; | ||
| }); | ||
| } | ||
|
|
||
| private async requireLinked(): Promise<KmartStatus> { | ||
| const status = await this.queryStatus(); | ||
| // The wired PID's link byte is unverified, so only the receiver is gated on it. | ||
| if (this.device.productId === KMART_RECEIVER_PRODUCT_ID && !status.linked) throw new Error("The mouse is asleep. Move it, then try again."); | ||
| return status; | ||
| } | ||
|
|
||
| private async queryStatus(): Promise<KmartStatus> { | ||
| await this.open(); | ||
| for (let attempt = 0; attempt < STATUS_ATTEMPTS; attempt += 1) { | ||
| const sequence = this.nextSequence(); | ||
| await this.device.sendFeatureReport(KMART_REPORT_ID, kmartRequest(KMART_COMMAND.status, sequence)); | ||
| await sleep(READ_PAUSE_MS); | ||
| const payload = kmartPayload(await this.device.receiveFeatureReport(KMART_REPORT_ID)); | ||
| // A reply that does not echo our sequence byte belongs to an earlier request. | ||
| if (payload[3] === sequence) return kmartDecodeStatus(payload); | ||
| } | ||
| throw new Error("Kmart status reply did not match the request."); | ||
| } | ||
|
|
||
| private async write(command: number, data: number[]): Promise<void> { | ||
| await this.open(); | ||
| await this.device.sendFeatureReport(KMART_REPORT_ID, kmartRequest(command, this.nextSequence(), data, true)); | ||
| await sleep(WRITE_PAUSE_MS); | ||
| } | ||
|
|
||
| private nextSequence(): number { | ||
| this.sequence = (this.sequence + 1) & 0xff; | ||
| return this.sequence; | ||
| } | ||
|
|
||
| private async run<T>(action: () => Promise<T>): Promise<T> { | ||
| const result = this.queue.then(action, action); | ||
| this.queue = result.then(() => undefined, () => undefined); | ||
| return result; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: OpenMouse-Project/mouse-protocol
Length of output: 42047
Script executed:
Repository: OpenMouse-Project/mouse-protocol
Length of output: 25765
Script executed:
Repository: OpenMouse-Project/mouse-protocol
Length of output: 14374
Web query:
github OpenMouse-Project openmouse src control.ts status.dpi status.pollingRateHz pollingRateHz setPollingRate UIResult:
Script executed:
Repository: OpenMouse-Project/mouse-protocol
Length of output: 9874
Script executed:
Repository: OpenMouse-Project/mouse-protocol
Length of output: 36577
Script executed:
Repository: OpenMouse-Project/mouse-protocol
Length of output: 14004
Mark the reported DPI as an estimate.
If another configurator changes the DPI table, switching to that stage can show the wrong DPI. The driver reads the active stage but indexes its own cached table, which may be stale. Expose that uncertainty to consumers instead of presenting the value as verified.