From 36d8b04b7aa8ea81d49893ecc791e30b849ea383 Mon Sep 17 00:00:00 2001 From: FeetusDeletus12 Date: Sun, 8 Nov 2026 15:48:47 +1100 Subject: [PATCH 1/3] feat: add Kmart 43499755 wireless gaming mouse driver Feature-report driver for the Kmart "Wireless Gaming Mouse" (item 43499755), VID 0x248a, PIDs 0x5b2e (wired) and 0x5b2f (2.4 GHz receiver). Report 0x0c on the 0xff00 vendor collection carries status reads, the six-stage DPI table and the polling interval. Verified on hardware through the receiver: status read, polling write with read-back, and DPI-stage write. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 + src/drivers/kmart/hid.test.ts | 86 ++++++++++++++++++++ src/drivers/kmart/hid.ts | 142 ++++++++++++++++++++++++++++++++ src/drivers/mouse-types.ts | 2 +- src/drivers/registry.ts | 5 +- src/drivers/vendors.ts | 7 ++ src/index.ts | 1 + src/kmart/index.test.ts | 65 +++++++++++++++ src/kmart/index.ts | 149 ++++++++++++++++++++++++++++++++++ 9 files changed, 459 insertions(+), 2 deletions(-) create mode 100644 src/drivers/kmart/hid.test.ts create mode 100644 src/drivers/kmart/hid.ts create mode 100644 src/kmart/index.test.ts create mode 100644 src/kmart/index.ts diff --git a/package.json b/package.json index 1764d83..8427776 100644 --- a/package.json +++ b/package.json @@ -130,6 +130,10 @@ "types": "./dist/valkyrie/index.d.ts", "import": "./dist/valkyrie/index.js" }, + "./kmart": { + "types": "./dist/kmart/index.d.ts", + "import": "./dist/kmart/index.js" + }, "./vaxee": { "types": "./dist/vaxee/index.d.ts", "import": "./dist/vaxee/index.js" diff --git a/src/drivers/kmart/hid.test.ts b/src/drivers/kmart/hid.test.ts new file mode 100644 index 0000000..8edc928 --- /dev/null +++ b/src/drivers/kmart/hid.test.ts @@ -0,0 +1,86 @@ +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 } = {}) { + let interval = 8; + let stageByte = 0x36; + let pending: Uint8Array | null = null; + const writes: Uint8Array[] = []; + const hid = { + vendorId: 0x248a, + 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); + 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, 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/); +}); diff --git a/src/drivers/kmart/hid.ts b/src/drivers/kmart/hid.ts new file mode 100644 index 0000000..7d809d5 --- /dev/null +++ b/src/drivers/kmart/hid.ts @@ -0,0 +1,142 @@ +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(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; +/** 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((resolve) => setTimeout(resolve, ms)); + +/** Feature-report client for the Kmart 43499755 wireless gaming mouse. */ +export class KmartHidClient { + readonly device: HIDDevice; + private queue: Promise = 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 { + if (!KmartHidClient.isSupported(this.device)) throw new Error("Kmart configuration collection is unavailable."); + if (!this.device.opened) await this.device.open(); + } + + async close(): Promise { if (this.device.opened) await this.device.close(); } + async startNotifications(_onChange?: () => void): Promise { return false; } + + async readStatus(): Promise { + return this.run(async () => { + const status = await this.queryStatus(); + 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 ?? 125, + 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 { + 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.`); + } + const stage = Math.min(status.activeStage, KMART_DPI_STAGE_COUNT - 1); + const stages = [...this.stages]; + stages[stage] = dpi; + await this.write(KMART_COMMAND.dpiStages, kmartDpiStagesData(stages, stage)); + this.stages = stages; + return dpi; + }); + } + + async setPollingRate(rate: number): Promise { + 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 { + const status = await this.queryStatus(); + if (!status.linked) throw new Error("The mouse is asleep. Move it, then try again."); + return status; + } + + private async queryStatus(): Promise { + await this.open(); + await this.device.sendFeatureReport(KMART_REPORT_ID, new Uint8Array(kmartRequest(KMART_COMMAND.status, this.nextSequence())).buffer); + await sleep(READ_PAUSE_MS); + return kmartDecodeStatus(kmartPayload(await this.device.receiveFeatureReport(KMART_REPORT_ID))); + } + + private async write(command: number, data: number[]): Promise { + await this.open(); + await this.device.sendFeatureReport(KMART_REPORT_ID, new Uint8Array(kmartRequest(command, this.nextSequence(), data, true)).buffer); + await sleep(WRITE_PAUSE_MS); + } + + private nextSequence(): number { + this.sequence = (this.sequence + 1) & 0xff; + return this.sequence; + } + + private async run(action: () => Promise): Promise { + const result = this.queue.then(action, action); + this.queue = result.then(() => undefined, () => undefined); + return result; + } +} diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 6caf6d6..726eb7d 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -208,7 +208,7 @@ export interface MagneticCalibrationProgress { } export interface MouseStatus { - 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" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear"; + 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" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "Kmart"; name: string; /** Optional LunaFury controls, populated only after successful device reads. */ lunafury?: import("../lamzu/lunafury.js").LunaFurySettings; diff --git a/src/drivers/registry.ts b/src/drivers/registry.ts index 4f3a4d6..f130340 100644 --- a/src/drivers/registry.ts +++ b/src/drivers/registry.ts @@ -36,6 +36,7 @@ import { RazerViperMiniHidClient } from "./razer/viper-mini-hid.ts"; 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 { VaxeeHidClient } from "./vaxee/hid.ts"; import { WallhackKeyboardHidClient } from "./wallhack/keyboard-hid.ts"; import { WallhackMouseHidClient } from "./wallhack/mouse-hid.ts"; @@ -105,7 +106,7 @@ import { HitscanHidClient } from "./hitscan/hid.ts"; import { HitscanXviHidClient } from "./hitscan/xvi-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 | 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 | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient; +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 | KmartHidClient | Keychron8kHidClient | Keychron1kHidClient | Keychron4kHidClient | Keychron8kNordicHidClient | KeychronNapeHidClient | ModdoHidClient | NinjutsoHidClient | ZaunkoenigHidClient | CorsairHidClient | CorsairBragiHidClient | AttackSharkHidClient | 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 | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient; export interface DeviceDriver { brand: string; supports(device: HIDDevice): boolean; @@ -149,6 +150,8 @@ export const DEVICE_DRIVERS: readonly DeviceDriver[] = [ { brand: "Teevolution", supports: (device) => TeevolutionHidClient.isSupported(device), create: (device) => new TeevolutionHidClient(device), score: () => 7 }, { brand: "VGN", supports: (device) => VgnF2HidClient.isSupported(device), create: (device) => new VgnF2HidClient(device), score: () => 7 }, { brand: "VAXEE", supports: (device) => VaxeeHidClient.isSupported(device), create: (device) => new VaxeeHidClient(device), score: () => 7 }, + // Kmart 43499755 (VID 0x248a): only PIDs 0x5b2e/0x5b2f with the 0xff00 report-0x0c collection. + { brand: "Kmart", supports: (device) => KmartHidClient.isSupported(device), create: (device) => new KmartHidClient(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 e528e20..88fbb7d 100644 --- a/src/drivers/vendors.ts +++ b/src/drivers/vendors.ts @@ -27,6 +27,7 @@ import { GLORIOUS_CORE2_PRODUCTS, GLORIOUS_CORE2_USAGE_PAGE, GLORIOUS_CORE2_VEND 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 { VAXEE_PRODUCT_IDS, VAXEE_USAGE, VAXEE_USAGE_PAGE, VAXEE_VENDOR_ID } from "@openmouse/protocol/vaxee"; import { GEARHUB_BLUETOOTH_USAGE, @@ -184,6 +185,7 @@ export const VENDOR_ID = { coolermaster: COOLERMASTER_VENDOR_ID, ajazz: 0x1a2c, vaxee: VAXEE_VENDOR_ID, + kmart: KMART_VENDOR_ID, asus: ASUS_VENDOR_ID, ryunix: RYUNIX_VENDOR_ID, // Amkette's XS series shares the 0x04F3 OEM firmware and IDs with Ryunix; the @@ -976,10 +978,15 @@ export const VAXEE_HID_FILTERS: HIDDeviceFilter[] = VAXEE_PRODUCT_IDS.map((produ vendorId: VAXEE_VENDOR_ID, productId, usagePage: VAXEE_USAGE_PAGE, usage: VAXEE_USAGE, })); +export const KMART_HID_FILTERS: HIDDeviceFilter[] = KMART_PRODUCT_IDS.map((productId) => ({ + vendorId: KMART_VENDOR_ID, productId, usagePage: KMART_USAGE_PAGE, usage: KMART_USAGE, +})); + export const SUPPORTED_HID_FILTERS: HIDDeviceFilter[] = [ ...[...AJ200P_PRODUCTS.keys()].map((productId) => ({ vendorId: AJ200P_VENDOR_ID, productId, usagePage: AJ200P_USAGE_PAGE, usage: AJ200P_USAGE })), { vendorId: VENDOR_ID.redgear, productId: REDGEAR_X13_PRODUCT_ID, usagePage: REDGEAR_X13_USAGE_PAGE, usage: REDGEAR_X13_USAGE }, ...VAXEE_HID_FILTERS, + ...KMART_HID_FILTERS, ...ASUS_HID_FILTERS, ...DAREU_HID_FILTERS, ...REDRAGON_HID_FILTERS, diff --git a/src/index.ts b/src/index.ts index b4cd705..469300e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,6 +30,7 @@ export * as gloriousSinowealth from "./glorious-sinowealth/index.js"; 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 vaxee from "./vaxee/index.js"; export * as incott from "./incott/index.js"; export * as ryunix from "./ryunix/index.js"; diff --git a/src/kmart/index.test.ts b/src/kmart/index.test.ts new file mode 100644 index 0000000..3ae724f --- /dev/null +++ b/src/kmart/index.test.ts @@ -0,0 +1,65 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + KMART_COMMAND, KMART_PMW3325_DPI_VALUES, kmartDecodeStatus, kmartDpiStagesData, kmartPmw3325DpiCode, + kmartPollingInterval, kmartPollingRate, kmartRequest, +} from "./index.ts"; + +// Captured from the 2.4 GHz receiver (PID 0x5b2f), report ID included. +const CAPTURED_STATUS = Uint8Array.from( + "0c 01 20 00 00 01 10 00 4d 33 36 31 32 01 11 25 36 08 58 00 ff 01 00 91 e4 10 ff ff 00 01 60 03 20".split(" "), + (byte) => parseInt(byte, 16), +); + +test("Kmart status request matches the configurator frame", () => { + const request = kmartRequest(KMART_COMMAND.status, 0); + assert.equal(request.length, 32); + assert.deepEqual([...request.slice(0, 7)], [0x01, 0x20, 0, 0, 0, 0, 0]); +}); + +test("Kmart writes carry the write flag, length and data", () => { + const request = kmartRequest(KMART_COMMAND.pollingInterval, 0xd0, [0x01], true); + assert.deepEqual([...request.slice(0, 8)], [0x01, 0x07, 0x00, 0xd0, 0x01, 0x01, 0x01, 0x00]); + assert.throws(() => kmartRequest(KMART_COMMAND.lighting, 0, new Array(27).fill(0), true), RangeError); +}); + +test("Kmart decodes a captured status reply with or without the report ID", () => { + for (const reply of [CAPTURED_STATUS, CAPTURED_STATUS.subarray(1)]) { + const status = kmartDecodeStatus(reply); + assert.equal(status.linked, true); + assert.equal(status.firmwareTag, "M3612"); + assert.equal(status.sensor, 0x25); + assert.equal(status.activeStage, 2); + assert.equal(status.enabledStageCount, 6); + assert.equal(status.pollingRateHz, 125); + assert.equal(status.batteryPercent, 88); + assert.equal(status.chargeState, 0); + } + const asleep = CAPTURED_STATUS.slice(); + asleep[3] = 0x02; + asleep[0x15] = 0x00; + assert.equal(kmartDecodeStatus(asleep).linked, false); + const corrupt = CAPTURED_STATUS.slice(); + corrupt[8] = 0; + assert.throws(() => kmartDecodeStatus(corrupt)); +}); + +test("Kmart DPI stages encode the bytes verified on hardware", () => { + assert.equal(KMART_PMW3325_DPI_VALUES.length, 59); + assert.equal(KMART_PMW3325_DPI_VALUES[0], 200); + assert.equal(KMART_PMW3325_DPI_VALUES.at(-1), 10000); + assert.deepEqual( + kmartDpiStagesData([400, 800, 1600, 2400, 3200, 6400], 2), + [0x36, 0x3f, 0x03, 0, 0x07, 0, 0x0f, 0, 0x17, 0, 0x1f, 0, 0x34, 0, 0, 0, 0, 0], + ); + assert.throws(() => kmartPmw3325DpiCode(450), RangeError); + assert.throws(() => kmartDpiStagesData([400], 1), RangeError); +}); + +test("Kmart polling uses report intervals in milliseconds", () => { + assert.equal(kmartPollingInterval(1000), 1); + assert.equal(kmartPollingInterval(125), 8); + assert.equal(kmartPollingRate(2), 500); + assert.equal(kmartPollingRate(3), null); + assert.throws(() => kmartPollingInterval(2000), RangeError); +}); diff --git a/src/kmart/index.ts b/src/kmart/index.ts new file mode 100644 index 0000000..58f4008 --- /dev/null +++ b/src/kmart/index.ts @@ -0,0 +1,149 @@ +/** + * Kmart "Wireless Gaming Mouse" (Kmart item 43499755) feature-report protocol. + * + * Evidence: static analysis of the vendor's Windows configurator + * (`43499755_Wireless_Gaming_Mouse.exe` from intraindustry.com, `GamingMS.exe`), + * confirmed on hardware through the 2.4 GHz receiver (PID 0x5b2f): the status + * query, polling-rate write with read-back, and DPI-stage write. + * + * Every request is one 32-byte feature report with ID 0x0c on the vendor + * collection (usage page 0xff00, usage 0x01). The configurator sends a request, + * waits 10 ms and reads report 0x0c back. Byte offsets below exclude the + * report ID, matching WebHID's `sendFeatureReport` payloads. + */ +export const KMART_VENDOR_ID = 0x248a; +export const KMART_WIRED_PRODUCT_ID = 0x5b2e; +export const KMART_RECEIVER_PRODUCT_ID = 0x5b2f; +export const KMART_PRODUCT_IDS = [KMART_WIRED_PRODUCT_ID, KMART_RECEIVER_PRODUCT_ID] as const; +export const KMART_USAGE_PAGE = 0xff00; +export const KMART_USAGE = 0x01; +export const KMART_REPORT_ID = 0x0c; +export const KMART_REPORT_SIZE = 32; +const KMART_MAX_DATA = KMART_REPORT_SIZE - 6; + +export const KMART_COMMAND = { + /** Read-only status: sensor, active DPI stage, polling interval, battery, link. */ + status: 0x20, + /** Six DPI stages, the enabled-stage mask and the active stage (18 bytes). */ + dpiStages: 0x05, + /** Eight button assignments, three bytes each (24 bytes). Not driven yet. */ + buttons: 0x06, + /** USB report interval in milliseconds (1 byte). */ + pollingInterval: 0x07, + /** Lighting effect block (25 bytes). Not driven yet. */ + lighting: 0x08, +} as const; + +/** Sensor codes the configurator recognises in status byte 14. */ +export const KMART_SENSOR_PMW3325 = 0x25; + +/** + * PMW3325 DPI ladder from the configurator, in DPI. The wire code for a stage + * is its index in this list plus one. + */ +export const KMART_PMW3325_DPI_VALUES: readonly number[] = [ + ...Array.from({ length: 49 }, (_, index) => (4 + index * 2) * 50), + 110 * 50, 120 * 50, 128 * 50, 140 * 50, 150 * 50, 160 * 50, 170 * 50, 180 * 50, 190 * 50, 200 * 50, +]; + +export const KMART_DPI_STAGE_COUNT = 6; + +const POLLING_INTERVALS: Readonly> = { 125: 8, 250: 4, 500: 2, 1000: 1 }; +export const KMART_POLLING_RATES = [125, 250, 500, 1000] as const; + +export interface KmartStatus { + /** False while the mouse sleeps or its radio link is idle (byte 2 is 0x02). */ + linked: boolean; + firmwareTag: string; + sensor: number; + /** Zero-based active DPI stage. */ + activeStage: number; + enabledStageCount: number; + pollingRateHz: number | null; + batteryPercent: number; + /** 0 on battery, 1 charging, 2 full (the configurator then shows 100%). */ + chargeState: number; +} + +/** Builds one request payload (report ID excluded). */ +export function kmartRequest(command: number, sequence: number, data: readonly number[] = [], write = false): Uint8Array { + if (!Number.isInteger(command) || command < 1 || command > 255) throw new RangeError("Invalid Kmart command."); + if (data.length > KMART_MAX_DATA) throw new RangeError("Kmart payload too long."); + const bytes = new Uint8Array(KMART_REPORT_SIZE); + bytes[0] = 0x01; + bytes[1] = command; + bytes[3] = sequence & 0xff; + if (write) { + bytes[4] = 0x01; + bytes[5] = data.length; + data.forEach((value, index) => { + if (!Number.isInteger(value) || value < 0 || value > 255) throw new RangeError("Invalid Kmart payload byte."); + bytes[6 + index] = value; + }); + } + return bytes; +} + +/** Normalises a feature-report read to the 32-byte payload, dropping a leading report ID if present. */ +export function kmartPayload(source: DataView | Uint8Array): Uint8Array { + const bytes = source instanceof Uint8Array + ? source + : new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + return bytes[0] === KMART_REPORT_ID && bytes[1] === 0x01 ? bytes.subarray(1) : bytes; +} + +export function kmartPollingInterval(rateHz: number): number { + const interval = POLLING_INTERVALS[rateHz]; + if (!interval) throw new RangeError(`Unsupported Kmart polling rate ${rateHz}.`); + return interval; +} + +export function kmartPollingRate(intervalMs: number): number | null { + const entry = Object.entries(POLLING_INTERVALS).find(([, interval]) => interval === intervalMs); + return entry ? Number(entry[0]) : null; +} + +export function kmartDecodeStatus(source: DataView | Uint8Array): KmartStatus { + const bytes = kmartPayload(source); + if (bytes.length < 21 || bytes[1] !== KMART_COMMAND.status) throw new Error("Invalid Kmart status reply."); + const tag = String.fromCharCode(bytes[7]!, bytes[8]!, bytes[9]!, bytes[10]!); + if (tag !== "M361") throw new Error("Kmart status reply has an unknown signature."); + const stageByte = bytes[15]!; + return { + linked: bytes[2] === 0x00 && bytes[20] === 0x01, + firmwareTag: tag + String.fromCharCode(bytes[11]!), + sensor: bytes[14]!, + activeStage: Math.max(0, (stageByte >> 4) - 1), + enabledStageCount: stageByte & 0x0f, + pollingRateHz: kmartPollingRate(bytes[16]!), + batteryPercent: bytes[18] === 2 ? 100 : Math.min(100, bytes[17]!), + chargeState: bytes[18]!, + }; +} + +/** Wire code for a DPI on the PMW3325 ladder. */ +export function kmartPmw3325DpiCode(dpi: number): number { + const index = KMART_PMW3325_DPI_VALUES.indexOf(dpi); + if (index < 0) throw new RangeError(`DPI ${dpi} is not on the Kmart PMW3325 ladder.`); + return index + 1; +} + +/** + * Data bytes for command 0x05: (active+1)<<4 | enabled count, enabled-stage + * mask, then six little-endian stage codes and four zero bytes. + */ +export function kmartDpiStagesData(stagesDpi: readonly number[], activeStage: number): number[] { + if (stagesDpi.length < 1 || stagesDpi.length > KMART_DPI_STAGE_COUNT) throw new RangeError("Kmart supports 1–6 DPI stages."); + if (!Number.isInteger(activeStage) || activeStage < 0 || activeStage >= stagesDpi.length) { + throw new RangeError("Active DPI stage is out of range."); + } + const data = new Array(18).fill(0); + data[0] = ((activeStage + 1) << 4) | stagesDpi.length; + data[1] = (1 << stagesDpi.length) - 1; + stagesDpi.forEach((dpi, index) => { + const code = kmartPmw3325DpiCode(dpi); + data[2 + index * 2] = code & 0xff; + data[3 + index * 2] = code >> 8; + }); + return data; +} From be5b2c488768abf44a7f377b00765aa8e9757a06 Mon Sep 17 00:00:00 2001 From: FeetusDeletus12 Date: Sun, 8 Nov 2026 16:09:22 +1100 Subject: [PATCH 2/3] fix(kmart): button mapping is command 0x04; 0x06 is DPI colours --- src/kmart/index.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/kmart/index.ts b/src/kmart/index.ts index 58f4008..6c9dfbd 100644 --- a/src/kmart/index.ts +++ b/src/kmart/index.ts @@ -26,8 +26,10 @@ export const KMART_COMMAND = { status: 0x20, /** Six DPI stages, the enabled-stage mask and the active stage (18 bytes). */ dpiStages: 0x05, - /** Eight button assignments, three bytes each (24 bytes). Not driven yet. */ - buttons: 0x06, + /** One button assignment: key index 0–5, then three action bytes (4 bytes). Not driven yet. */ + buttons: 0x04, + /** Eight RGB colours, probably the DPI-stage indicator (24 bytes). Not driven yet. */ + dpiColors: 0x06, /** USB report interval in milliseconds (1 byte). */ pollingInterval: 0x07, /** Lighting effect block (25 bytes). Not driven yet. */ From a74502c0f137a9fed52ee5638402aa19936b1791 Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:33:30 -0600 Subject: [PATCH 3/3] fix(kmart): address review feedback on the Kmart driver Keep the device's enabled DPI stage count when writing stages, match status replies by echoed sequence byte, serialise close() through the queue, accept unknown firmware tags, stop defaulting unknown polling to 125 Hz, skip the link check on the unverified wired PID, and drop redundant buffer copies. --- src/drivers/kmart/hid.test.ts | 61 ++++++++++++++++++++++++++++++++--- src/drivers/kmart/hid.ts | 33 +++++++++++++------ src/drivers/registry.test.ts | 11 +++++++ src/kmart/index.test.ts | 5 +++ src/kmart/index.ts | 18 +++++++---- 5 files changed, 108 insertions(+), 20 deletions(-) diff --git a/src/drivers/kmart/hid.test.ts b/src/drivers/kmart/hid.test.ts index 8edc928..ce1a9ce 100644 --- a/src/drivers/kmart/hid.test.ts +++ b/src/drivers/kmart/hid.test.ts @@ -3,14 +3,18 @@ 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 } = {}) { - let interval = 8; - let stageByte = 0x36; +function device(options: { + asleep?: boolean; ignoreWrites?: boolean; sensor?: number; productId?: number; stageByte?: number; + staleReplies?: number; interval?: number; onSend?: () => Promise; +} = {}) { + 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: 0x5b2f, + productId: options.productId ?? 0x5b2f, productName: "Wireless-Receiver", opened: false, collections: [{ @@ -23,6 +27,7 @@ function device(options: { asleep?: boolean; ignoreWrites?: boolean; sensor?: nu 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]!; @@ -33,7 +38,7 @@ function device(options: { asleep?: boolean; ignoreWrites?: boolean; sensor?: nu 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, pending[3]!, 0x01, 0x10, 0x00, 0x4d, 0x33, 0x36, 0x31, 0x32, + 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); }, @@ -84,3 +89,49 @@ test("Kmart refuses writes while the mouse sleeps or on an unverified sensor", a 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((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); +}); diff --git a/src/drivers/kmart/hid.ts b/src/drivers/kmart/hid.ts index 7d809d5..ad39cb9 100644 --- a/src/drivers/kmart/hid.ts +++ b/src/drivers/kmart/hid.ts @@ -10,6 +10,7 @@ const PRODUCT_IDS = new Set(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]; @@ -49,12 +50,16 @@ export class KmartHidClient { if (!this.device.opened) await this.device.open(); } - async close(): Promise { if (this.device.opened) await this.device.close(); } + async close(): Promise { + await this.run(async () => { if (this.device.opened) await this.device.close(); }); + } async startNotifications(_onChange?: () => void): Promise { return false; } async readStatus(): Promise { 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 { @@ -63,7 +68,7 @@ export class KmartHidClient { batteryPercent: status.batteryPercent, batteryState: status.chargeState === 1 ? "Charging" : status.chargeState === 2 ? "Full" : "Discharging", dpi: this.stages[stage]!, - pollingRateHz: status.pollingRateHz ?? 125, + pollingRateHz: status.pollingRateHz, supportedPollingRates: this.getSupportedPollingRates(), activeProfile: null, connectionType: receiver ? "Wireless" : "Wired", @@ -90,10 +95,13 @@ export class KmartHidClient { if (status.sensor !== KMART_SENSOR_PMW3325) { throw new Error(`Kmart sensor 0x${status.sensor.toString(16)} has no verified DPI table.`); } - const stage = Math.min(status.activeStage, KMART_DPI_STAGE_COUNT - 1); + // 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)); + await this.write(KMART_COMMAND.dpiStages, kmartDpiStagesData(stages, stage, enabled)); this.stages = stages; return dpi; }); @@ -112,20 +120,27 @@ export class KmartHidClient { private async requireLinked(): Promise { const status = await this.queryStatus(); - if (!status.linked) throw new Error("The mouse is asleep. Move it, then try again."); + // 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 { await this.open(); - await this.device.sendFeatureReport(KMART_REPORT_ID, new Uint8Array(kmartRequest(KMART_COMMAND.status, this.nextSequence())).buffer); - await sleep(READ_PAUSE_MS); - return kmartDecodeStatus(kmartPayload(await this.device.receiveFeatureReport(KMART_REPORT_ID))); + 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 { await this.open(); - await this.device.sendFeatureReport(KMART_REPORT_ID, new Uint8Array(kmartRequest(command, this.nextSequence(), data, true)).buffer); + await this.device.sendFeatureReport(KMART_REPORT_ID, kmartRequest(command, this.nextSequence(), data, true)); await sleep(WRITE_PAUSE_MS); } diff --git a/src/drivers/registry.test.ts b/src/drivers/registry.test.ts index 8109820..e802280 100644 --- a/src/drivers/registry.test.ts +++ b/src/drivers/registry.test.ts @@ -18,6 +18,7 @@ import { DELUX_OEM_VENDOR_ID, } 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 { REDGEAR_X13_VENDOR_ID, REDGEAR_X13_PRODUCT_ID, @@ -34,6 +35,16 @@ test("Redgear picker filter uses the protocol identity constants", () => { ); }); +test("Kmart picker filters use the protocol identity constants", () => { + assert.equal(VENDOR_ID.kmart, KMART_VENDOR_ID); + assert.deepEqual( + SUPPORTED_HID_FILTERS.filter((filter) => filter.vendorId === KMART_VENDOR_ID), + KMART_PRODUCT_IDS.map((productId) => ({ + vendorId: KMART_VENDOR_ID, productId, usagePage: KMART_USAGE_PAGE, usage: KMART_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/kmart/index.test.ts b/src/kmart/index.test.ts index 3ae724f..e872629 100644 --- a/src/kmart/index.test.ts +++ b/src/kmart/index.test.ts @@ -42,6 +42,9 @@ test("Kmart decodes a captured status reply with or without the report ID", () = const corrupt = CAPTURED_STATUS.slice(); corrupt[8] = 0; assert.throws(() => kmartDecodeStatus(corrupt)); + const newer = CAPTURED_STATUS.slice(); + newer[11] = 0x32; + assert.equal(kmartDecodeStatus(newer).firmwareTag, "M3622"); }); test("Kmart DPI stages encode the bytes verified on hardware", () => { @@ -54,6 +57,8 @@ test("Kmart DPI stages encode the bytes verified on hardware", () => { ); assert.throws(() => kmartPmw3325DpiCode(450), RangeError); assert.throws(() => kmartDpiStagesData([400], 1), RangeError); + assert.deepEqual(kmartDpiStagesData([400, 800, 1600, 2400, 3200, 6400], 1, 4).slice(0, 2), [0x24, 0x0f]); + assert.throws(() => kmartDpiStagesData([400, 800], 1, 1), RangeError); }); test("Kmart polling uses report intervals in milliseconds", () => { diff --git a/src/kmart/index.ts b/src/kmart/index.ts index 6c9dfbd..50fd8cf 100644 --- a/src/kmart/index.ts +++ b/src/kmart/index.ts @@ -68,7 +68,7 @@ export interface KmartStatus { } /** Builds one request payload (report ID excluded). */ -export function kmartRequest(command: number, sequence: number, data: readonly number[] = [], write = false): Uint8Array { +export function kmartRequest(command: number, sequence: number, data: readonly number[] = [], write = false): Uint8Array { if (!Number.isInteger(command) || command < 1 || command > 255) throw new RangeError("Invalid Kmart command."); if (data.length > KMART_MAX_DATA) throw new RangeError("Kmart payload too long."); const bytes = new Uint8Array(KMART_REPORT_SIZE); @@ -109,7 +109,8 @@ export function kmartDecodeStatus(source: DataView | Uint8Array): KmartStatus { const bytes = kmartPayload(source); if (bytes.length < 21 || bytes[1] !== KMART_COMMAND.status) throw new Error("Invalid Kmart status reply."); const tag = String.fromCharCode(bytes[7]!, bytes[8]!, bytes[9]!, bytes[10]!); - if (tag !== "M361") throw new Error("Kmart status reply has an unknown signature."); + // Only the "M" prefix is checked so other firmware revisions still decode. + if (tag[0] !== "M") throw new Error("Kmart status reply has an unknown signature."); const stageByte = bytes[15]!; return { linked: bytes[2] === 0x00 && bytes[20] === 0x01, @@ -134,14 +135,19 @@ export function kmartPmw3325DpiCode(dpi: number): number { * Data bytes for command 0x05: (active+1)<<4 | enabled count, enabled-stage * mask, then six little-endian stage codes and four zero bytes. */ -export function kmartDpiStagesData(stagesDpi: readonly number[], activeStage: number): number[] { +export function kmartDpiStagesData( + stagesDpi: readonly number[], activeStage: number, enabledCount = stagesDpi.length, +): number[] { if (stagesDpi.length < 1 || stagesDpi.length > KMART_DPI_STAGE_COUNT) throw new RangeError("Kmart supports 1–6 DPI stages."); - if (!Number.isInteger(activeStage) || activeStage < 0 || activeStage >= stagesDpi.length) { + if (!Number.isInteger(enabledCount) || enabledCount < 1 || enabledCount > stagesDpi.length) { + throw new RangeError("Enabled DPI stage count is out of range."); + } + if (!Number.isInteger(activeStage) || activeStage < 0 || activeStage >= enabledCount) { throw new RangeError("Active DPI stage is out of range."); } const data = new Array(18).fill(0); - data[0] = ((activeStage + 1) << 4) | stagesDpi.length; - data[1] = (1 << stagesDpi.length) - 1; + data[0] = ((activeStage + 1) << 4) | enabledCount; + data[1] = (1 << enabledCount) - 1; stagesDpi.forEach((dpi, index) => { const code = kmartPmw3325DpiCode(dpi); data[2 + index * 2] = code & 0xff;