Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
63 changes: 63 additions & 0 deletions docs/logitech-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,66 @@ legacy zones; it advertises `0x8060` report rate, which this driver does not
implement. No write path was exercised, so the catalog entries stay
`verified: false`.

### K400 / K400 Plus

The K400 (wpids `0x400E`, `0x4024`) and K400 Plus (`0x404D`) are Unifying
office keyboards, catalogued from [Solaar's device descriptors](https://github.com/pwr-Solaar/Solaar/blob/master/lib/logitech_receiver/descriptors.py)
rather than G HUB. They have no USB product id of their own, so they are only
reached through a Unifying receiver (`0xC52B`, `0xC532`). Older firmware may
not implement `0x0003` deviceInformation; when no slot names a catalogued
keyboard that way, the driver reads the receiver's HID++ 1.0 pairing register
(`0x83 0xB5`, sub-address `0x20 + slot - 1`, wpid at bytes 3–4 of the reply)
and addresses the slot whose wpid is catalogued, as Solaar does.

Battery comes from the original `0x1000` batteryStatus (`[level%, next%,
status]`, read with fn 0) when neither `0x1004` nor `0x1001` is advertised.
Fn inversion (`0x40A0`, or `0x40A2` when that is absent) reads bit 0 of fn 0
and writes `[state]` with fn 1, verified by a read-back. `0x40A3` (K375s-style
Fn swap with a `0xFF` prefix) is not implemented.

A K400 Plus (wpid `0x404D`, HID++ 4.1) on a `0xC52B` receiver was probed
read-only and then driven through OpenMouse. It advertises `0x0003`, `0x0005`,
`0x1000`, `0x1B04`, `0x2005`, `0x40A2`, `0x4100`, `0x4521`, `0x6100`, `0x6501`
and engineering features. Fn inversion over `0x40A2` was switched in the app
and the F-row behaviour changed. Further settings follow Solaar's handling:

- `0x4521` keyboardDisableKeys: fn 0 capability mask, fn 1 disabled mask, fn 2
writes the mask (bits 1 Caps Lock, 2 Num Lock, 4 Scroll Lock, 8 Insert, 16
Win). This board reports `0x1D` (no Num Lock). Writes are read back.
- `0x6501` gesture2: fn 0 pages eight `[high, low]` fields per call until
`high == 0x01`; enable bits are numbered in field order over gestures that
can be enabled or default on. Fn 1 `[offset, 1, 0xFF]` reads an enable byte,
fn 2 `[offset, 1, mask, value]` (long report) writes one bit. Parameter 4 is
the pointer scale factor, big-endian, 256 = normal: fn 7 `[index, 0xFF]`
reads it, fn 6 the default, fn 8 `[index, value…, 0xFF]` writes it. Only
gesture 34 (Fn+click suppression) is flagged persistent; the other gesture
settings are lost when the keyboard powers off.

Only gesture 34 survives a power cycle. Fn inversion and the disabled keys
are lost as well, though neither feature reports persistence; Logi Options+
and Solaar keep these settings on the host and write them again after each
reconnect.

Results on that K400 Plus, Windows 11, through the OpenMouse UI:

| Setting | Result |
| --- | --- |
| Fn inversion (`0x40A2`) | Works; lost when the keyboard powers off |
| Disable keys (`0x4521`) | Works; lost when the keyboard powers off (mask read back as `0x00`) |
| Pointer speed (`0x6501` parameter 4) | Works; lost when the keyboard powers off |
| Natural scrolling (gesture 45) | Works; lost when the keyboard powers off |
| Taps (gestures 1, 2, 10, 30) | Bits change and read back, no effect. The firmware does not flag them `showInUi`; tapping follows gesture 34 instead |
| Edge swipes (64, 65, 67), pinch zoom (84) | Bits change and read back, no visible effect. Flagged `showInUi`, but these are Windows 8 charm gestures |

The status reports every switchable gesture with its `showInUi` flag; the
OpenMouse panel offers natural scrolling, the two scroll axes and gesture 34
only. Battery was read at 90% over `0x1000`.
- `0x1B04` lists 20 controls, all in group 0 with no remap targets, so there is
no firmware remap. Logi Options+ reassigns those keys by diverting them to
host software, which a web page cannot keep running.
- `0x2005` (swap button cancel) and `0x6100` (raw touchpad reports) have no
setting here.

## Transport

HID++ 2.0 rides on usage page `0xFF00` (USB) or `0xFF43` (Bluetooth). Requests
Expand All @@ -95,6 +155,9 @@ transport.
| --- | --- | --- | --- |
| Identity | `0x0003` | `getDeviceInfo`, `getFwInfo`, `getSerialNumber` | Unit id, transport bits, model ids, firmware version, serial when advertised. |
| Battery | `0x1004` | `getBatteryCapabilities`, `getBatteryInfo` | Percentage only when the gauge capability is set; otherwise the coarse level. |
| Battery (legacy) | `0x1001`, `0x1000` | `getBatteryVoltage`, `getBatteryLevelStatus` | Voltage curve for `0x1001`; reported percentage and charge status for `0x1000` (K400 family). |
| Fn inversion | `0x40A0`, `0x40A2` | `getFnInversion`, `setFnInversion` | Reads and toggles whether F1–F12 or the media keys are the default, with read-back. |
| Unifying pairing | Receiver register `0xB5` | HID++ 1.0 long register read | Names a paired keyboard by wpid when it lacks `0x0003`. |
| Polling rate | `0x8061` | `getActualReportRateList`, `getReportRate`, `setReportRate` | Reads the advertised mask, writes a discriminant and verifies the read-back. |
| Brightness and illumination | `0x8040` | functions 0–4 | Reads the range and current brightness; writes big-endian brightness and verifies it. When the illumination capability is advertised, reads and toggles backlight power independently, with read-back. |
| Receiver | HID++ pairing slots 1–6 | Root `getFeature` + `0x0003` device information | Probes each slot, matches the reported model ids against the keyboard catalog, and addresses that device index. |
Expand Down
262 changes: 262 additions & 0 deletions src/drivers/logitech/hid.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -916,3 +916,265 @@ test("closing a receiver endpoint discards a late feature lookup before it can s
await result;
assert.deepEqual(requests, [0]);
});

/**
* A Unifying receiver with one K400-family keyboard that, like the older
* firmware, does not implement 0x0003 deviceInformation. Only the receiver's
* HID++ 1.0 pairing register can name it.
*/
class FakeUnifyingK400 {
vendorId = LOGITECH_VENDOR_ID;
productId = 0xc52b;
productName = "USB Receiver";
opened = false;
slot = 2;
wpid = 0x404d;
fnFeature: 0x40a0 | 0x40a2 | null = 0x40a0;
fnInverted = false;
ignoreFnWrite = false;
battery = [70, 50, 0];
supportsSettings = true;
disableCapabilities = 0x1d;
disabledMask = 0x00;
// 0x6501 fn 0 fields as read from a K400 Plus (firmware on wpid 0x404d).
gestureFields: [number, number][] = [
[0x42, 3], [0x41, 1], [0x41, 2], [0x04, 0], [0x22, 4], [0x80, 20], [0x8c, 33], [0xa3, 1],
[0xa3, 2], [0xa1, 30], [0xa3, 10], [0x41, 5], [0x82, 44], [0x85, 45], [0xad, 42], [0xad, 43],
[0x8f, 64], [0x8f, 65], [0x8f, 67], [0x42, 4], [0xaf, 84], [0x91, 34], [0x82, 85], [0x82, 100],
[0x01, 0],
];
gestureBitmap = [0x6f, 0x00];
pointerScale = 256;
/** Keyboard requests to ignore after the slot is named, as a dozing keyboard does. */
dropAfterPairing = 0;
private paired = false;
collections = [
{ usagePage: 0xff00, usage: 1, inputReports: [], outputReports: [], featureReports: [], children: [] },
{ usagePage: 0xff00, usage: 2, inputReports: [], outputReports: [], featureReports: [], children: [] },
];
writes: { deviceIndex: number; featureIndex: number; functionByte: number; params: number[] }[] = [];
private listeners = new Set<(event: HIDInputReportEvent) => void>();

async open(): Promise<void> { this.opened = true; }
async close(): Promise<void> { this.opened = false; }
addEventListener(_type: "inputreport", listener: (event: HIDInputReportEvent) => void): void { this.listeners.add(listener); }
removeEventListener(_type: "inputreport", listener: (event: HIDInputReportEvent) => void): void { this.listeners.delete(listener); }

private emit(bytes: readonly number[]): void {
const data = new Uint8Array(19);
data.set(bytes);
const event = { reportId: LOGITECH_LONG_REPORT_ID, data: new DataView(data.buffer), device: this } as unknown as HIDInputReportEvent;
for (const listener of this.listeners) listener(event);
}

async sendReport(_reportId: number, source: BufferSource): Promise<void> {
const data = source instanceof ArrayBuffer
? new Uint8Array(source)
: new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
const [deviceIndex = 0, featureIndex = 0, functionByte = 0] = data;
const params = [...data.slice(3)];
this.writes.push({ deviceIndex, featureIndex, functionByte, params });
if (deviceIndex === 0xff && featureIndex === 0x83 && functionByte === 0xb5) {
const sub = params[0] ?? 0;
if (this.wpid !== null && sub === 0x20 + this.slot - 1) {
this.emit([0xff, 0x83, 0xb5, sub, 0x11, 0x08, this.wpid >> 8, this.wpid & 0xff, 0x00, 0x00, 0x01]);
this.paired = true;
} else {
this.emit([0xff, 0x8f, 0x83, 0xb5, 0x02]);
}
return;
}
if (deviceIndex !== this.slot) {
// HID++ 1.0 "unknown device" from the receiver.
this.emit([deviceIndex, 0x8f, featureIndex, functionByte, 0x08]);
return;
}
if (this.paired && this.dropAfterPairing > 0) {
this.dropAfterPairing -= 1;
return;
}
const functionId = functionByte >> 4;
const reply = (index: number, values: readonly number[]) => this.emit([this.slot, index, functionByte, ...values]);
if (featureIndex === 0 && functionId === 0) {
const featureId = ((params[0] ?? 0) << 8) | (params[1] ?? 0);
const index = featureId === 0x1000 ? 2 : featureId === this.fnFeature ? 3
: this.supportsSettings && featureId === 0x4521 ? 4 : this.supportsSettings && featureId === 0x6501 ? 5 : 0;
reply(0, [index, 0x00, 0x00]);
return;
}
if (featureIndex === 4) {
if (functionId === 0) { reply(4, [this.disableCapabilities]); return; }
if (functionId === 1) { reply(4, [this.disabledMask]); return; }
if (functionId === 2) { this.disabledMask = (params[0] ?? 0) & this.disableCapabilities; reply(4, []); return; }
}
if (featureIndex === 5) {
if (functionId === 0) {
const start = ((params[0] ?? 0) << 8) | (params[1] ?? 0);
const page = this.gestureFields.slice(start, start + 8);
while (page.length < 8) page.push([0x01, 0x00]);
reply(5, page.flat());
return;
}
if (functionId === 1) { reply(5, [this.gestureBitmap[params[0] ?? 0] ?? 0]); return; }
if (functionId === 2) {
const [offset = 0, , mask = 0, value = 0] = params;
this.gestureBitmap[offset] = ((this.gestureBitmap[offset] ?? 0) & ~mask) | (value & mask);
reply(5, []);
return;
}
if (functionId === 6) { reply(5, [0x01, 0x00]); return; }
if (functionId === 7) { reply(5, [this.pointerScale >> 8, this.pointerScale & 0xff]); return; }
if (functionId === 8) {
if ((params[3] ?? 0) === 0xff) this.pointerScale = ((params[1] ?? 0) << 8) | (params[2] ?? 0);
reply(5, []);
return;
}
}
if (featureIndex === 2 && functionId === 0) { reply(2, this.battery); return; }
if (featureIndex === 3 && functionId === 0) { reply(3, [Number(this.fnInverted)]); return; }
if (featureIndex === 3 && functionId === 1) {
if (!this.ignoreFnWrite) this.fnInverted = ((params[0] ?? 0) & 1) === 1;
reply(3, []);
return;
}
// HID++ 2.0 "invalid function" for anything else.
this.emit([this.slot, 0xff, featureIndex, functionByte, 0x07]);
}

async sendFeatureReport(): Promise<void> { throw new Error("not used"); }
async receiveFeatureReport(): Promise<DataView> { throw new Error("not used"); }
}

test("a K400 Plus without 0x0003 is found through the Unifying pairing register", async () => {
const device = new FakeUnifyingK400();
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
const status = await client.readStatus();
assert.equal(status.name, "K400 Plus");
assert.equal(status.connectionDetail, "Unifying receiver");
assert.equal(status.logitech?.productId, 0x404d);
assert.equal(status.logitech?.receiverProductId, 0xc52b);
assert.deepEqual(status.logitech?.battery, { percent: 70, level: "good", status: "discharging" });
assert.equal(status.logitech?.fnInversion, false);
assert.match(status.ui?.statusNote ?? "", /Solaar's device descriptors/);
// The keyboard slot, not the receiver, answers the HID++ 2.0 requests.
assert.ok(device.writes.some(write => write.deviceIndex === 2 && write.featureIndex === 2));
});

test("Fn inversion is written and confirmed by a read-back", async () => {
const device = new FakeUnifyingK400();
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
assert.equal(await client.setFnInversion(true), true);
assert.equal(device.fnInverted, true);
assert.deepEqual(device.writes.find(write => write.featureIndex === 3 && write.functionByte >> 4 === 1)?.params.slice(0, 1), [1]);
assert.equal(await client.setFnInversion(false), false);
});

test("the newer 0x40A2 Fn inversion is used when 0x40A0 is absent", async () => {
const device = new FakeUnifyingK400();
device.fnFeature = 0x40a2;
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
assert.equal((await client.readStatus()).logitech?.fnInversion, false);
assert.equal(await client.setFnInversion(true), true);
});

test("an Fn inversion the keyboard does not apply is reported, and a missing feature refuses to write", async () => {
const device = new FakeUnifyingK400();
device.ignoreFnWrite = true;
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
await assert.rejects(client.setFnInversion(true), /did not confirm/);

const bare = new FakeUnifyingK400();
bare.fnFeature = null;
const bareClient = new LogitechKeyboardHidClient(bare as unknown as HIDDevice);
assert.equal((await bareClient.readStatus()).logitech?.fnInversion, null);
await assert.rejects(bareClient.setFnInversion(true), /does not expose an Fn-inversion feature/);
assert.ok(!bare.writes.some(write => write.featureIndex === 3));
});

test("a Unifying receiver with only an unknown wpid paired has no supported keyboard", async () => {
const device = new FakeUnifyingK400();
device.wpid = 0x4051; // Not a catalogued keyboard.
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
await assert.rejects(client.readStatus(), /no supported keyboard paired/);
});

test("K400 Plus status lists disableable keys and the switchable touchpad gestures", async () => {
const device = new FakeUnifyingK400();
device.disabledMask = 0x10;
const status = await new LogitechKeyboardHidClient(device as unknown as HIDDevice).readStatus();
assert.deepEqual(status.logitech?.disabledKeys, { supported: ["capsLock", "scrollLock", "insert", "windows"], disabled: ["windows"] });
const gestures = status.logitech?.touchpad?.gestures ?? [];
// Twelve gestures can be switched; fixed ones (tracking, tap group, raw data) are left out.
assert.deepEqual(gestures.map(gesture => gesture.id), [1, 2, 30, 10, 45, 42, 43, 64, 65, 67, 84, 34]);
const enabled = Object.fromEntries(gestures.map(gesture => [gesture.id, gesture.enabled]));
// Bitmap 0x6f: taps, drag, double tap and both two-finger scrolls on; natural scrolling off.
assert.equal(enabled[1], true);
assert.equal(enabled[45], false);
assert.equal(enabled[43], true);
assert.equal(enabled[84], false);
assert.equal(gestures.find(gesture => gesture.id === 34)?.persistent, true);
// The firmware flags scrolling, edge swipes and zoom for a settings UI, but not the taps.
assert.deepEqual(gestures.filter(gesture => gesture.showInUi).map(gesture => gesture.id), [45, 42, 43, 64, 65, 67, 84]);
assert.deepEqual(status.logitech?.touchpad?.pointerSpeed, { value: 256, defaultValue: 256, min: 0x2e, max: 0x1ff });
});

test("disabled keys are written as one mask and confirmed; unsupported keys are refused", async () => {
const device = new FakeUnifyingK400();
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
assert.deepEqual((await client.setDisabledKeys(["capsLock", "windows"])).disabled, ["capsLock", "windows"]);
assert.equal(device.disabledMask, 0x11);
await assert.rejects(client.setDisabledKeys(["numLock"]), /cannot disable: numLock/);
assert.equal(device.disabledMask, 0x11);
});

test("a gesture change writes [offset, 1, mask, value] in a long report and reads the bit back", async () => {
const device = new FakeUnifyingK400();
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
// Natural scrolling is enable index 4; zoom is index 10 (byte 1, bit 2).
assert.equal(await client.setGesture(45, true), true);
assert.equal(device.gestureBitmap[0], 0x7f);
assert.equal(await client.setGesture(84, true), true);
assert.equal(device.gestureBitmap[1], 0x04);
assert.equal(await client.setGesture(1, false), false);
assert.equal(device.gestureBitmap[0], 0x7e);
const write = device.writes.find(entry => entry.featureIndex === 5 && entry.functionByte >> 4 === 2);
assert.deepEqual(write?.params.slice(0, 4), [0, 1, 0x10, 0x10]);
// A gesture the firmware does not let the host switch is refused.
await assert.rejects(client.setGesture(20, true), /does not let gesture 20 be switched/);
});

test("pointer speed is written big-endian with the 0xFF terminator and range-checked", async () => {
const device = new FakeUnifyingK400();
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
assert.equal(await client.setPointerSpeed(384), 384);
assert.equal(device.pointerScale, 384);
const write = device.writes.find(entry => entry.featureIndex === 5 && entry.functionByte >> 4 === 8);
assert.deepEqual(write?.params.slice(0, 4), [0, 0x01, 0x80, 0xff]);
await assert.rejects(client.setPointerSpeed(0x200), RangeError);
await assert.rejects(client.setPointerSpeed(10), RangeError);
});

test("keyboards without 0x4521 or 0x6501 report neither setting", async () => {
const device = new FakeUnifyingK400();
device.supportsSettings = false;
const client = new LogitechKeyboardHidClient(device as unknown as HIDDevice);
const status = await client.readStatus();
assert.equal(status.logitech?.disabledKeys, null);
assert.equal(status.logitech?.touchpad, null);
await assert.rejects(client.setDisabledKeys([]), /does not expose a disable-keys feature/);
await assert.rejects(client.setPointerSpeed(256), /does not expose a pointer-speed setting/);
});

test("a keyboard dozing behind a direct Unifying receiver gets one identity retry", async () => {
const device = new FakeUnifyingK400();
// The first keyboard request after the slot is named goes unanswered.
device.dropAfterPairing = 1;
const status = await new LogitechKeyboardHidClient(device as unknown as HIDDevice).readStatus();
assert.equal(status.name, "K400 Plus");
assert.equal(status.logitech?.fnInversion, false);

// Two missed identity reads in a row still fail instead of retrying forever.
const asleep = new FakeUnifyingK400();
asleep.dropAfterPairing = 2;
await assert.rejects(new LogitechKeyboardHidClient(asleep as unknown as HIDDevice).readStatus(), { name: "TimeoutError" });
});
Loading