diff --git a/README.md b/README.md index 8a15aeab..a863a6c5 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ checklist. | --- | --- | | A4Tech Bloody R36 Ultra | `@openmouse/protocol/a4tech` | | AJAZZ | `@openmouse/protocol/ajazz` | +| Angry Miao | `@openmouse/protocol/angry-miao` | | ATK | `@openmouse/protocol/atk` | | Corsair | `@openmouse/protocol/corsair` | | Dareu | `@openmouse/protocol/dareu` | diff --git a/captures/angry-miao-infinity/bluetooth-reads.json b/captures/angry-miao-infinity/bluetooth-reads.json new file mode 100644 index 00000000..00f42707 --- /dev/null +++ b/captures/angry-miao-infinity/bluetooth-reads.json @@ -0,0 +1,27 @@ +{ + "model": "Angry Miao Infinity .100 (AM30)", + "firmware": { + "mouseSoc": "0x0318 (vendor 1.1.1)" + }, + "date": "2026-12-03", + "os": "macOS", + "transport": "Bluetooth", + "vendorId": 12625, + "productId": 16428, + "productName": "AM INFINITY BT MOUSE", + "collections": "0x0001:0x0006, 0x000C:0x0001 (input 2), 0x0001:0x0080, 0x0001:0x0006, 0x0001:0x0002, 0xFF55:0x0202 (input 6, output 6)", + "source": "OpenMouse on Bluetooth, recorded with a passive WebHID logger on sendReport and input reports, before the Angry Miao driver handled 3151:402C. Reads only.", + "notes": { + "framing": "Every command is sent as output report 6: byte 0 = 0x55, then the same checksummed command as on the cable. The reply is input report 6 with the same 0x55 byte in front of the cable reply.", + "battery": "0x77 is a Bluetooth-only request; byte 1 of the reply is the battery percent (0x4E = 78). Bytes 2-3 (18 03) match the SoC firmware code but are not decoded.", + "replies": "8F, 80, D4, D3 and D0 answer with the same layout as on the cable. D0 does not echo its command byte." + }, + "replies": { + "battery": { "request": "7700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "reply": "774e180300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + "deviceId": { "request": "558f000000000000700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "reply": "558fae0800000000700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + "firmware": { "request": "55800000000000007f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "reply": "55801803000000007f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + "dpi": { "request": "55d40000000000002b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "reply": "55d40003080000002b90012003b0044006800c00191027307590012003b0044006800c001910273075ff0000ff3200ffff0000ff0000ffff0000ffff00ffffffff" }, + "option0": { "request": "55d30000000000002c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "reply": "55d30000000000002c00810f0000000c0101000000000000000000000000000000000000000000000058022c013c00b400000064640100ffffffffffff010f0300" }, + "keyMatrix": { "request": "55d00000000000002f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "reply": "550100f0000100f1000100f2000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff" } + } +} diff --git a/captures/angry-miao-infinity/cable-reads.json b/captures/angry-miao-infinity/cable-reads.json new file mode 100644 index 00000000..803f1232 --- /dev/null +++ b/captures/angry-miao-infinity/cable-reads.json @@ -0,0 +1,29 @@ +{ + "model": "Angry Miao Infinity .100 (AM30)", + "firmware": { "mouseUsb": "0x0101 (vendor 1.0.3)", "mouseSoc": "0x0318 (vendor 1.1.1)" }, + "date": "2026-12-01", + "os": "Windows 11", + "transport": "USB cable", + "vendorId": 12625, + "productId": 16426, + "usagePage": 65535, + "usage": 2, + "featureReportLength": 65, + "notes": { + "usbVersion": "0x8F read. Device id 2222 (0x08AE) is bytes 1-4 little-endian; byte 5 (0x06) is unidentified. Re-read in full on macOS on 2026-12-03; the first 16 bytes match the 2026-12-01 read.", + "firmware": "0x80 read. Bytes 1-2 are the SoC code 0x0318, shown as Mouse SoC 0x0318. Re-read in full on macOS on 2026-12-03; the first 16 bytes match the 2026-12-01 read.", + "usbFirmware": "0xAD read, recorded on macOS on 2026-12-03. Bytes 1-2 are the USB code 0x0101, shown as Mouse USB 0x0101.", + "dpi": "Full 64-byte reply.", + "option0": "Full 64-byte reply.", + "keyMatrix": "Full 64-byte reply for profile 0. No command echo byte; sixteen 4-byte slots.", + "reportDescriptor": "Not captured; only the collection capabilities were queried." + }, + "replies": { + "usbVersion": "8fae0800000600700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "firmware": "801803000000007f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "usbFirmware": "ad010100000000520000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "dpi": "d40003080000002b90012003b0044006800c00191027307590012003b0044006800c001910273075ff0000ff3200ffff0000ff0000ffff0000ffff00ffffffff", + "option0": "d30000000000002c0001030000000c01010000000000000000000000000000000000000000000000580200001e000000000064640100ffffffffffff00010100", + "keyMatrix": "0100f0000100f1000100f2000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff" + } +} diff --git a/captures/angry-miao-infinity/cable-vendor-writes.json b/captures/angry-miao-infinity/cable-vendor-writes.json new file mode 100644 index 00000000..504274ed --- /dev/null +++ b/captures/angry-miao-infinity/cable-vendor-writes.json @@ -0,0 +1,35 @@ +{ + "model": "Angry Miao Infinity .100 (AM30)", + "firmware": { "mouseUsb": "0x0101 (vendor 1.0.3)", "mouseSoc": "0x0318 (vendor 1.1.1)" }, + "date": "2026-12-02", + "os": "Windows 11", + "transport": "USB cable", + "vendorId": 12625, + "productId": 16426, + "source": "Vendor web configurator (ammaster.angrymiao.com, model page am30), recorded with a passive WebHID logger that wraps sendFeatureReport and receiveFeatureReport. Each setting was changed once and then restored.", + "notes": { + "reads": "Full 64-byte replies read before the changes. The final reads after all restores were identical. Compared with cable-reads.json, option0 differs only in bytes 42-43 (300), 46-47 (180) and 61-62 (3), all written by earlier vendor-app sessions.", + "writes": "Full 64-byte feature reports sent by the vendor app, in order. Writes get no reply. Each 0x53 write carries the whole parameter block; each 0x54 write carries the whole DPI table.", + "keyMatrixAfterRemap": "0xD0 read-back after the Back -> Middle click write. Slot 4 (offset 16) holds 01 00 f2 00." + }, + "reads": { + "option0": "d30000000000002c0001030000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00030300", + "dpi": "d40003080000002b90012003b0044006800c00191027307590012003b0044006800c001910273075ff0000ff3200ffff0000ff0000ffff0000ffff00ffffffff", + "keyMatrix": "0100f0000100f1000100f2000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff", + "keyMatrixAfterRemap": "0100f0000100f1000100f2000100f4000100f200140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff" + }, + "writes": [ + { "change": "polling rate 1000 -> 8000 Hz", "hex": "53000000000000ac00810f0000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff000f0300" }, + { "change": "polling rate 8000 -> 1000 Hz", "hex": "53000000000000ac0001030000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00030300" }, + { "change": "debounce 10 -> 5 ms", "hex": "53000000000000ac0001020000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00020200" }, + { "change": "debounce 5 -> 10 ms", "hex": "53000000000000ac0001030000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00030300" }, + { "change": "2.4 GHz standby 30 s -> never", "hex": "53000000000000ac0001030000000c0101000000000000000000000000000000000000000000000058022c01ffffb400000064640100ffffffffffff00030300" }, + { "change": "2.4 GHz standby never -> 30 s", "hex": "53000000000000ac0001030000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00030300" }, + { "change": "ripple control off -> on", "hex": "53000000000000ac0001030001000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00030300" }, + { "change": "ripple control on -> off", "hex": "53000000000000ac0001030000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00030300" }, + { "change": "DPI stage 8 colour #ffffff -> #d0021b", "hex": "54000308000000a090012003b0044006800c00191027307590012003b0044006800c001910273075ff0000ff3200ffff0000ff0000ffff0000ffff00ffd0021b" }, + { "change": "DPI stage 8 colour #d0021b -> #ffffff", "hex": "54000308000000a090012003b0044006800c00191027307590012003b0044006800c001910273075ff0000ff3200ffff0000ff0000ffff0000ffff00ffffffff" }, + { "change": "button Back -> Middle click", "hex": "50000400000000ab0100f20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "change": "button Middle click -> Back", "hex": "50000400000000ab0100f30000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" } + ] +} diff --git a/captures/angry-miao-infinity/dongle-reads.json b/captures/angry-miao-infinity/dongle-reads.json new file mode 100644 index 00000000..dec9a6f5 --- /dev/null +++ b/captures/angry-miao-infinity/dongle-reads.json @@ -0,0 +1,51 @@ +{ + "model": "Angry Miao Infinity .100 (AM30)", + "firmware": { + "mouseUsb": "0x0101 (vendor 1.0.3)", + "mouseSoc": "0x0318 (vendor 1.1.1)", + "receiverUsb": "0x0008 (vendor 1.0.7)", + "receiverRf": "240 (vendor 1.0.8)", + "receiverLed": "0x0109 (vendor 1.0.5)" + }, + "date": "2026-12-02", + "os": "Windows 11", + "transport": "2.4 GHz receiver", + "vendorId": 12625, + "productId": 20487, + "source": "Vendor web configurator (ammaster.angrymiao.com, model page am30), recorded with a passive WebHID logger. Reads only: the tabs were opened and nothing was changed.", + "notes": { + "status": "First 11 bytes of the 0xF7 reply. The rest of each 0xF7 reply repeats stale bytes from the previous relayed reply. Byte 0 = 1 when a relayed reply is ready, byte 5 = 1 when the receiver can take a command, byte 4 = 0 when the mouse is online. Byte 2 (0x64) matches the receiver battery the vendor app shows.", + "exchange": "One complete relayed read of 0xD4, in order. The vendor app sends F6 05 and FE 40 before every mouse command, polls F7 about every 100 ms until byte 0 = 1, then sends FC and reads the reply.", + "relayed": "Replies read after FC. option0, dpi and keyMatrix are byte for byte the same as the cable reads in cable-vendor-writes.json." + }, + "status": { + "idle": "0000640100010200000163", + "busy": "0000640100000200000163", + "replyReady": "0100640100010200000163" + }, + "exchange": [ + { "dir": "send", "hex": "f6050000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "send", "hex": "f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "recv", "hex": "0000640100010200000163000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff" }, + { "dir": "send", "hex": "fe400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "send", "hex": "d40000000000002b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "send", "hex": "f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "recv", "hex": "0000640100000200000163000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff" }, + { "dir": "send", "hex": "f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "recv", "hex": "0000640100000200000163000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff" }, + { "dir": "send", "hex": "f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "recv", "hex": "0100640100010200000163000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff" }, + { "dir": "send", "hex": "fc000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, + { "dir": "recv", "hex": "d40003080000002b90012003b0044006800c00191027307590012003b0044006800c001910273075ff0000ff3200ffff0000ff0000ffff0000ffff00ffffffff" } + ], + "relayed": { + "option0": "d30000000000002c0001030000000c0101000000000000000000000000000000000000000000000058022c011e00b400000064640100ffffffffffff00030300", + "dpi": "d40003080000002b90012003b0044006800c00191027307590012003b0044006800c001910273075ff0000ff3200ffff0000ff0000ffff0000ffff00ffffffff", + "keyMatrix": "0100f0000100f1000100f2000100f4000100f300140000000a05000000000000000000000000000000000000000000000100f9010100f9ff0100f5010100f5ff", + "battery": "d6000164000000290000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "fpsMode": "e20000000000001d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "dpiButton": "e30000000000001c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "profileButton": "e40000000000001b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "sensorAngle": "e50000000000001a0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + } +} diff --git a/captures/angry-miao-infinity/openmouse-hardware-test-bluetooth.json b/captures/angry-miao-infinity/openmouse-hardware-test-bluetooth.json new file mode 100644 index 00000000..6c7481bf --- /dev/null +++ b/captures/angry-miao-infinity/openmouse-hardware-test-bluetooth.json @@ -0,0 +1,146 @@ +{ + "device": { + "present": true, + "brand": "Angry Miao", + "name": "Angry Miao Infinity .100", + "vendorId": 12625, + "productId": 16428, + "productName": "Angry Miao Infinity .100", + "transport": "webhid", + "connectionType": "Wireless", + "pollingRateHz": 8000, + "supportedPollingRates": [ + 125, + 250, + 500, + 1000, + 2000, + 4000, + 8000 + ], + "dpi": 1600, + "dpiStages": [ + 400, + 800, + 1200, + 1600, + 3200, + 6400, + 10000, + 30000 + ], + "activeDpiStage": 3, + "batteryPercent": 78, + "batteryState": "Discharging", + "firmware": [ + "Mouse SoC 0x0318", + "PixArt PAW3950" + ], + "liftOffDistance": "Medium", + "driverFamily": "angry-miao", + "deviceMode": null, + "collectionsSummary": "interfaces 0x0001:0x0006, 0x000C:0x0001, 0x0001:0x0080, 0x0001:0x0002, 0xFF55:0x0202", + "signalStrength": null, + "receiverOnline": null, + "receiverRfId": null, + "pairingInProgress": false + }, + "results": [ + { + "key": "connection", + "label": "Device connected", + "status": "pass", + "detail": "Connected through WebHID" + }, + { + "key": "interface", + "label": "Control interface", + "status": "pass", + "detail": "interfaces 0x0001:0x0006, 0x000C:0x0001, 0x0001:0x0080, 0x0001:0x0002, 0xFF55:0x0202" + }, + { + "key": "identity", + "label": "Device identity", + "status": "pass", + "detail": "Angry Miao Angry Miao Infinity .100" + }, + { + "key": "driver", + "label": "Driver identification", + "status": "pass", + "detail": "Angry Miao angry-miao" + }, + { + "key": "dpi", + "label": "DPI read-back", + "status": "pass", + "detail": "1,600 DPI" + }, + { + "key": "pollingRead", + "label": "Polling rate read-back", + "status": "pass", + "detail": "8000 Hz" + }, + { + "key": "battery", + "label": "Battery read-back", + "status": "pass", + "detail": "78%" + }, + { + "key": "firmware", + "label": "Firmware read-back", + "status": "pass", + "detail": "Mouse SoC 0x0318, PixArt PAW3950" + }, + { + "key": "liftOff", + "label": "Lift-off read-back", + "status": "pass", + "detail": "Medium" + }, + { + "key": "dpiStages", + "label": "DPI stages read-back", + "status": "pass", + "detail": "400, 800, 1,200, 1,600, 3,200, 6,400, 10,000, 30,000 DPI" + }, + { + "key": "link", + "label": "Wireless link (receiver)", + "status": "pass", + "detail": "driver read the wireless connection over the RF link" + }, + { + "key": "flashRead", + "label": "Flash / EEPROM read-back", + "status": "pass", + "detail": "decoded fields are in range (dpi, polling, lift-off, battery, dpi stages)" + }, + { + "key": "sampling", + "label": "Polling rate sampling", + "status": "skip", + "detail": "Not enough movement captured (needed ≥ 40 samples) — inconclusive." + }, + { + "key": "flashWrite", + "label": "Flash write round-trip", + "status": "pass", + "detail": "wrote 800 DPI → read back → restored 1,600 DPI · wrote 4,000 Hz → read back → restored 8,000 Hz · wrote Low → read back → restored Medium" + } + ], + "verdict": "pass", + "durationMs": 19573.600000023842, + "runAt": "2026-12-03T06:39:20.516Z", + "build": "BETA · v2.0.1471", + "supportedPage": { + "listed": false, + "status": null, + "label": null, + "matchedBy": null, + "pageModel": null, + "detail": "not listed on the supported-devices page" + } +} \ No newline at end of file diff --git a/captures/angry-miao-infinity/openmouse-hardware-test-wired.json b/captures/angry-miao-infinity/openmouse-hardware-test-wired.json new file mode 100644 index 00000000..ce4d7153 --- /dev/null +++ b/captures/angry-miao-infinity/openmouse-hardware-test-wired.json @@ -0,0 +1,147 @@ +{ + "device": { + "present": true, + "brand": "Angry Miao", + "name": "Angry Miao Infinity .100", + "vendorId": 12625, + "productId": 16426, + "productName": "Angry Miao Infinity .100", + "transport": "webhid", + "connectionType": "Wired", + "pollingRateHz": 8000, + "supportedPollingRates": [ + 125, + 250, + 500, + 1000, + 2000, + 4000, + 8000 + ], + "dpi": 1600, + "dpiStages": [ + 400, + 800, + 1200, + 1600, + 3200, + 6400, + 10000, + 30000 + ], + "activeDpiStage": 3, + "batteryPercent": 77, + "batteryState": "Charging", + "firmware": [ + "Mouse SoC 0x0318", + "Mouse USB 0x0101", + "PixArt PAW3950" + ], + "liftOffDistance": "Medium", + "driverFamily": "angry-miao", + "deviceMode": null, + "collectionsSummary": "interfaces 0xFFFF:0x0002", + "signalStrength": null, + "receiverOnline": null, + "receiverRfId": null, + "pairingInProgress": false + }, + "results": [ + { + "key": "connection", + "label": "Device connected", + "status": "pass", + "detail": "Connected through WebHID" + }, + { + "key": "interface", + "label": "Control interface", + "status": "pass", + "detail": "interfaces 0xFFFF:0x0002" + }, + { + "key": "identity", + "label": "Device identity", + "status": "pass", + "detail": "Angry Miao Angry Miao Infinity .100" + }, + { + "key": "driver", + "label": "Driver identification", + "status": "pass", + "detail": "Angry Miao angry-miao" + }, + { + "key": "dpi", + "label": "DPI read-back", + "status": "pass", + "detail": "1,600 DPI" + }, + { + "key": "pollingRead", + "label": "Polling rate read-back", + "status": "pass", + "detail": "8000 Hz" + }, + { + "key": "battery", + "label": "Battery read-back", + "status": "pass", + "detail": "77%" + }, + { + "key": "firmware", + "label": "Firmware read-back", + "status": "pass", + "detail": "Mouse SoC 0x0318, Mouse USB 0x0101, PixArt PAW3950" + }, + { + "key": "liftOff", + "label": "Lift-off read-back", + "status": "pass", + "detail": "Medium" + }, + { + "key": "dpiStages", + "label": "DPI stages read-back", + "status": "pass", + "detail": "400, 800, 1,200, 1,600, 3,200, 6,400, 10,000, 30,000 DPI" + }, + { + "key": "link", + "label": "Wireless link (receiver)", + "status": "skip", + "detail": null + }, + { + "key": "flashRead", + "label": "Flash / EEPROM read-back", + "status": "pass", + "detail": "decoded fields are in range (dpi, polling, lift-off, battery, dpi stages)" + }, + { + "key": "sampling", + "label": "Polling rate sampling", + "status": "skip", + "detail": "avg 195 Hz vs reported 8000 Hz — dropout or rate mismatch detected, so the sample is not counted as a failure." + }, + { + "key": "flashWrite", + "label": "Flash write round-trip", + "status": "pass", + "detail": "wrote 800 DPI → read back → restored 1,600 DPI · wrote 4,000 Hz → read back → restored 8,000 Hz · wrote Low → read back → restored Medium" + } + ], + "verdict": "pass", + "durationMs": 18271.5, + "runAt": "2026-12-03T08:22:15.881Z", + "build": "BETA · v2.0.1472", + "supportedPage": { + "listed": false, + "status": null, + "label": null, + "matchedBy": null, + "pageModel": null, + "detail": "not listed on the supported-devices page" + } +} \ No newline at end of file diff --git a/captures/angry-miao-infinity/openmouse-hardware-test-wireless.json b/captures/angry-miao-infinity/openmouse-hardware-test-wireless.json new file mode 100644 index 00000000..7e0c5aa4 --- /dev/null +++ b/captures/angry-miao-infinity/openmouse-hardware-test-wireless.json @@ -0,0 +1,149 @@ +{ + "device": { + "present": true, + "brand": "Angry Miao", + "name": "Angry Miao Infinity .100", + "vendorId": 12625, + "productId": 20487, + "productName": "Angry Miao Infinity .100", + "transport": "webhid", + "connectionType": "Wireless", + "pollingRateHz": 8000, + "supportedPollingRates": [ + 125, + 250, + 500, + 1000, + 2000, + 4000, + 8000 + ], + "dpi": 1600, + "dpiStages": [ + 400, + 800, + 1200, + 1600, + 3200, + 6400, + 10000, + 30000 + ], + "activeDpiStage": 3, + "batteryPercent": 77, + "batteryState": "Discharging", + "firmware": [ + "Mouse SoC 0x0318", + "Receiver USB 0x0008", + "Receiver RF 0xf0", + "Receiver LED 0x0109", + "PixArt PAW3950" + ], + "liftOffDistance": "Medium", + "driverFamily": "angry-miao", + "deviceMode": null, + "collectionsSummary": "interfaces 0xFFFF:0x0002", + "signalStrength": null, + "receiverOnline": null, + "receiverRfId": null, + "pairingInProgress": false + }, + "results": [ + { + "key": "connection", + "label": "Device connected", + "status": "pass", + "detail": "Connected through WebHID" + }, + { + "key": "interface", + "label": "Control interface", + "status": "pass", + "detail": "interfaces 0xFFFF:0x0002" + }, + { + "key": "identity", + "label": "Device identity", + "status": "pass", + "detail": "Angry Miao Angry Miao Infinity .100" + }, + { + "key": "driver", + "label": "Driver identification", + "status": "pass", + "detail": "Angry Miao angry-miao" + }, + { + "key": "dpi", + "label": "DPI read-back", + "status": "pass", + "detail": "1,600 DPI" + }, + { + "key": "pollingRead", + "label": "Polling rate read-back", + "status": "pass", + "detail": "8000 Hz" + }, + { + "key": "battery", + "label": "Battery read-back", + "status": "pass", + "detail": "77%" + }, + { + "key": "firmware", + "label": "Firmware read-back", + "status": "pass", + "detail": "Mouse SoC 0x0318, Receiver USB 0x0008, Receiver RF 0xf0, Receiver LED 0x0109, PixArt PAW3950" + }, + { + "key": "liftOff", + "label": "Lift-off read-back", + "status": "pass", + "detail": "Medium" + }, + { + "key": "dpiStages", + "label": "DPI stages read-back", + "status": "pass", + "detail": "400, 800, 1,200, 1,600, 3,200, 6,400, 10,000, 30,000 DPI" + }, + { + "key": "link", + "label": "Wireless link (receiver)", + "status": "pass", + "detail": "driver read the wireless connection over the RF link" + }, + { + "key": "flashRead", + "label": "Flash / EEPROM read-back", + "status": "pass", + "detail": "decoded fields are in range (dpi, polling, lift-off, battery, dpi stages)" + }, + { + "key": "sampling", + "label": "Polling rate sampling", + "status": "skip", + "detail": "avg 177 Hz vs reported 8000 Hz — dropout or rate mismatch detected, so the sample is not counted as a failure." + }, + { + "key": "flashWrite", + "label": "Flash write round-trip", + "status": "pass", + "detail": "wrote 800 DPI → read back → restored 1,600 DPI · wrote 4,000 Hz → read back → restored 8,000 Hz · wrote Low → read back → restored Medium" + } + ], + "verdict": "pass", + "durationMs": 39594.90000009537, + "runAt": "2026-12-03T08:24:25.489Z", + "build": "BETA · v2.0.1472", + "supportedPage": { + "listed": false, + "status": null, + "label": null, + "matchedBy": null, + "pageModel": null, + "detail": "not listed on the supported-devices page" + } +} \ No newline at end of file diff --git a/captures/angry-miao-infinity/receiver-spare-removed.json b/captures/angry-miao-infinity/receiver-spare-removed.json new file mode 100644 index 00000000..83d74dd0 --- /dev/null +++ b/captures/angry-miao-infinity/receiver-spare-removed.json @@ -0,0 +1,25 @@ +{ + "model": "Angry Miao Infinity .100 (AM30)", + "firmware": { + "mouseSoc": "0x0318 (vendor 1.1.1)", + "receiverUsb": "0x0008 (vendor 1.0.7)", + "receiverRf": "240 (vendor 1.0.8)", + "receiverLed": "0x0109 (vendor 1.0.5)" + }, + "date": "2026-12-03", + "os": "macOS", + "transport": "2.4 GHz receiver", + "vendorId": 12625, + "productId": 20487, + "productName": "AM INFINITY 8K MOUSE", + "source": "OpenMouse with the Angry Miao driver, recorded with a passive WebHID logger on sendFeatureReport and receiveFeatureReport. The spare battery was taken out of the receiver dock first. Reads only.", + "notes": { + "status": "0xF7 replies, mouse online at 76 %. Byte 10 (the spare battery) read 0 in every reply. Byte 9 also read 0, where dongle-reads.json (spare in the dock at 99 %) has 1. The vendor app decodes only byte 10.", + "stale": "Some 0xF7 replies repeat bytes 11-63 of the previous relayed reply, as in dongle-reads.json. Only the clean replies are kept." + }, + "status": { + "idle": "00004c01000102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "busy": "00004c01000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "replyReady": "01004c01000102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + } +} diff --git a/docs/angry-miao-infinity.md b/docs/angry-miao-infinity.md new file mode 100644 index 00000000..277fd00f --- /dev/null +++ b/docs/angry-miao-infinity.md @@ -0,0 +1,225 @@ +# Angry Miao Infinity .100 + +The Angry Miao Infinity .100 (model AM30) is a wireless mouse. It is sold as +"AM Infinity", and the vendor app calls it "AM Infinity .100". Yichip makes its +chip and owns vendor ID 0x3151, so the mouse speaks the Yichip protocol. + +- `AngryMiaoHidClient` (`src/drivers/angry-miao/hid.ts`) and its codec + (`src/angry-miao/`) handle everything for this mouse: sending reports, + passing commands through the receiver, and the settings layout. +- Other brands use the same product IDs. The driver claims a device only when + the product ID and the product name both say Angry Miao. +- The driver reads the device ID with `8F` during each status read that reaches + the mouse. It writes to the mouse only when that ID is **2222** (`0x08AE`), so + a caller must finish such a status read before it changes a mouse setting. + For any other ID, mouse settings are read-only. +- A status read where only the receiver answers does not send `8F`. It clears + the device ID, so mouse settings stay read-only until the mouse answers again. +- The receiver light belongs to the receiver, not the mouse. Its writes go + straight to the receiver and do not need the device ID. +- Each setting change and each status read runs as one step. A change that + starts during a status read waits for it, so two changes never undo each + other. + +How to read this page: + +- A command is named by its first byte, in hex, such as `D3`. +- Byte numbers start at 0 in the 64-byte reply. +- A write gets no reply, so the driver reads back what the mouse can report. + - Every options change (`53`) reads `D3` again and fails if a changed byte + does not match. That covers the report rate, debounce, standby, lift-off, + angle snapping, ripple control, motion sync and the mouse light. + - A profile switch reads `85`, and a receiver light change reads `88` and + `87`. + - DPI table (`54`), button (`50`) and Blast Mode (`62`) writes are not read + back. To confirm them, read the status again. `E2` does not reflect Blast + Mode on SoC firmware 1.1.1. +- The vendor app is Angry Miao's own configurator. + +## Connections + +| Connection | VID:PID | Control collection | +| ---------------------------------- | --------- | -------------------------------------------- | +| USB cable | 3151:402A | FFFF:0002, unnumbered 64-byte feature report | +| 2.4 GHz receiver | 3151:5007 | FFFF:0002, unnumbered 64-byte feature report | +| Bluetooth ("AM INFINITY BT MOUSE") | 3151:402C | FF55:0202, output and input report 6 | + +### Bluetooth + +- The driver sends the cable command with a `55` byte in front, as output + report 6. The reply comes back as input report 6. +- `77` asks for the battery. It works on Bluetooth only. Byte 1 is the percent, + and `88` means the mouse is asleep. `D6` also returns the battery. +- The vendor web app does not offer Bluetooth for this mouse. + +### 2.4 GHz receiver + +The receiver does not pass USB traffic straight to the mouse. The driver asks +the receiver to send each command to the mouse over 2.4 GHz, then to hand back +the reply. The vendor app does the same. + + + + The driver selects the mouse with F6 05, waits for F7, sets the length with FE 40, sends the command, waits for F7 again and reads the reply with FC, up to three times, then sends F6 00 if every try failed. + + +For each mouse command, the driver: + +1. Sends `F6 05` to select the mouse. +2. Polls `F7` until byte 5 is 1 (the receiver can take a command). +3. Sends `FE 40` to set the length. +4. Sends the command. +5. Polls `F7` until byte 0 is 1 (the reply is ready). +6. Sends `FC` and reads the reply. + +If a try fails, the driver tries again, up to three times in total, 100 ms +apart. After the last failure it sends `F6 00` to release the receiver. A write +is retried only if it failed before the driver sent it. A relayed reply is +byte for byte the same as the reply on the cable. + +A second app that polls the receiver at the same time mixes up the replies. +Cutting one app off in the middle of a relay left `F7` byte 5 at 0 until the +receiver was unplugged. + +The receiver answers some commands itself, with no relay: + +| Command | What it returns or does | +| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `F7` byte 2 | Battery in the mouse. Same as `D6` byte 3 | +| `F7` byte 4 | Not 0 when the mouse is asleep, off or on another link | +| `F7` byte 10 | Charge of the spare battery: 1 to 100. The vendor app reads 100 as full, lower as charging and 0 as no battery. It read 0 with the spare taken out | +| `F0`, `AE` | USB and LED firmware versions, as a 16-bit little-endian number at bytes 1 and 2. Wait 500 ms after `F0` | +| `FB` | RF firmware version, at byte 3. The reply does not repeat the command byte | +| `87` / `07` | Receiver light on or off: read / write | +| `88` / `08` | Receiver light effect, speed, brightness and colour: read / write | + +- The receiver has no battery of its own. It charges a spare mouse battery that + you can swap in and out. +- On the receiver, the mouse's own `AD` firmware read returns 0. OpenMouse shows + the receiver versions instead: `Receiver USB 0x0008`, `Receiver RF 0xf0` and + `Receiver LED 0x0109`. +- When `F7` byte 4 is not 0, OpenMouse shows only the receiver (firmware, light + and spare battery) and sends nothing to the mouse. The driver names it + "Angry Miao Receiver" until the mouse answers again. + +## Settings + +The mouse supports 50 to 30000 DPI in up to 8 stages, and polling rates from +125 to 8000 Hz. + +### Main settings (`D3`) + +| Byte | Setting | +| ------------------ | ------------------------------------------------------------------------------------- | +| 8 | Active profile. It follows a profile switch | +| 9 | Polling rate (codes below) | +| 10, 61, 62 | Debounce time for USB, 2.4 GHz and Bluetooth | +| 12 | Ripple control: 1 is on | +| 17, 18 | Not changed. A write sends back the values it read | +| 40, 41 | Bluetooth standby time | +| 44, 45 | 2.4 GHz standby time | +| 52 | Lift-off distance: 0 Low, 1 Medium, 2 High | +| 53 | Angle snapping | +| 54 to 56, 57 to 59 | Mouse light colour (RGB). The vendor app has one colour control and writes it to both | +| 60 | Mouse light: 1 is on | +| 63 | Motion sync: 1 is on | + +Polling rate codes: + +| Rate | 125 Hz | 250 Hz | 500 Hz | 1000 Hz | 2000 Hz | 4000 Hz | 8000 Hz | +| ---- | ------ | ------ | ------ | ------- | ------- | ------- | ------- | +| Code | 8 | 4 | 2 | 1 | 132 | 130 | 129 | + +Debounce is one slider with seven stops: 30, 25, 20, 15, 10, 5 and 0 ms. The +byte value for each stop depends on the polling rate: + +| Rate | Byte value for 30, 25, 20, 15, 10, 5 and 0 ms | +| -------------- | --------------------------------------------- | +| 125 to 1000 Hz | 10, 8, 6, 4, 3, 2, 0 | +| 2000 Hz | 20, 16, 12, 8, 4, 2, 0 | +| 4000 Hz | 39, 31, 23, 15, 7, 3, 0 | +| 8000 Hz | 79, 63, 47, 31, 15, 7, 0 | + +- A write sets bytes 10 and 61 from the row for the current rate. +- Byte 62 (Bluetooth) always uses the 125 to 1000 Hz row. +- When the rate changes, the stop stays the same. +- A value that is not in the row shows as the nearest stop. + +Standby time is a 16-bit little-endian number of seconds. `0xFFFF` means never. +OpenMouse offers 15 s, 30 s, 1 min, 10 min, 30 min, 1 h and never. A write +changes only the timer for the link in use, as the vendor app does. + +### DPI (`D4` read, `54` write) + +- The range is 50 to 30000 DPI in steps of 50. There are 8 stages, each with a + colour, and one active stage. +- `D4` byte 3 is the number of stages in use (1 to 8). If the active stage is + past the new count, it moves to the last stage in use. +- A write always sends all 8 stages, so stages past the count keep their + values. A stage that reads 0 gets 800 DPI and red, as in the vendor app. + +### Buttons (`D0` read, `50 ` write) + +A write is the `50` command, the profile, the button slot, then a 4-byte action. + +- Slots: Left, Right, Middle, Back (slot 4), Forward (slot 3), Scroll Up + (slot 14) and Scroll Down (slot 15). +- Left always stays Left Click, as in the vendor app. +- Slot 5 reads DPI Loop, but the mouse has no DPI button, so OpenMouse does not + offer it. +- Slots 12 and 13 hold a second pair of wheel actions (`F9`). The vendor app + does not show them. +- Restore defaults rewrites each button that differs from its factory action. + +| Action | Bytes | +| -------------------- | ---------------------------------------------------------------------------------------- | +| Scroll up / down | `01 00 F5 01` / `01 00 F5 FF` | +| DPI loop / up / down | `14 00 00 00` / `14 00 01 00` / `14 00 02 00` | +| Media key | `03 00 00`. Usages: `E9` volume up, `EA` volume down, `E2` mute, `CD` play/pause | +| Disabled | `00 00 00 00` | + +Mouse button actions (left, right, middle, back and forward click) are offered +too. + +### Other commands + +- **Battery (`D6`).** Byte 1 is 0 on battery, 1 when charging and 2 when full. + Byte 2 says whether the percent is valid. Byte 3 is the percent. +- **Blast Mode.** This runs the sensor at its top frame rate. OpenMouse calls + it Turbo mode. Write `62 <0|1>` and read `E2` byte 1. On SoC firmware 1.1.1, + `E2` read 0 even right after `62 01`. The driver therefore keeps the last + value it wrote, as the vendor app does. +- **Profiles.** The mouse has 2. + - `85` byte 1 is the active profile. The driver reads it before `D0`. + - When `85` does not answer, the driver does not know which profile is + active. It hides the button mappings and refuses to change them until the + next status read gets an answer. + - To switch, send `05 02`, confirm with `85`, then send `62 00`, as + the vendor app does. + - The `D0` request names the profile. `D3`, `D4` and `54` have no profile + byte. + - The vendor app says each profile has its own DPI table, polling rate and + buttons. The polling rate is confirmed on hardware. The light and standby + read the same on both profiles. +- **Receiver light write.** The format is + `08 effect speed brightness 07 R G B checksum`, with the checksum in byte 8. + - Effects 1 to 8: always on, breathing, neon, light wave, marquee, ring, + buffer, chase. + - Speed 1 to 5 is stored as 4 down to 0. Brightness 0 to 100 % is stored as + 0 to 4. + - Colour option 7 is a custom RGB value. Options 0 to 6 are presets. + +## Status against the vendor app + +Not done yet: + +| Feature | What we know | Next step | +| ---------------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | +| DPI quick switch | `63 <0\|1>`, then the vendor app rewrites `54` unchanged. `E3` byte 1 is the read (from a capture) | Add a switch. Check whether `E3` follows the write (`E2` does not) | +| Sensor rotation (-90 to 90°) | `65 `. `E5` byte 1 is the read (from a capture) | Add an angle control. Check the `E5` read-back | + +## Automated tests + +`npm run check` runs them. They decode the captured replies, send each captured +change through the driver and compare all 64 bytes with the vendor app's write. +They also check that no other driver claims the Angry Miao IDs. diff --git a/docs/diagrams/angry-miao-relay-dark.svg b/docs/diagrams/angry-miao-relay-dark.svg new file mode 100644 index 00000000..e382f505 --- /dev/null +++ b/docs/diagrams/angry-miao-relay-dark.svg @@ -0,0 +1,79 @@ + +One mouse command through the 2.4 GHz receiver +The driver selects the mouse with F6 05, waits for F7, sets the length with FE 40, sends the command, waits for F7 again and reads the reply with FC, up to three times, then sends F6 00 if every try failed. + + + + + +One mouse command through the 2.4 GHz receiver +Every request is a 64-byte feature report on the receiver. The receiver forwards the command to the mouse. + + + + + + + +LOOP +[≤ 3 tries] + + + + + + + + + + + + + + +F6 05 MOUSE +F7 SEND-READY +FE 40 LENGTH +COMMAND +2.4 GHZ +REPLY +F7 REPLY-READY +FC READ +64-BYTE REPLY +F6 00 ON FAIL + + + + +HOST +OpenMouse driver +AngryMiaoHidClient + + + +2.4 GHZ +Receiver +3151:5007 + + + +MOUSE +Infinity .100 +AM30 + + + +LEGEND + +OpenMouse code + +Hardware + +Request + +Reply + +Sent without waiting + +Reply the driver returns + diff --git a/docs/diagrams/angry-miao-relay.svg b/docs/diagrams/angry-miao-relay.svg new file mode 100644 index 00000000..a18adcfc --- /dev/null +++ b/docs/diagrams/angry-miao-relay.svg @@ -0,0 +1,79 @@ + +One mouse command through the 2.4 GHz receiver +The driver selects the mouse with F6 05, waits for F7, sets the length with FE 40, sends the command, waits for F7 again and reads the reply with FC, up to three times, then sends F6 00 if every try failed. + + + + + +One mouse command through the 2.4 GHz receiver +Every request is a 64-byte feature report on the receiver. The receiver forwards the command to the mouse. + + + + + + + +LOOP +[≤ 3 tries] + + + + + + + + + + + + + + +F6 05 MOUSE +F7 SEND-READY +FE 40 LENGTH +COMMAND +2.4 GHZ +REPLY +F7 REPLY-READY +FC READ +64-BYTE REPLY +F6 00 ON FAIL + + + + +HOST +OpenMouse driver +AngryMiaoHidClient + + + +2.4 GHZ +Receiver +3151:5007 + + + +MOUSE +Infinity .100 +AM30 + + + +LEGEND + +OpenMouse code + +Hardware + +Request + +Reply + +Sent without waiting + +Reply the driver returns + diff --git a/package.json b/package.json index 43480e6d..a637f32a 100644 --- a/package.json +++ b/package.json @@ -71,6 +71,10 @@ "types": "./dist/gearhub/index.d.ts", "import": "./dist/gearhub/index.js" }, + "./angry-miao": { + "types": "./dist/angry-miao/index.d.ts", + "import": "./dist/angry-miao/index.js" + }, "./keychron": { "types": "./dist/keychron/index.d.ts", "import": "./dist/keychron/index.js" diff --git a/src/angry-miao/index.test.ts b/src/angry-miao/index.test.ts new file mode 100644 index 00000000..051b4283 --- /dev/null +++ b/src/angry-miao/index.test.ts @@ -0,0 +1,82 @@ +import assert from "node:assert/strict"; +import { it } from "node:test"; +import { + AM30_DEBOUNCE_GEARS_MS, + AM30_DEBOUNCE_RAW, + am30DebounceGear, + am30DebounceRaw, + am30DecodeBattery, + am30DecodeReceiverLight, + am30EncodeCommand, + am30EncodeReceiverLight, + AM30_RATE_DECODE, + ANGRY_MIAO_INFINITY_PROFILE, + ANGRY_MIAO_PRODUCTS, + ANGRY_MIAO_PROFILES, +} from "./index.ts"; +import { GEARHUB_DEVICE_PROFILES, GEARHUB_PRODUCTS } from "../gearhub/index.ts"; + +it("stamps the checksum and decodes the rate codes the mouse uses", () => { + // Captured: D6 00 00 00 00 00 00 29 (battery read). + assert.deepEqual([...am30EncodeCommand([0xd6])], [0xd6, 0, 0, 0, 0, 0, 0, 0x29, 0]); + // Captured option blocks: 0x01 at 1000 Hz, 0x81 at 8000 Hz. + assert.equal(AM30_RATE_DECODE[0x01], 1000); + assert.equal(AM30_RATE_DECODE[0x81], 8000); +}); + +it("names the Infinity from its device id and claims its cable and receiver product ids", () => { + const profile = ANGRY_MIAO_PROFILES.get(2222); + assert.equal(profile, ANGRY_MIAO_INFINITY_PROFILE); + assert.equal(profile?.sensor, "PixArt PAW3950"); + assert.equal(profile?.maxDpi, 30000); + assert.equal(profile?.buttons?.find((button) => button.name === "Back")?.slot, 4); + assert.equal(profile?.buttons?.find((button) => button.name === "Forward")?.slot, 3); + assert.equal(profile?.buttons?.some((button) => button.name === "DPI"), false); + assert.equal(ANGRY_MIAO_PRODUCTS.get(0x402a)?.transport, "direct"); + assert.deepEqual(ANGRY_MIAO_PRODUCTS.get(0x5007), { transport: "dongle", usagePage: 0xffff, usage: 0x02 }); + assert.deepEqual(ANGRY_MIAO_PRODUCTS.get(0x402c), { transport: "bluetooth", usagePage: 0xff55, usage: 0x0202 }); +}); + +it("decodes the battery read with its charge state", () => { + const reply = (bytes: number[]) => Uint8Array.from([...bytes, ...new Array(60).fill(0)]); + // Captured: receiver 00 01 64, cable 01 01 63 and 02 01 64. + assert.deepEqual(am30DecodeBattery(reply([0xd6, 0, 1, 100])), { percent: 100, state: "Discharging" }); + assert.deepEqual(am30DecodeBattery(reply([0xd6, 1, 1, 99])), { percent: 99, state: "Charging" }); + assert.deepEqual(am30DecodeBattery(reply([0xd6, 2, 1, 100])), { percent: 100, state: "Full" }); + assert.deepEqual(am30DecodeBattery(reply([0xd6, 7, 1, 200])), { percent: null, state: "Unknown" }); + assert.equal(am30DecodeBattery(reply([0xd6, 1, 0, 50])).percent, null, "byte 2 = 0 marks the percent invalid"); +}); + +it("decodes and encodes the receiver light the way the vendor app does", () => { + const reply = (bytes: number[]) => Uint8Array.from([...bytes, ...new Array(64 - bytes.length).fill(0)]); + // Captured: 88 03 04 04 08 FF FF FF and 87 01 = neon, slowest, full brightness, custom white, on. + assert.deepEqual( + am30DecodeReceiverLight(reply([0x88, 3, 4, 4, 8, 0xff, 0xff, 0xff]), reply([0x87, 1])), + { enabled: true, effect: 3, speed: 1, brightness: 100, color: "#ffffff" }, + ); + assert.equal(am30DecodeReceiverLight(reply([0x88, 1, 0, 2, 3]), reply([0x87, 0])).color, "#00ff00", "option 3 is the green preset"); + // Neon, speed 1, 50 %, #d0021b: the checksum is byte 8. + assert.deepEqual( + [...am30EncodeReceiverLight({ effect: 3, speed: 1, brightness: 50, color: "#d0021b" }).subarray(0, 10)], + [0x08, 3, 4, 2, 7, 0xd0, 0x02, 0x1b, 0xfa, 0], + ); + assert.equal(am30EncodeReceiverLight({ effect: 1, speed: 5, brightness: 100, color: "#ffffff" })[2], 0, "always on writes speed 0"); + assert.throws(() => am30EncodeReceiverLight({ effect: 9, speed: 1, brightness: 50, color: "#ffffff" })); + assert.throws(() => am30EncodeReceiverLight({ effect: 2, speed: 1, brightness: 40, color: "#ffffff" })); +}); + +it("keeps the AM30 out of the shared catalog", () => { + assert.equal(GEARHUB_DEVICE_PROFILES.has(2222), false); + assert.equal(GEARHUB_PRODUCTS.has(0x402a), false); +}); + +it("maps debounce gears per report rate the way the vendor app does", () => { + for (const list of Object.values(AM30_DEBOUNCE_RAW)) { + assert.equal(list.length, AM30_DEBOUNCE_GEARS_MS.length); + } + // Captured: 10 ms at 1000 Hz is raw 3; the same gear at 8000 Hz is 15, and Bluetooth stays 3. + assert.equal(am30DebounceGear(1000, 3), 4); + assert.deepEqual(am30DebounceRaw(8000, 4), { usb: 15, rf: 15, bt: 3 }); + assert.equal(am30DebounceGear(8000, 16), 4, "an off-table byte snaps to the nearest gear"); + assert.equal(am30DebounceGear(undefined, 3), 4, "an unknown rate uses the 1000 Hz list"); +}); diff --git a/src/angry-miao/index.ts b/src/angry-miao/index.ts new file mode 100644 index 00000000..a153a3c0 --- /dev/null +++ b/src/angry-miao/index.ts @@ -0,0 +1,391 @@ +/** + * Angry Miao Infinity .100 mouse (model AM30) on the Yichip (VID 0x3151) block + * protocol. This codec owns everything the Angry Miao driver + * (`src/drivers/angry-miao/`) sends; it does not share constants with the + * other Yichip brands, so their changes cannot move this mouse. + * + * Sources: replies read over the USB cable and the vendor configurator + * (ammaster.angrymiao.com, model page am30). See + * docs/angry-miao-infinity.md. + */ + +/** Yichip's vendor id. Other brands ship on it, so it never identifies this mouse alone. */ +export const ANGRY_MIAO_VENDOR_ID = 0x3151; +/** Product names: cable "Angry Miao Infinity", receiver "AM INFINITY 8K MOUSE", Bluetooth "AM INFINITY BT MOUSE". */ +export const ANGRY_MIAO_PRODUCT_NAME = /angry\s*miao|\bAM\s+INFINITY\b/i; +/** One unnumbered 64-byte feature report on usage page 0xFFFF, usage 0x02. */ +export const AM30_REPORT_ID = 0; +export const AM30_REPORT_SIZE = 64; +export const AM30_USAGE_PAGE = 0xffff; +export const AM30_USAGE = 0x02; + +/** Bluetooth: the same commands go out and come back as report 6 on 0xFF55:0x0202, after a `55` byte. */ +export const AM30_BT_USAGE_PAGE = 0xff55; +export const AM30_BT_USAGE = 0x0202; +export const AM30_BT_REPORT_ID = 6; +export const AM30_BT_REPORT_SIZE = 65; +export const AM30_BT_ENVELOPE = 0x55; +/** `77` asks for the battery (byte 1, percent); a reply of `88` means the mouse is asleep. */ +export const AM30_BT_BATTERY = 0x77; +export const AM30_BT_SLEEPING = 0x88; + +export function am30BluetoothPacket(encoded: Uint8Array): Uint8Array { + const packet = new Uint8Array(AM30_BT_REPORT_SIZE); + packet[0] = AM30_BT_ENVELOPE; + packet.set(encoded.subarray(0, AM30_BT_REPORT_SIZE - 1), 1); + return packet; +} + +/** Mouse commands. Blocks are read whole and written back whole. */ +export const AM30_CMD = { + GET_FIRMWARE: 0x80, + GET_DEVICE_ID: 0x8f, + GET_OPTIONS: 0xd3, + SET_OPTIONS: 0x53, + GET_DPI: 0xd4, + SET_DPI: 0x54, + GET_KEYMATRIX: 0xd0, + SET_KEYMATRIX: 0x50, +} as const; + +/** Receiver relay commands. Raw: no checksum. */ +export const AM30_RELAY = { + SELECT_TARGET: 0xf6, + GET_STATUS: 0xf7, + NOTICE_READ: 0xfc, + SET_LENGTH: 0xfe, +} as const; +export const AM30_TARGET_MOUSE = 0x05; +/** `F6 00` releases the receiver after a relay fails, as the vendor app does. */ +export const AM30_TARGET_NONE = 0x00; +/** The vendor app tries a relayed command this many times, 100 ms apart. */ +export const AM30_RELAY_ATTEMPTS = 3; +/** The vendor app sends `FE 40` before every relayed command. */ +export const AM30_RELAY_LENGTH = 0x40; + +/** Pad to 9 bytes; byte 7 is 255 minus the sum of bytes 0-6. */ +export function am30EncodeCommand(bytes: readonly number[]): Uint8Array { + const out = new Uint8Array(Math.max(9, bytes.length)); + out.set(bytes); + let sum = 0; + for (let i = 0; i < 7; i++) sum = (sum + out[i]) & 0xff; + out[7] = (255 - sum) & 0xff; + return out; +} + +/** Options block (`D3` / `53`) byte offsets. */ +export const AM30_OPT0_REPORT_RATE = 9; +export const AM30_OPT0_DEBOUNCE = 10; +export const AM30_OPT0_FLAGS = 12; +export const AM30_OPT0_SLEEP_BT = 40; +export const AM30_OPT0_SLEEP_24G = 44; +export const AM30_OPT0_LIFT_OFF = 52; +export const AM30_OPT0_ANGLE_SNAP = 53; + +/** Report rate byte: a code, not an index. */ +export const AM30_RATE_ENCODE: Readonly> = { + 125: 8, 250: 4, 500: 2, 1000: 1, 2000: 132, 4000: 130, 8000: 129, +}; +export const AM30_RATE_DECODE: Readonly> = Object.fromEntries( + Object.entries(AM30_RATE_ENCODE).map(([hz, code]) => [code, Number(hz)]), +); +export const AM30_RATES: readonly number[] = Object.keys(AM30_RATE_ENCODE).map(Number).sort((a, b) => a - b); + +/** Lift-off byte 52: 0, 1, 2. */ +export const AM30_LIFT_OFF_LEVELS = ["Low", "Medium", "High"] as const; +export type Am30LiftOff = (typeof AM30_LIFT_OFF_LEVELS)[number]; + +/** DPI block (`D4` / `54`): byte 2 active stage, byte 3 count, then X, Y and RGB per stage. */ +export const AM30_MAX_DPI_STAGES = 8; +export const AM30_DPI_X_OFFSET = 8; +export const AM30_DPI_Y_OFFSET = 24; +export const AM30_DPI_RGB_OFFSET = 40; + +/** OPTIONPARAM0 debounce bytes for the 2.4 GHz and Bluetooth links. */ +export const AM30_OPT0_DEBOUNCE_24G = 61; +export const AM30_OPT0_DEBOUNCE_BT = 62; +/** Ripple control on is byte 12 = 1 (captured from the vendor app). */ +export const AM30_OPT0_FLAG_RIPPLE = 1 << 0; +/** Motion sync, 1 = on. */ +export const AM30_OPT0_MOTION_SYNC = 63; +/** Mouse light: on/off switch and two RGB slots, which the vendor panel sets to one colour. */ +export const AM30_OPT0_LIGHT_COLOR = 54; +export const AM30_OPT0_LIGHT_COLOR_2 = 57; +export const AM30_OPT0_LIGHT = 60; +/** LE16 standby value meaning "never". */ +export const AM30_SLEEP_NEVER = 0xffff; + +/** Standby stops in seconds, 0 = never (the vendor presets). */ +export const AM30_SLEEP_OPTIONS: readonly number[] = [0, 15, 30, 60, 600, 1800, 3600]; + +/** The vendor app's one debounce slider, by gear index (30..0 ms). */ +export const AM30_DEBOUNCE_GEARS_MS: readonly number[] = [30, 25, 20, 15, 10, 5, 0]; + +const LOW_RATE_DEBOUNCE = [10, 8, 6, 4, 3, 2, 0] as const; + +/** USB and 2.4 GHz raw debounce by gear, per report rate. Bluetooth always uses the 1000 Hz list. */ +export const AM30_DEBOUNCE_RAW: Readonly> = { + 125: LOW_RATE_DEBOUNCE, + 250: LOW_RATE_DEBOUNCE, + 500: LOW_RATE_DEBOUNCE, + 1000: LOW_RATE_DEBOUNCE, + 2000: [20, 16, 12, 8, 4, 2, 0], + 4000: [39, 31, 23, 15, 7, 3, 0], + 8000: [79, 63, 47, 31, 15, 7, 0], +}; + +function debounceRawList(rateHz: number | undefined): readonly number[] { + return (rateHz !== undefined && AM30_DEBOUNCE_RAW[rateHz]) || LOW_RATE_DEBOUNCE; +} + +/** Gear index for a raw USB debounce byte: exact match, else the nearest. */ +export function am30DebounceGear(rateHz: number | undefined, raw: number): number { + const list = debounceRawList(rateHz); + const exact = list.indexOf(raw); + if (exact >= 0) return exact; + const nearest = Math.min(...list.map((value) => Math.abs(value - raw))); + return list.findIndex((value) => Math.abs(value - raw) === nearest); +} + +/** Raw bytes for one gear at a report rate: USB, 2.4 GHz and Bluetooth. */ +export function am30DebounceRaw( + rateHz: number | undefined, + gear: number, +): { usb: number; rf: number; bt: number } { + const list = debounceRawList(rateHz); + return { usb: list[gear], rf: list[gear], bt: LOW_RATE_DEBOUNCE[gear] }; +} + +/** Battery read: byte 1 = charge state, byte 2 = percent valid, byte 3 = percent. */ +export const AM30_GET_BATTERY = 0xd6; +/** Blast Mode (sensor at its top frame rate): read byte 1, write `62 <0|1>`. */ +export const AM30_GET_BLAST_MODE = 0xe2; +export const AM30_SET_BLAST_MODE = 0x62; + +/** Onboard profiles: read `85` byte 1 (active, 0-based), switch with `05 `. */ +export const AM30_GET_PROFILE = 0x85; +export const AM30_SET_PROFILE = 0x05; +export const AM30_PROFILE_COUNT = 2; + +/** USB firmware read (`AD`): bytes 1-2, LE16. The SoC version is the shared `80` read. */ +export const AM30_GET_USB_VERSION = 0xad; + +const hexCode = (code: number) => `0x${code.toString(16).padStart(4, "0")}`; + +/** + * Raw firmware codes. The vendor app's names for them (SoC 0x0318 = 1.1.1, + * package 1.6) come from a table on its server, so they are not repeated here. + */ +export function am30FirmwareLabels(usbCode: number | null, socCode: number | null): string[] { + return [ + ...(socCode === null ? [] : [`Mouse SoC ${hexCode(socCode)}`]), + ...(usbCode === null ? [] : [`Mouse USB ${hexCode(usbCode)}`]), + ]; +} + +/** Receiver firmware reads, sent to the receiver itself. The vendor app reads these instead of `AD` on 2.4 GHz. */ +export const AM30_RECEIVER_GET_USB_VERSION = 0xf0; +export const AM30_RECEIVER_GET_RF_VERSION = 0xfb; +export const AM30_RECEIVER_GET_LED_VERSION = 0xae; + +/** `F0` and `AE` hold LE16 codes at bytes 1-2; `FB` does not echo and holds the RF code in byte 3. */ +export function am30ReceiverFirmwareLabels( + usb: Uint8Array | null, + rf: Uint8Array | null, + led: Uint8Array | null, +): string[] { + const le16 = (reply: Uint8Array) => reply[1] | (reply[2] << 8); + return [ + ...(usb ? [`Receiver USB ${hexCode(le16(usb))}`] : []), + ...(rf ? [`Receiver RF 0x${rf[3].toString(16).padStart(2, "0")}`] : []), + ...(led ? [`Receiver LED ${hexCode(le16(led))}`] : []), + ]; +} + +export type Am30ChargeState = "Discharging" | "Charging" | "Full" | "Unknown"; + +/** Receiver status (`F7`) byte 4: 0 while the mouse is linked. */ +export const AM30_STATUS_MOUSE_OFFLINE = 4; + +/** Receiver status (`F7`) byte 10: the spare battery in the dock, 1-100; 0 = none. */ +export const AM30_STATUS_SPARE_BATTERY = 10; + +/** As the vendor app reads it: 100 is full, below that the dock is charging it. */ +export function am30DecodeSpareBattery(status: Uint8Array): { percent: number; state: "Charging" | "Full" } | null { + const percent = status[AM30_STATUS_SPARE_BATTERY]; + if (!percent || percent > 100) return null; + return { percent, state: percent === 100 ? "Full" : "Charging" }; +} + +/** Byte 1 is 0 on battery, 1 charging, 2 full, as the vendor app reads it. */ +export function am30DecodeBattery(reply: Uint8Array): { percent: number | null; state: Am30ChargeState } { + const percent = reply[2] !== 0 && reply[3] <= 100 ? reply[3] : null; + const state = (["Discharging", "Charging", "Full"] as const)[reply[1]] ?? "Unknown"; + return { percent, state }; +} + +/** + * Receiver light, sent to the receiver itself (never relayed). Read `88` / + * write `08`: effect, speed, brightness, colour option, R, G, B. Read `87` / + * write `07`: on/off. + */ +export const AM30_RECEIVER_GET_LIGHT = 0x88; +export const AM30_RECEIVER_SET_LIGHT = 0x08; +export const AM30_RECEIVER_GET_LIGHT_SWITCH = 0x87; +export const AM30_RECEIVER_SET_LIGHT_SWITCH = 0x07; +/** Effects 1..8: always on, breathing, neon, light wave, marquee, ring, buffer, chase. */ +export const AM30_RECEIVER_EFFECT_COUNT = 8; +export const AM30_RECEIVER_SPEEDS: readonly number[] = [1, 2, 3, 4, 5]; +export const AM30_RECEIVER_BRIGHTNESS: readonly number[] = [0, 25, 50, 75, 100]; +/** Colour option 7 = custom RGB; 0..6 pick these presets. */ +const RECEIVER_CUSTOM_COLOR = 7; +const RECEIVER_PRESETS = ["#ff0000", "#ff8800", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#8800ff"]; + +export interface Am30ReceiverLight { + enabled: boolean; + /** 1..8, see `AM30_RECEIVER_EFFECT_COUNT`. */ + effect: number; + /** The vendor slider, 1..5; the wire stores 4..0. */ + speed: number; + /** Percent in 25 % steps; the wire stores 0..4. */ + brightness: number; + color: string; +} + +const hex = (bytes: ArrayLike) => + `#${Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("")}`; + +export function am30DecodeReceiverLight(light: Uint8Array, power: Uint8Array): Am30ReceiverLight { + return { + enabled: power[1] === 1, + effect: Math.max(1, Math.min(AM30_RECEIVER_EFFECT_COUNT, light[1])), + speed: 5 - Math.min(4, light[2]), + brightness: Math.min(4, light[3]) * 25, + color: RECEIVER_PRESETS[light[4]] ?? hex(light.subarray(5, 8)), + }; +} + +/** The 64-byte `08` write. Its checksum is in byte 8, after the seven fields. */ +export function am30EncodeReceiverLight(light: Omit): Uint8Array { + const { effect, speed, brightness, color } = light; + if (!Number.isInteger(effect) || effect < 1 || effect > AM30_RECEIVER_EFFECT_COUNT) { + throw new Error(`Receiver light effect must be 1..${AM30_RECEIVER_EFFECT_COUNT}.`); + } + if (!AM30_RECEIVER_SPEEDS.includes(speed)) throw new Error("Receiver light speed must be 1..5."); + if (!AM30_RECEIVER_BRIGHTNESS.includes(brightness)) throw new Error("Receiver light brightness must be 0..100 in 25 % steps."); + const match = /^#?([0-9a-f]{6})$/i.exec(color); + if (!match) throw new Error(`Invalid receiver light colour: ${color}.`); + const rgb = parseInt(match[1], 16); + // The vendor app writes speed 0 for always on. + const fields = [ + AM30_RECEIVER_SET_LIGHT, effect, effect === 1 ? 0 : 5 - speed, brightness / 25, + RECEIVER_CUSTOM_COLOR, (rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff, + ]; + const out = new Uint8Array(64); + out.set(fields); + out[8] = (255 - (fields.reduce((sum, b) => sum + b, 0) & 0xff)) & 0xff; + return out; +} + +/** + * Key matrix actions from the vendor app (`D0` / `50`), label to 4-byte value. + * Scroll Up/Down are the factory values of slots 14 and 15. + */ +export const AM30_BUTTON_ACTIONS: ReadonlyArray = [ + ["Left Click", [0x01, 0, 0xf0, 0]], + ["Right Click", [0x01, 0, 0xf1, 0]], + ["Middle Click", [0x01, 0, 0xf2, 0]], + ["Back", [0x01, 0, 0xf3, 0]], + ["Forward", [0x01, 0, 0xf4, 0]], + ["Scroll Up", [0x01, 0, 0xf5, 0x01]], + ["Scroll Down", [0x01, 0, 0xf5, 0xff]], + ["DPI Loop", [0x14, 0, 0x00, 0]], + ["DPI +", [0x14, 0, 0x01, 0]], + ["DPI -", [0x14, 0, 0x02, 0]], + ["Volume Up", [0x03, 0, 0xe9, 0]], + ["Volume Down", [0x03, 0, 0xea, 0]], + ["Mute", [0x03, 0, 0xe2, 0]], + ["Play/Pause", [0x03, 0, 0xcd, 0]], + ["Disabled", [0, 0, 0, 0]], +]; + +/** Action label for a 4-byte slot; "Custom" for keys, combinations and macros. */ +export function am30DecodeButtonAction(bytes: ArrayLike): string { + const match = AM30_BUTTON_ACTIONS.find(([, value]) => value.every((b, i) => b === bytes[i])); + return match?.[0] ?? "Custom"; +} + +export function am30EncodeButtonAction(label: string): readonly [number, number, number, number] | null { + return AM30_BUTTON_ACTIONS.find(([l]) => l === label)?.[1] ?? null; +} + +/** Factory assignments, from the first cable read of the key matrix. */ +export const AM30_DEFAULT_BUTTON_MAPPINGS: Readonly> = { + Left: "Left Click", + Right: "Right Click", + Middle: "Middle Click", + Back: "Back", + Forward: "Forward", + "Scroll Up": "Scroll Up", + "Scroll Down": "Scroll Down", +}; + +/** A Yichip-protocol Angry Miao model, keyed by its `8F` device id. */ +export interface AngryMiaoProfile { + deviceId: number; + brand: "Angry Miao"; + model: string; + sensor: string; + maxPollingHz: number; + minDpi: number; + maxDpi: number; + dpiStep: number; + /** Key matrix slot per physical button. */ + buttons: ReadonlyArray<{ name: string; slot: number }>; +} + +/** + * Device id 2222 (0x08AE) and firmware bytes 0x0318 were read over the USB + * cable (0x3151:0x402A). PAW3950 and 50-30000 DPI are from the retail listing + * and the AM30 manual; the top stage reads back 30000. + */ +export const ANGRY_MIAO_INFINITY_PROFILE: AngryMiaoProfile = { + deviceId: 2222, + brand: "Angry Miao", + model: "Infinity .100", + sensor: "PixArt PAW3950", + maxPollingHz: 8000, + minDpi: 50, + maxDpi: 30000, + dpiStep: 50, + // Slot 3 is Forward and slot 4 is Back on this mouse. Slot 5 reads DPI Loop, + // but the mouse has no DPI button, so it is not offered. Slots 12 and 13 + // hold a second wheel pair the vendor app does not show. + buttons: [ + { name: "Left", slot: 0 }, + { name: "Right", slot: 1 }, + { name: "Middle", slot: 2 }, + { name: "Back", slot: 4 }, + { name: "Forward", slot: 3 }, + { name: "Scroll Up", slot: 14 }, + { name: "Scroll Down", slot: 15 }, + ], +}; + +export const ANGRY_MIAO_PROFILES: ReadonlyMap = new Map([ + [ANGRY_MIAO_INFINITY_PROFILE.deviceId, ANGRY_MIAO_INFINITY_PROFILE], +]); + +export interface AngryMiaoTransport { + transport: "direct" | "dongle" | "bluetooth"; + /** The settings collection on this link. */ + usagePage: number; + usage: number; +} + +/** Transport by product id. The receiver relays every mouse command; Bluetooth wraps them in report 6. */ +export const ANGRY_MIAO_PRODUCTS: ReadonlyMap = new Map([ + [0x402a, { transport: "direct", usagePage: AM30_USAGE_PAGE, usage: AM30_USAGE }], + [0x5007, { transport: "dongle", usagePage: AM30_USAGE_PAGE, usage: AM30_USAGE }], + [0x402c, { transport: "bluetooth", usagePage: AM30_BT_USAGE_PAGE, usage: AM30_BT_USAGE }], +]); diff --git a/src/drivers/angry-miao/hid.test.ts b/src/drivers/angry-miao/hid.test.ts new file mode 100644 index 00000000..0e591761 --- /dev/null +++ b/src/drivers/angry-miao/hid.test.ts @@ -0,0 +1,910 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { + AM30_CMD, + AM30_GET_USB_VERSION, + AM30_OPT0_DEBOUNCE as OPT0_DEBOUNCE, + AM30_OPT0_DEBOUNCE_24G as OPT0_DEBOUNCE_24G, + AM30_OPT0_DEBOUNCE_BT as OPT0_DEBOUNCE_BT, + AM30_OPT0_FLAGS as OPT0_FLAGS, + AM30_OPT0_REPORT_RATE as OPT0_REPORT_RATE, + AM30_OPT0_SLEEP_24G as OPT0_SLEEP_24G, +} from "@openmouse/protocol/angry-miao"; +import { DEVICE_DRIVERS } from "../registry.ts"; +import { AngryMiaoHidClient } from "./hid.ts"; + +/** Every registered driver that would take this device. */ +const claimants = (device: HIDDevice) => DEVICE_DRIVERS.filter((driver) => driver.supports(device)).map((driver) => driver.brand); + +/** The block names the captures were recorded under (`usbVersion` is the `8F` device id read). */ +const CMD = { + ...AM30_CMD, + GET_USB_VERSION: AM30_CMD.GET_DEVICE_ID, + GET_OPTIONPARAM0: AM30_CMD.GET_OPTIONS, + SET_OPTIONPARAM0: AM30_CMD.SET_OPTIONS, +} as const; + +const WIRED = { vendorId: 0x3151, productId: 0x402a }; +const RECEIVER = { vendorId: 0x3151, productId: 0x5007 }; +const capture = (name: string) => + JSON.parse(readFileSync(new URL(`../../../captures/angry-miao-infinity/${name}`, import.meta.url), "utf8")); + +/** + * The cable answers each checksummed command directly. The receiver answers + * F7 and its own light commands itself, and hands back a mouse reply only + * after the relayed command and FC. + */ +function fakeDevice(options: { + ids: { vendorId: number; productId: number }; + productName?: string; + replies?: Record; + receiverReplies?: Record; + status?: number[]; + /** False for a mouse that ignores options writes, so `D3` keeps answering the old block. */ + keepsOptions?: boolean; +}) { + const usbVersion = new Array(64).fill(0); + usbVersion.splice(0, 3, CMD.GET_USB_VERSION, 2222 & 0xff, 2222 >> 8); + // `85`: the first profile is active. + const profile = [0x85, 0, 0, 0, 0, 0, 0, 0x7a]; + const replies: Record = { [CMD.GET_USB_VERSION]: usbVersion, [0x85]: profile, ...options.replies }; + const wired = options.ids.productId === WIRED.productId; + const sent: Uint8Array[] = []; + const report = (bytes: number[] | null) => { + const out = new Uint8Array(64); + if (bytes) out.set(bytes.slice(0, 64)); + return out; + }; + // Ready to read, mouse battery 0x64, mouse online, ready to send. + const status = report(options.status ?? [1, 0, 0x64, 1, 0, 1]); + let pending: number[] | null = null; + let last = status; + const device = { + ...options.ids, + productName: options.productName ?? (wired ? "Angry Miao Infinity" : "AM INFINITY 8K MOUSE"), + opened: true, + collections: [{ usagePage: 0xffff, usage: 0x02, children: [] }], + open: async () => {}, + close: async () => {}, + sendFeatureReport: async (_id: number, data: Uint8Array) => { + sent.push(new Uint8Array(data)); + const head = data[0]; + if (head === 0xf7) last = status; + else if (head === 0xf6 || head === 0xfe) { /* relay prelude */ } + else if (head === 0xfc) last = report(pending); + else if (options.receiverReplies?.[head]) last = report(options.receiverReplies[head]); + else if (head === CMD.SET_OPTIONPARAM0 && options.keepsOptions !== false && replies[CMD.GET_OPTIONPARAM0]) { + // The mouse keeps the block, so the read-back sees it. A copy, so a test's baseline array stays as read. + const held = replies[CMD.GET_OPTIONPARAM0]; + replies[CMD.GET_OPTIONPARAM0] = Array.from({ length: 64 }, (_, i) => (i < 8 ? held[i] ?? 0 : data[i])); + pending = null; + } else { + pending = replies[head] ?? null; + if (wired) last = report(pending); + } + }, + receiveFeatureReport: async () => new DataView(last.buffer.slice(0)), + }; + return { device: device as unknown as HIDDevice, sent }; +} + +/** The mouse on Bluetooth (3151:402C), answering report 6 from the Bluetooth capture; other commands read zeros. */ +function fakeBluetooth() { + const { replies } = capture("bluetooth-reads.json") as { replies: Record }; + const byCommand = new Map(Object.values(replies).map(({ request, reply }) => [request.slice(0, 4), reply])); + const listeners = new Set<(event: unknown) => void>(); + const sent: Uint8Array[] = []; + const device = { + vendorId: 0x3151, + productId: 0x402c, + productName: "AM INFINITY BT MOUSE", + opened: true, + collections: [{ usagePage: 0xff55, usage: 0x0202, children: [] }], + open: async () => {}, + close: async () => {}, + addEventListener: (_type: string, listener: (event: unknown) => void) => listeners.add(listener), + removeEventListener: (_type: string, listener: (event: unknown) => void) => listeners.delete(listener), + sendReport: async (_id: number, data: Uint8Array) => { + sent.push(new Uint8Array(data)); + const key = Buffer.from(data.subarray(0, 2)).toString("hex"); + if (data[1] === CMD.SET_OPTIONPARAM0) { + // The mouse keeps the block, so the `D3` read-back sees it. + const readKey = `55${CMD.GET_OPTIONPARAM0.toString(16)}`; + const held = Buffer.alloc(65); + held.set(Buffer.from(byCommand.get(readKey)!, "hex").subarray(0, 9)); + held.set(data.subarray(9, 65), 9); + byCommand.set(readKey, held.toString("hex")); + return; + } + const hex = byCommand.get(key) ?? (data[0] === 0x55 ? key : null); + if (hex === null) return; + const out = new Uint8Array(65); + out.set(Buffer.from(hex, "hex")); + queueMicrotask(() => listeners.forEach((listener) => listener({ reportId: 6, data: new DataView(out.buffer) }))); + }, + sendFeatureReport: async () => { throw new Error("Bluetooth has no feature reports."); }, + }; + return { device: device as unknown as HIDDevice, sent }; +} + +/** Makes the fake keep what it is sent, as the mouse does: `54` replaces the `D4` table, `53` the `D3` block and `05` the `85` profile. */ +function holdWrites(device: HIDDevice, held: { dpi?: number[]; option0?: number[]; profile?: number[] }) { + const fake = device as unknown as { sendFeatureReport: (id: number, data: Uint8Array) => Promise }; + const send = fake.sendFeatureReport; + fake.sendFeatureReport = async (id, data) => { + if (data[0] === CMD.SET_DPI && held.dpi) held.dpi.splice(2, 62, ...data.subarray(2, 64)); + if (data[0] === CMD.SET_OPTIONPARAM0 && held.option0) held.option0.splice(8, 56, ...data.subarray(8, 64)); + if (data[0] === 0x05 && held.profile) held.profile[1] = data[1]; + return send(id, data); + }; +} + +describe("AngryMiaoHidClient", () => { + it("reads and writes over Bluetooth in report 6, as captured", async () => { + const { device, sent } = fakeBluetooth(); + assert.equal(AngryMiaoHidClient.isSupported(device), true); + assert.deepEqual(claimants(device), ["Angry Miao"], "the AJ179 PRO driver shares 0x402C"); + const client = new AngryMiaoHidClient(device); + const status = await client.readStatus(); + assert.equal(status.name, "Angry Miao Infinity .100"); + assert.deepEqual([status.connectionType, status.connectionDetail], ["Wireless", "Bluetooth"]); + assert.equal(status.batteryPercent, 78, "D6 reads zeros here, so the 77 battery request answers"); + assert.deepEqual(status.dpiStages, [400, 800, 1200, 1600, 3200, 6400, 10000, 30000]); + assert.equal(status.pollingRateHz, 8000); + assert.equal(status.sleepTimeout, 600, "the Bluetooth timer, bytes 40-41"); + assert.equal(status.debounceMs, 10); + assert.deepEqual(status.firmware, ["Mouse SoC 0x0318", "PixArt PAW3950"]); + assert.equal(sent.some((report) => report[1] === AM30_GET_USB_VERSION), false, "AD is a cable read"); + + await client.setSleepTimeout(300); + const write = sent.findLast((report) => report[1] === CMD.SET_OPTIONPARAM0)!; + assert.deepEqual([write[0], write[1]], [0x55, CMD.SET_OPTIONPARAM0]); + assert.equal(sent.at(-1)![1], CMD.GET_OPTIONPARAM0, "the write is read back"); + assert.deepEqual([...write.subarray(1 + 40, 1 + 46)], [0x2c, 0x01, 0x2c, 0x01, 0x3c, 0x00], "only the Bluetooth timer changes"); + }); + + it("claims its cable and receiver by product id and name; the registry keeps the shared driver and Fantech off them", () => { + for (const ids of [WIRED, RECEIVER]) { + const { device } = fakeDevice({ ids }); + assert.equal(AngryMiaoHidClient.isSupported(device), true); + assert.deepEqual(claimants(device), ["Angry Miao"]); + } + assert.equal(AngryMiaoHidClient.isSupported(fakeDevice({ ids: { vendorId: 0x3151, productId: 0x402d } }).device), false); + // linux-hardware.org lists an AJAZZ receiver on 3151:5007. + for (const productName of ["AJAZZ 2.4G 8K", ""]) { + assert.equal(AngryMiaoHidClient.isSupported(fakeDevice({ ids: RECEIVER, productName }).device), false, productName); + } + assert.equal(new AngryMiaoHidClient(fakeDevice({ ids: WIRED }).device).transport, "direct"); + assert.equal(new AngryMiaoHidClient(fakeDevice({ ids: RECEIVER }).device).transport, "dongle"); + }); + + it("identifies the Infinity by cable from captured replies", async () => { + const reads = capture("cable-reads.json"); + // The two identity captures are truncated to 16 bytes; pad them to a full report. + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_USB_VERSION]: bytes("usbVersion"), + [CMD.GET_FIRMWARE]: bytes("firmware"), + [CMD.GET_DPI]: bytes("dpi"), + [CMD.GET_OPTIONPARAM0]: bytes("option0"), + [CMD.GET_KEYMATRIX]: bytes("keyMatrix"), + // Battery read on the cable: full at 100 %. + [0xd6]: [0xd6, 0x02, 0x01, 0x64, 0, 0, 0, 0x29], + // Blast Mode read on the cable: off. + [0xe2]: [0xe2, 0, 0, 0, 0, 0, 0, 0x1d], + // USB firmware read on the cable: 0x0101. + [0xad]: [0xad, 0x01, 0x01, 0, 0, 0, 0, 0x52], + } }); + const client = new AngryMiaoHidClient(device); + assert.equal(await client.getDeviceId(), 2222); + + const status = await client.readStatus(); + assert.equal(status.brand, "Angry Miao"); + assert.equal(status.ui?.family, "angry-miao"); + assert.equal(status.name, "Angry Miao Infinity .100"); + assert.equal(status.batteryPercent, 100); + assert.equal(status.batteryState, "Full"); + assert.deepEqual(status.dpiStages, [400, 800, 1200, 1600, 3200, 6400, 10000, 30000]); + assert.equal(status.activeDpiStage, 3); + assert.equal(status.pollingRateHz, 1000); + // Raw USB debounce 3 at 1000 Hz is gear 4, which the vendor slider labels 10 ms. + assert.equal(status.debounceMs, 10); + assert.equal(status.sleepTimeout, 30); + assert.equal(status.rippleControl, false); + assert.equal(status.angleSnapping, false); + assert.equal(status.motionSync, false); + assert.equal(status.turboMode, false, "Blast Mode"); + assert.deepEqual([status.lighting?.mode, status.lighting?.color], ["Off", "#ffffff"]); + assert.equal(status.lightingZones, undefined, "no receiver light on the cable"); + assert.equal(status.ui?.hideAdvancedLighting, true, "the light shows once, in the Lighting tab"); + assert.equal(status.liftOffDistance, "Medium", "PAW3950 index 1 is the middle stop"); + assert.equal(status.connectionDetail, "USB"); + assert.deepEqual(status.firmware, ["Mouse SoC 0x0318", "Mouse USB 0x0101", "PixArt PAW3950"], "raw codes, not the shared driver's v3.24"); + assert.equal(status.supportedPollingRates.at(-1), 8000); + assert.deepEqual(client.getDebounceOptions(), [0, 5, 10, 15, 20, 25, 30]); + assert.equal(client.getDebounceMaxMs(), 30); + assert.deepEqual(client.getSleepOptions(), [0, 15, 30, 60, 600, 1800, 3600]); + assert.equal(client.getDpiOptions().at(-1), 30000); + assert.equal(sent.some((report) => [0xf6, 0xf7, 0xfc].includes(report[0])), false, "cable skips the receiver relay"); + // Slot 3 holds Forward and slot 4 holds Back; slot 5 reads DPI Loop, but the mouse has no DPI button. + assert.deepEqual(status.buttonMappings, { + Left: "Left Click", Right: "Right Click", Middle: "Middle Click", Back: "Back", Forward: "Forward", + "Scroll Up": "Scroll Up", "Scroll Down": "Scroll Down", + }); + assert.deepEqual(status.defaultButtonMappings, status.buttonMappings, "the first cable read is the factory map"); + assert.deepEqual(status.fixedButtons, ["Left"]); + assert.deepEqual(status.ui?.dpiStageEditor, { maxStages: 8, countEditable: true, minDpi: 50, maxDpi: 30000, stepDpi: 50 }); + + await client.setButtonMapping("Back", "Middle Click"); + assert.equal(sent.filter((report) => report[0] === CMD.SET_KEYMATRIX).at(-1)![2], 4, "Back is slot 4"); + await client.setButtonMapping("Left", "Right Click"); + const left = sent.filter((report) => report[0] === CMD.SET_KEYMATRIX).at(-1)!; + assert.deepEqual([left[2], ...left.slice(8, 12)], [0, 1, 0, 0xf0, 0], "Left is always written as Left Click"); + await assert.rejects(client.setButtonMapping("DPI", "DPI Loop"), /Unknown button/); + + assert.equal(await client.setTurboMode(true), true); + // Captured from the vendor app: Blast Mode on is 62 01 ... 9C. + assert.deepEqual([...sent.filter((report) => report[0] === 0x62).at(-1)!.subarray(0, 8)], [0x62, 1, 0, 0, 0, 0, 0, 0x9c]); + assert.equal((await client.readStatus()).turboMode, true, "the written value wins over E2, which reads 0 on SoC 1.1.1"); + }); + + it("derives writes from the captured cable settings", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const option0 = bytes("option0"); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: bytes("dpi"), + [CMD.GET_OPTIONPARAM0]: option0, + [CMD.GET_KEYMATRIX]: bytes("keyMatrix"), + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + const lastWrite = () => sent.filter((report) => report[0] === CMD.SET_OPTIONPARAM0).at(-1)!; + // The mouse keeps each write, so a change is measured against the block it held just before. + let held = option0; + const step = async (run: () => Promise) => { + held = [...await client.getOptionParam0()]; + await run(); + return lastWrite(); + }; + const changed = (write: Uint8Array) => [...write.keys()].filter((i) => i >= 8 && write[i] !== held[i]); + + // Captured: 1000 -> 8000 Hz kept the 10 ms stop as USB 15, 2.4G 15, Bluetooth 3. + let write = await step(() => client.setPollingRate(8000)); + assert.equal(write[7], 0xac); + assert.deepEqual( + [write[OPT0_REPORT_RATE], write[OPT0_DEBOUNCE], write[OPT0_DEBOUNCE_24G], write[OPT0_DEBOUNCE_BT]], + [0x81, 15, 15, 3], + ); + assert.deepEqual(changed(write), [OPT0_REPORT_RATE, OPT0_DEBOUNCE, OPT0_DEBOUNCE_24G, OPT0_DEBOUNCE_BT]); + assert.deepEqual([write[17], write[18]], [0, 0], "bytes 17/18 stay as read"); + + // 5 ms is gear 5: raw 2 at 1000 Hz on every link. + await client.setPollingRate(1000); + write = await step(() => client.setDebounceTime(5)); + assert.deepEqual([write[OPT0_DEBOUNCE], write[OPT0_DEBOUNCE_24G], write[OPT0_DEBOUNCE_BT]], [2, 2, 2]); + assert.deepEqual(changed(write), [OPT0_DEBOUNCE, OPT0_DEBOUNCE_24G, OPT0_DEBOUNCE_BT]); + assert.equal(await client.setDebounceTime(7), 5, "snaps to the nearest slider stop"); + + await client.setSleepTimeout(0); + assert.deepEqual([...lastWrite().subarray(40, 48)], [0x58, 0x02, 0, 0, 0xff, 0xff, 0, 0], "never is 0xFFFF on the cable's (2.4 GHz) timer only"); + + await client.setRippleControl(true); + assert.equal(lastWrite()[OPT0_FLAGS], 1); + + write = await step(() => client.setMotionSync(true)); + assert.deepEqual(changed(write), [63]); + assert.equal(lastWrite()[63], 1); + + // The vendor's lighting panel writes one colour into both RGB slots. + write = await step(() => client.setLighting({ mode: "Static", color: "#d0021b" })); + assert.deepEqual([...write.subarray(54, 61)], [0xd0, 0x02, 0x1b, 0xd0, 0x02, 0x1b, 1]); + assert.deepEqual(changed(write), [54, 55, 56, 57, 58, 59, 60]); + write = await step(() => client.setLighting({ mode: "Off", color: "#d0021b" })); + assert.deepEqual(changed(write), [60], "off clears the switch and keeps the colours"); + await assert.rejects(client.setLighting({ zone: "Receiver", mode: "Static", color: "#ffffff" }), /receiver/); + + // Captured from the vendor app: 1600 -> 3200 DPI (stage 3 -> 4) and back. + const lastDpiWrite = () => sent.filter((report) => report[0] === CMD.SET_DPI).at(-1)!; + await client.setActiveDpiStage(4); + assert.deepEqual([...lastDpiWrite().subarray(0, 8)], [0x54, 0x00, 0x04, 0x08, 0x00, 0x00, 0x00, 0x9f]); + assert.deepEqual([...lastDpiWrite().subarray(8)], bytes("dpi").slice(8), "stage table and colours are kept"); + }); + + it("sends the same writes as the vendor app, byte for byte", async () => { + const vendor = capture("cable-vendor-writes.json"); + const bytes = (hex: string) => [...Buffer.from(hex, "hex")]; + const write = (change: string) => bytes(vendor.writes.find((w: { change: string }) => w.change === change).hex); + // The fake keeps each options write, as the mouse does, so the next change starts from it. + const option0 = bytes(vendor.reads.option0); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: bytes(vendor.reads.dpi), + [CMD.GET_OPTIONPARAM0]: option0, + [CMD.GET_KEYMATRIX]: bytes(vendor.reads.keyMatrix), + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + const steps: Array<[string, () => Promise]> = [ + ["polling rate 1000 -> 8000 Hz", () => client.setPollingRate(8000)], + ["polling rate 8000 -> 1000 Hz", () => client.setPollingRate(1000)], + ["debounce 10 -> 5 ms", () => client.setDebounceTime(5)], + ["debounce 5 -> 10 ms", () => client.setDebounceTime(10)], + ["2.4 GHz standby 30 s -> never", () => client.setSleepTimeout(0)], + ["2.4 GHz standby never -> 30 s", () => client.setSleepTimeout(30)], + ["ripple control off -> on", () => client.setRippleControl(true)], + ["ripple control on -> off", () => client.setRippleControl(false)], + ["DPI stage 8 colour #ffffff -> #d0021b", () => client.setDpiStageColor(7, "#d0021b")], + ["DPI stage 8 colour #d0021b -> #ffffff", () => client.setDpiStageColor(7, "#ffffff")], + ["button Back -> Middle click", () => client.setButtonMapping("Back", "Middle Click")], + ["button Middle click -> Back", () => client.setButtonMapping("Back", "Back")], + ]; + for (const [change, run] of steps) { + await run(); + const last = [...sent.findLast((report) => [CMD.SET_OPTIONPARAM0, CMD.SET_DPI, CMD.SET_KEYMATRIX].includes(report[0]))!]; + assert.deepEqual(last, write(change), change); + } + }); + + it("remaps the wheel and offers the vendor app's scroll, DPI and media actions", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const keyMatrix = bytes("keyMatrix"); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: bytes("dpi"), + [CMD.GET_OPTIONPARAM0]: bytes("option0"), + [CMD.GET_KEYMATRIX]: keyMatrix, + } }); + const client = new AngryMiaoHidClient(device); + const status = await client.readStatus(); + assert.deepEqual(status.buttonOptions, [ + "Left Click", "Right Click", "Middle Click", "Back", "Forward", "Scroll Up", "Scroll Down", + "DPI Loop", "DPI +", "DPI -", "Volume Up", "Volume Down", "Mute", "Play/Pause", "Disabled", + ]); + const lastRemap = () => { + const write = sent.filter((report) => report[0] === CMD.SET_KEYMATRIX).at(-1)!; + return [write[1], write[2], ...write.subarray(8, 12)]; + }; + // Header and actions from the vendor app: wheel up is slot 14 (`50 00 0E`), wheel down slot 15. + await client.setButtonMapping("Scroll Up", "Scroll Down"); + assert.deepEqual(lastRemap(), [0, 14, 0x01, 0, 0xf5, 0xff]); + await client.setButtonMapping("Scroll Down", "Disabled"); + assert.deepEqual(lastRemap(), [0, 15, 0, 0, 0, 0]); + await client.setButtonMapping("Back", "Volume Up"); + assert.deepEqual(lastRemap(), [0, 4, 0x03, 0, 0xe9, 0]); + await client.setButtonMapping("Forward", "DPI -"); + assert.deepEqual(lastRemap(), [0, 3, 0x14, 0, 0x02, 0]); + await assert.rejects(client.setButtonMapping("Back", "Polling +"), /Unsupported button action/); + + // Restore writes only the buttons that moved from their factory action. + keyMatrix.splice(16, 4, 0x03, 0, 0xe9, 0); + keyMatrix.splice(60, 4, 0, 0, 0, 0); + assert.equal((await client.readStatus()).buttonMappings?.Back, "Volume Up"); + const before = sent.length; + await client.resetButtonMappings(); + const restores = sent.slice(before).filter((report) => report[0] === CMD.SET_KEYMATRIX); + assert.deepEqual( + restores.map((write) => [write[2], ...write.subarray(8, 12)]), + [[4, 0x01, 0, 0xf3, 0], [15, 0x01, 0, 0xf5, 0xff]], + ); + }); + + it("sets the active stage's DPI from one read of the table", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: bytes("dpi"), + [CMD.GET_OPTIONPARAM0]: bytes("option0"), + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + const before = sent.length; + assert.equal(await client.setDpi(1700), 1700); + const after = sent.slice(before); + assert.equal(after.filter((report) => report[0] === CMD.GET_DPI).length, 1); + const write = after.find((report) => report[0] === CMD.SET_DPI)!; + assert.equal(write[2], 3, "the captured table's active stage"); + assert.deepEqual([...write.subarray(8 + 3 * 2, 8 + 4 * 2)], [0xa4, 0x06], "1700 DPI on stage 4's X axis"); + }); + + it("lists the stage count from the status read's own DPI reply", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const dpi = bytes("dpi"); + const { device } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: dpi, + [CMD.GET_OPTIONPARAM0]: bytes("option0"), + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + // The status read gets eight stages, then another D4 sees two before the status read finishes. + const fake = device as unknown as { sendFeatureReport: (id: number, data: Uint8Array) => Promise }; + const send = fake.sendFeatureReport; + fake.sendFeatureReport = async (id, data) => { + await send(id, data); + if (data[0] === CMD.GET_DPI) { + fake.sendFeatureReport = send; + dpi.splice(2, 2, 1, 2); + void client.getDpi(); + } + }; + const status = await client.readStatus(); + assert.equal(status.dpiStages.length, 8); + assert.equal(status.activeDpiStage, 3); + }); + + it("writes the DPI stage count and keeps every stage's value", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const dpi = bytes("dpi"); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: dpi, + [CMD.GET_OPTIONPARAM0]: bytes("option0"), + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + const lastDpiWrite = () => sent.filter((report) => report[0] === CMD.SET_DPI).at(-1)!; + + // Captured header for 8 -> 7 stages: `54 00 03 07`, whole table sent. + assert.equal(await client.setDpiStageCount(7), 7); + assert.deepEqual([...lastDpiWrite().subarray(0, 4)], [0x54, 0, 3, 7]); + assert.deepEqual([...lastDpiWrite().subarray(8)], dpi.slice(8), "all eight stages and colours are kept"); + // Captured: at 3 stages the active stage clamps from 3 to 2. + await client.setDpiStageCount(3); + assert.deepEqual([...lastDpiWrite().subarray(0, 4)], [0x54, 0, 2, 3]); + await assert.rejects(client.setDpiStageCount(0), /1 to 8/); + await assert.rejects(client.setDpiStageCount(9), /1 to 8/); + + // The mouse holds 2 stages: only those show, the hidden six still ride along in writes. + dpi.splice(2, 2, 1, 2); + const status = await client.readStatus(); + assert.deepEqual(status.dpiStages, [400, 800]); + assert.deepEqual(status.dpiStageColors, ["#ff0000", "#ff3200"]); + assert.equal(status.activeDpiStage, 1); + await client.setDpiStageColor(1, "#ffffff"); + assert.deepEqual([...lastDpiWrite().subarray(0, 4)], [0x54, 0, 1, 2]); + assert.deepEqual([...lastDpiWrite().subarray(8, 40)], dpi.slice(8, 40), "hidden stage values survive an edit"); + await client.setDpiStageValue(0, 450); + assert.deepEqual([...lastDpiWrite().subarray(0, 4)], [0x54, 0, 1, 2]); + assert.deepEqual([...lastDpiWrite().subarray(8, 10)], [0xc2, 0x01]); + await assert.rejects(client.setDpiStageValue(0, 425), /50 DPI steps/); + await client.setActiveDpiStage(5); + assert.equal(lastDpiWrite()[2], 1, "the active stage stays within the count"); + + // A slot the mouse returns empty is filled the way the vendor app fills it. + dpi.fill(0, 8 + 7 * 2, 8 + 8 * 2); + dpi.fill(0, 24 + 7 * 2, 24 + 8 * 2); + await client.setDpiStageCount(8); + const write = lastDpiWrite(); + assert.deepEqual([write[8 + 14], write[8 + 15], write[24 + 14], write[24 + 15]], [0x20, 0x03, 0x20, 0x03]); + assert.deepEqual([...write.subarray(40 + 21, 40 + 24)], [0xff, 0, 0]); + }); + + it("reads and switches the onboard profile the way the vendor app does", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const profileReply = [0x85, 1, 0, 0, 0, 0, 0, 0x79]; + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: bytes("dpi"), + [CMD.GET_OPTIONPARAM0]: bytes("option0"), + [CMD.GET_KEYMATRIX]: bytes("keyMatrix"), + [0x85]: profileReply, + } }); + const client = new AngryMiaoHidClient(device); + const status = await client.readStatus(); + assert.equal(status.profileCount, 2); + assert.equal(status.activeProfile, 2, "85 byte 1 = 1 is the second profile"); + assert.equal(sent.find((report) => report[0] === CMD.GET_KEYMATRIX)![1], 1, "the key map is read for the active profile"); + assert.equal(sent.find((report) => report[0] === CMD.GET_DPI)![1], 0, "D4 carries no profile byte"); + await client.setButtonMapping("Back", "Forward"); + assert.equal(sent.filter((report) => report[0] === CMD.SET_KEYMATRIX).at(-1)![1], 1); + + // Captured: to profile 0 is `05 00 02 ... F8`, then the app sends `62 00`. + profileReply[1] = 0; + assert.equal(await client.setProfile(1), 1); + const switchAt = sent.findLastIndex((report) => report[0] === 0x05); + assert.deepEqual([...sent[switchAt].subarray(0, 8)], [0x05, 0, 2, 0, 0, 0, 0, 0xf8]); + assert.equal(sent[switchAt + 1][0], 0x85, "confirmed with 85"); + assert.deepEqual([...sent.at(-1)!.subarray(0, 2)], [0x62, 0], "Blast Mode off, as the vendor app does"); + assert.equal((await client.readStatus()).turboMode, false); + + await assert.rejects(client.setProfile(2), /stayed on profile 1/); + await assert.rejects(client.setProfile(3), /profiles 1 to 2/); + }); + + it("confirms a profile switch after an unanswered 85, and treats an unconfirmed switch as unknown", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const profileReply = [0x85, 0, 0, 0, 0, 0, 0, 0x7a]; + const { device } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: bytes("dpi"), + [CMD.GET_OPTIONPARAM0]: bytes("option0"), + [CMD.GET_KEYMATRIX]: bytes("keyMatrix"), + [0x85]: profileReply, + } }); + const fake = device as unknown as { sendFeatureReport: (id: number, data: Uint8Array) => Promise }; + const send = fake.sendFeatureReport; + let dropNextProfileRead = false; + fake.sendFeatureReport = async (id, data) => { + if (data[0] === 0x05) { + profileReply[1] = data[1]; + dropNextProfileRead = true; + } + if (data[0] === 0x85 && dropNextProfileRead) { + dropNextProfileRead = false; + // A report of zeros reads back as zeros, which the driver treats as unanswered. + return send(id, new Uint8Array(64)); + } + return send(id, data); + }; + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + assert.equal(await client.setProfile(2), 2); + assert.equal((await client.readStatus()).activeProfile, 2); + + // When no 85 read answers, the mouse may or may not have switched. + profileReply.fill(0); + await assert.rejects(client.setProfile(1), /did not confirm the switch to profile 1/); + await assert.rejects(client.setButtonMapping("Back", "Forward"), /active profile is unknown/); + }); + + it("hides the profile selector and keeps button mappings read-only when 85 is not answered", async () => { + const reads = capture("cable-reads.json"); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], + [CMD.GET_KEYMATRIX]: [...Buffer.from(reads.replies.keyMatrix, "hex")], + // An empty reply reads as 64 zeros, which the driver treats as unanswered. + [0x85]: [], + } }); + const client = new AngryMiaoHidClient(device); + const status = await client.readStatus(); + assert.equal(status.activeProfile, null); + assert.equal(status.profileCount, undefined); + assert.equal(status.buttonMappings, undefined, "the first profile's map may not be the active one"); + assert.equal(sent.some((report) => report[0] === CMD.GET_KEYMATRIX), false); + await assert.rejects(client.setButtonMapping("Back", "Forward"), /active profile is unknown/); + await assert.rejects(client.resetButtonMappings(), /active profile is unknown/); + assert.equal(sent.some((report) => report[0] === CMD.SET_KEYMATRIX), false); + }); + + it("reports the spare battery charging in the receiver dock", async () => { + const dongle = capture("dongle-reads.json"); + const bytes = (hex: string) => [...Buffer.from(hex, "hex")]; + const replies = { + [CMD.GET_OPTIONPARAM0]: bytes(dongle.relayed.option0), + [CMD.GET_DPI]: bytes(dongle.relayed.dpi), + [0xd6]: bytes(dongle.relayed.battery), + }; + // Idle F7 on macOS: byte 2 follows the mouse, byte 10 is the spare (vendor decoder `BO`). + const idle = [0x01, 0, 0x59, 1, 0, 1, 2, 0, 0, 1]; + const spare = async (byte10: number) => { + const { device } = fakeDevice({ ids: RECEIVER, replies, status: [...idle, byte10] }); + return (await new AngryMiaoHidClient(device).readStatus()).spareBattery; + }; + assert.deepEqual(await spare(0x5a), { percent: 90, state: "Charging" }); + assert.deepEqual(await spare(0x64), { percent: 100, state: "Full" }); + assert.equal(await spare(0), undefined, "no spare in the dock"); + assert.equal(await spare(0xff), undefined); + + const onHardware = async (status: number[]) => { + const { device } = fakeDevice({ ids: RECEIVER, replies, status }); + return (await new AngryMiaoHidClient(device).readStatus()).spareBattery; + }; + assert.deepEqual(await onHardware(bytes(dongle.status.replyReady)), { percent: 99, state: "Charging" }); + const removed = capture("receiver-spare-removed.json"); + assert.equal(await onHardware(bytes(removed.status.replyReady)), undefined, "spare taken out of the dock"); + + const { device } = fakeDevice({ ids: WIRED, replies }); + assert.equal((await new AngryMiaoHidClient(device).readStatus()).spareBattery, undefined, "the cable has no receiver"); + }); + + it("reads never-sleep and an off-table debounce byte", async () => { + const reads = capture("cable-reads.json"); + const option0 = [...Buffer.from(reads.replies.option0, "hex")]; + option0[OPT0_SLEEP_24G] = 0xff; + option0[OPT0_SLEEP_24G + 1] = 0xff; + option0[OPT0_REPORT_RATE] = 0x81; + option0[OPT0_DEBOUNCE] = 16; + const { device } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + [CMD.GET_OPTIONPARAM0]: option0, + } }); + const status = await new AngryMiaoHidClient(device).readStatus(); + assert.equal(status.sleepTimeout, 0); + assert.equal(status.pollingRateHz, 8000); + assert.equal(status.debounceMs, 10, "raw 16 at 8000 Hz is nearest to 15, the 10 ms stop"); + }); + + it("relays through the receiver the way the vendor app does", async () => { + const dongle = capture("dongle-reads.json"); + const bytes = (hex: string) => [...Buffer.from(hex, "hex")]; + const { device, sent } = fakeDevice({ + ids: RECEIVER, + // Receiver light from the tab capture: neon, slowest, full brightness, white, on. + receiverReplies: { + 0x88: [0x88, 0x03, 0x04, 0x04, 0x08, 0xff, 0xff, 0xff], + 0x87: [0x87, 0x01, 0, 0, 0, 0, 0, 0x78], + }, + replies: { + [CMD.GET_OPTIONPARAM0]: bytes(dongle.relayed.option0), + [CMD.GET_DPI]: bytes(dongle.relayed.dpi), + [CMD.GET_KEYMATRIX]: bytes(dongle.relayed.keyMatrix), + [0xd6]: bytes(dongle.relayed.battery), + [0xe2]: bytes(dongle.relayed.fpsMode), + }, + }); + const client = new AngryMiaoHidClient(device); + const status = await client.readStatus(); + assert.equal(status.name, "Angry Miao Infinity .100"); + assert.equal(status.connectionDetail, "2.4 GHz"); + assert.deepEqual(status.dpiStages, [400, 800, 1200, 1600, 3200, 6400, 10000, 30000]); + assert.equal(status.debounceMs, 10); + assert.equal(status.batteryPercent, 100, "mouse battery comes from D6, not the receiver status byte"); + assert.equal(status.batteryState, "Discharging"); + const [mouse, receiver] = status.lightingZones ?? []; + assert.equal(mouse?.zone, "Mouse"); + assert.equal(status.ui?.separateLightingZones, true, "mouse and receiver lights get their own cards"); + assert.deepEqual( + [receiver?.zone, receiver?.mode, receiver?.speed, receiver?.brightness, receiver?.color], + ["Receiver", "Neon", 1, 100, "#ffffff"], + ); + const lightReadAt = sent.findIndex((report) => report[0] === 0x88); + assert.notEqual(sent[lightReadAt - 1][0], 0xfe, "receiver commands skip the relay"); + + // Captured order: F6 05, F7 until ready, FE 40, the command, F7 until a reply is ready, FC. + const heads = sent.map((report) => report[0]); + const dpiAt = heads.indexOf(CMD.GET_DPI); + assert.deepEqual(heads.slice(0, dpiAt).filter((head) => head !== 0xf7).slice(-2), [0xf6, 0xfe]); + assert.deepEqual([...sent[heads.lastIndexOf(0xfe, dpiAt)].subarray(0, 2)], [0xfe, 0x40]); + assert.equal(heads.slice(dpiAt + 1).find((head) => head !== 0xf7), 0xfc); + + const beforeWrite = sent.length; + await client.setMotionSync(true); + const writeHeads = sent.slice(beforeWrite).map((report) => report[0]).filter((head) => head !== 0xf7); + const writeAt = writeHeads.indexOf(CMD.SET_OPTIONPARAM0); + assert.deepEqual(writeHeads.slice(writeAt - 2, writeAt + 1), [0xf6, 0xfe, CMD.SET_OPTIONPARAM0], "writes get the same prelude"); + + const beforeLight = sent.length; + await client.setLighting({ zone: "Receiver", mode: "Breathing single", color: "#d0021b", speed: 3, brightness: 50 }); + const lightWrites = sent.slice(beforeLight).filter((report) => report[0] === 0x08 || report[0] === 0x07); + assert.deepEqual([...lightWrites[0].subarray(0, 9)], [0x08, 2, 2, 2, 7, 0xd0, 0x02, 0x1b, 0xfd]); + assert.deepEqual([...lightWrites[1].subarray(0, 8)], [0x07, 1, 0, 0, 0, 0, 0, 0xf7]); + await client.setLighting({ zone: "Receiver", mode: "Off", color: null }); + assert.deepEqual([...sent.at(-3)!.subarray(0, 2)], [0x07, 0], "off only flips the switch"); + }); + + it("only writes to a device id it has verified", async () => { + const reads = capture("cable-reads.json"); + // 1893 is the Attack Shark R2, another mouse on this chip. + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_USB_VERSION]: [CMD.GET_USB_VERSION, 1893 & 0xff, 1893 >> 8], + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], + } }); + const client = new AngryMiaoHidClient(device); + const status = await client.readStatus(); + assert.equal(status.ui?.settingsReady, false); + assert.equal(status.ui?.receiverOnly, undefined, "the mouse answered; only its id is unknown"); + assert.match(status.ui?.statusNote ?? "", /1893/); + await assert.rejects(client.setMotionSync(true), /not a verified Angry Miao model/); + await assert.rejects(client.setDpiStageCount(4), /not a verified Angry Miao model/); + assert.equal(sent.some((report) => report[0] === CMD.SET_OPTIONPARAM0 || report[0] === CMD.SET_DPI), false); + }); + + it("runs each setting change and status read as one step, so none undoes or misdirects another", async () => { + const reads = capture("cable-reads.json"); + const bytes = (key: string) => [...Buffer.from(reads.replies[key], "hex"), ...new Array(64).fill(0)].slice(0, 64); + const dpi = bytes("dpi"); + const option0 = bytes("option0"); + const keyMatrix = bytes("keyMatrix"); + const profile = [0x85, 0, 0, 0, 0, 0, 0, 0x7a]; + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: dpi, + [CMD.GET_OPTIONPARAM0]: option0, + [CMD.GET_KEYMATRIX]: keyMatrix, + [0x85]: profile, + } }); + holdWrites(device, { dpi, option0, profile }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + + // Two DPI table edits started together both stay on the mouse. + await Promise.all([client.setDpiStageColor(0, "#00ff00"), client.setDpiStageValue(1, 900)]); + const table = await client.getDpi(); + assert.equal(table.stages[0].rgb, 0x00ff00); + assert.equal(table.stages[1].x, 900); + + // A remap started right after a profile switch goes to the new profile. + await Promise.all([client.setProfile(2), client.setButtonMapping("Back", "Forward")]); + assert.equal(sent.filter((report) => report[0] === CMD.SET_KEYMATRIX).at(-1)![1], 1); + + // A restore started right after a profile switch reads and writes the new profile. + keyMatrix.splice(16, 4, 0x03, 0, 0xe9, 0); + const before = sent.length; + await Promise.all([client.setProfile(1), client.resetButtonMappings()]); + const restore = sent.slice(before).filter((report) => report[0] === CMD.GET_KEYMATRIX || report[0] === CMD.SET_KEYMATRIX); + assert.deepEqual(restore.map((report) => [report[0], report[1]]), [[CMD.GET_KEYMATRIX, 0], [CMD.SET_KEYMATRIX, 0]]); + }); + + it("sends no setting change once 8F reports a device id it has not verified", async () => { + const reads = capture("cable-reads.json"); + const usbVersion = new Array(64).fill(0); + usbVersion.splice(0, 3, CMD.GET_USB_VERSION, 2222 & 0xff, 2222 >> 8); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_USB_VERSION]: usbVersion, + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + // The next status read finds another model, and a change starts before that read finishes. + usbVersion.splice(1, 2, 1893 & 0xff, 1893 >> 8); + const [status, change] = await Promise.allSettled([client.readStatus(), client.setMotionSync(true)]); + assert.equal(status.status === "fulfilled" && status.value.ui?.settingsReady, false); + assert.equal(change.status, "rejected"); + assert.equal(sent.some((report) => report[0] === CMD.SET_OPTIONPARAM0), false); + }); + + it("reads every options change back and fails when the mouse does not keep it", async () => { + const reads = capture("cable-reads.json"); + const { device, sent } = fakeDevice({ ids: WIRED, keepsOptions: false, replies: { + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + await assert.rejects(client.setMotionSync(true), /did not keep the change: options byte 63/); + const heads = sent.map((report) => report[0]); + assert.equal(heads.at(-1), CMD.GET_OPTIONPARAM0, "D3 read after the write"); + assert.equal(heads.at(-2), CMD.SET_OPTIONPARAM0); + }); + + it("keeps both of two settings changes sent back to back", async () => { + const reads = capture("cable-reads.json"); + const option0 = [...Buffer.from(reads.replies.option0, "hex"), ...new Array(64).fill(0)].slice(0, 64); + const { device } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + [CMD.GET_OPTIONPARAM0]: option0, + } }); + // The mouse keeps each options block it is sent, so the next read returns it. + const fake = device as unknown as { sendFeatureReport: (id: number, data: Uint8Array) => Promise }; + const send = fake.sendFeatureReport; + fake.sendFeatureReport = async (id, data) => { + if (data[0] === CMD.SET_OPTIONPARAM0) option0.splice(8, 56, ...data.subarray(8)); + return send(id, data); + }; + const client = new AngryMiaoHidClient(device); + assert.equal((await client.readStatus()).liftOffDistance, "Medium"); + // Neither call waits for the other, as when two controls change at once. + await Promise.all([client.setLiftOffDistance("Low"), client.setMotionSync(true)]); + const status = await client.readStatus(); + assert.equal(status.liftOffDistance, "Low"); + assert.equal(status.motionSync, true); + }); + + it("accepts a settings change while a status read is running", async () => { + const reads = capture("cable-reads.json"); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + [CMD.GET_OPTIONPARAM0]: [...Buffer.from(reads.replies.option0, "hex")], + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + // A background poll starts, then the user changes a setting before it finishes. + const poll = client.readStatus(); + assert.equal(await client.setMotionSync(true), true); + assert.equal((await poll).ui?.settingsReady, true); + assert.equal(sent.filter((report) => report[0] === CMD.SET_OPTIONPARAM0).length, 1); + }); + + it("sends the command it was given, even if the caller changes its array afterwards", async () => { + const reads = capture("cable-reads.json"); + const { device, sent } = fakeDevice({ ids: WIRED, replies: { + [CMD.GET_DPI]: [...Buffer.from(reads.replies.dpi, "hex")], + } }); + const client = new AngryMiaoHidClient(device); + const busy = client.command([CMD.GET_DPI]); + const request = [0x85]; + const queued = client.command(request); + request[0] = CMD.GET_USB_VERSION; + await Promise.all([busy, queued]); + assert.deepEqual(sent.map((report) => report[0]), [CMD.GET_DPI, 0x85]); + }); + + it("retries an unanswered relayed command three times, then releases the receiver", async () => { + const { device, sent } = fakeDevice({ ids: RECEIVER }); + await assert.rejects(new AngryMiaoHidClient(device).command([0xd6]), /not answered/); + assert.equal(sent.filter((report) => report[0] === 0xd6).length, 3); + assert.deepEqual([...sent.at(-1)!.subarray(0, 2)], [0xf6, 0x00], "F6 00 after the last try"); + }); + + it("releases the receiver when a relayed write fails to send, and does not retry it", async () => { + const dongle = capture("dongle-reads.json"); + const bytes = (hex: string) => [...Buffer.from(hex, "hex")]; + const { device, sent } = fakeDevice({ ids: RECEIVER, replies: { + [CMD.GET_OPTIONPARAM0]: bytes(dongle.relayed.option0), + [CMD.GET_DPI]: bytes(dongle.relayed.dpi), + } }); + const client = new AngryMiaoHidClient(device); + await client.readStatus(); + const fake = device as unknown as { sendFeatureReport: (id: number, data: Uint8Array) => Promise }; + const send = fake.sendFeatureReport; + let attempts = 0; + fake.sendFeatureReport = async (id, data) => { + if (data[0] === CMD.SET_OPTIONPARAM0) { + attempts++; + throw new Error("USB transfer failed"); + } + return send(id, data); + }; + await assert.rejects(client.setMotionSync(true), /USB transfer failed/); + assert.equal(attempts, 1); + assert.deepEqual([...sent.at(-1)!.subarray(0, 2)], [0xf6, 0x00]); + }); + + it("retries only the receiver versions that did not answer", async () => { + const dongle = capture("dongle-reads.json"); + const bytes = (hex: string) => [...Buffer.from(hex, "hex")]; + // The RF read first answers zeros, which the driver treats as unanswered. + const receiverReplies: Record = { + 0xf0: [0xf0, 0x08, 0x00], + 0xfb: [], + 0xae: [0xae, 0x09, 0x01], + }; + const { device, sent } = fakeDevice({ ids: RECEIVER, receiverReplies, replies: { + [CMD.GET_OPTIONPARAM0]: bytes(dongle.relayed.option0), + [CMD.GET_DPI]: bytes(dongle.relayed.dpi), + } }); + const client = new AngryMiaoHidClient(device); + const receiverLabels = (firmware: string[]) => firmware.filter((label) => label.startsWith("Receiver")); + assert.deepEqual(receiverLabels((await client.readStatus()).firmware), ["Receiver USB 0x0008", "Receiver LED 0x0109"]); + + receiverReplies[0xfb] = [0xdf, 0, 0, 0xf0]; + const before = sent.length; + assert.deepEqual( + receiverLabels((await client.readStatus()).firmware), + ["Receiver USB 0x0008", "Receiver RF 0xf0", "Receiver LED 0x0109"], + ); + const heads = sent.slice(before).map((report) => report[0]); + assert.deepEqual([heads.includes(0xf0), heads.includes(0xfb), heads.includes(0xae)], [false, true, false]); + }); + + it("reports the receiver and the mouse apart on 2.4 GHz", async () => { + const dongle = capture("dongle-reads.json"); + const bytes = (hex: string) => [...Buffer.from(hex, "hex")]; + // Receiver versions from the dongle capture: USB 1.0.7, RF 1.0.8, LED 1.0.5 in the vendor app. + const receiverReplies = { + 0xf0: [0xf0, 0x08, 0x00], + 0xfb: [0xdf, 0, 0, 0xf0], + 0xae: [0xae, 0x09, 0x01], + }; + const replies = { + [CMD.GET_OPTIONPARAM0]: bytes(dongle.relayed.option0), + [CMD.GET_DPI]: bytes(dongle.relayed.dpi), + [CMD.GET_FIRMWARE]: [CMD.GET_FIRMWARE, 0x18, 0x03], + }; + const { device, sent } = fakeDevice({ ids: RECEIVER, receiverReplies, replies }); + const client = new AngryMiaoHidClient(device); + const status = await client.readStatus(); + assert.deepEqual(status.firmware, [ + "Mouse SoC 0x0318", "Receiver USB 0x0008", "Receiver RF 0xf0", "Receiver LED 0x0109", "PixArt PAW3950", + ]); + assert.equal(sent.some((report) => report[0] === AM30_GET_USB_VERSION), false, "AD is a cable read"); + const before = sent.length; + await client.readStatus(); + assert.equal(sent.slice(before).some((report) => report[0] === 0xf0), false, "receiver versions are read once"); + + // F7 byte 4 = 1: the mouse is asleep, off, or on another link; byte 10 is a spare at 90 %. + const offline = fakeDevice({ ids: RECEIVER, receiverReplies, replies, status: [0, 0, 0, 1, 1, 1, 2, 0, 0, 1, 0x5a] }); + const alone = await new AngryMiaoHidClient(offline.device).readStatus(); + assert.equal(alone.ui?.settingsReady, false); + assert.equal(alone.ui?.receiverOnly, true); + assert.equal(alone.name, "Angry Miao Receiver"); + assert.equal(alone.ui?.defaultDisplayName, "Angry Miao Receiver"); + assert.equal(alone.connectionType, "Wireless"); + assert.deepEqual(alone.firmware, ["Receiver USB 0x0008", "Receiver RF 0xf0", "Receiver LED 0x0109"]); + assert.deepEqual(alone.spareBattery, { percent: 90, state: "Charging" }); + assert.equal(offline.sent.some((report) => report[0] === 0xf6), false, "nothing is relayed to an absent mouse"); + }); +}); diff --git a/src/drivers/angry-miao/hid.ts b/src/drivers/angry-miao/hid.ts new file mode 100644 index 00000000..0e09b713 --- /dev/null +++ b/src/drivers/angry-miao/hid.ts @@ -0,0 +1,1010 @@ +import type { MouseLighting, MouseLightingMode, MouseStatus } from "../mouse-types.ts"; +import { + AM30_BUTTON_ACTIONS, + AM30_CMD, + AM30_DPI_RGB_OFFSET, + AM30_DPI_X_OFFSET, + AM30_DPI_Y_OFFSET, + AM30_LIFT_OFF_LEVELS, + AM30_MAX_DPI_STAGES, + AM30_OPT0_ANGLE_SNAP, + AM30_OPT0_DEBOUNCE, + AM30_OPT0_FLAGS, + AM30_OPT0_LIFT_OFF, + AM30_OPT0_REPORT_RATE, + AM30_OPT0_SLEEP_24G, + AM30_RATE_DECODE, + AM30_RATE_ENCODE, + AM30_RATES, + AM30_RELAY, + AM30_RELAY_ATTEMPTS, + AM30_RELAY_LENGTH, + AM30_REPORT_ID, + AM30_REPORT_SIZE, + AM30_TARGET_MOUSE, + AM30_TARGET_NONE, + AM30_BT_BATTERY, + AM30_BT_ENVELOPE, + AM30_BT_REPORT_ID, + AM30_BT_REPORT_SIZE, + AM30_BT_SLEEPING, + AM30_OPT0_SLEEP_BT, + am30BluetoothPacket, + ANGRY_MIAO_PRODUCT_NAME, + am30EncodeCommand, + ANGRY_MIAO_VENDOR_ID, + type Am30LiftOff, + type AngryMiaoProfile, + type AngryMiaoTransport, + AM30_DEBOUNCE_GEARS_MS, + AM30_DEFAULT_BUTTON_MAPPINGS, + AM30_GET_BATTERY, + AM30_GET_BLAST_MODE, + AM30_GET_PROFILE, + AM30_GET_USB_VERSION, + AM30_OPT0_DEBOUNCE_24G, + AM30_OPT0_DEBOUNCE_BT, + AM30_OPT0_FLAG_RIPPLE, + AM30_OPT0_LIGHT, + AM30_OPT0_LIGHT_COLOR, + AM30_OPT0_LIGHT_COLOR_2, + AM30_OPT0_MOTION_SYNC, + AM30_PROFILE_COUNT, + AM30_RECEIVER_BRIGHTNESS, + AM30_RECEIVER_GET_LED_VERSION, + AM30_RECEIVER_GET_LIGHT, + AM30_RECEIVER_GET_LIGHT_SWITCH, + AM30_RECEIVER_GET_RF_VERSION, + AM30_RECEIVER_GET_USB_VERSION, + AM30_RECEIVER_SET_LIGHT_SWITCH, + AM30_RECEIVER_SPEEDS, + AM30_SET_BLAST_MODE, + AM30_SET_PROFILE, + AM30_SLEEP_NEVER, + AM30_SLEEP_OPTIONS, + AM30_STATUS_MOUSE_OFFLINE, + am30DebounceGear, + am30DebounceRaw, + am30DecodeBattery, + am30DecodeButtonAction, + am30DecodeReceiverLight, + am30DecodeSpareBattery, + am30EncodeButtonAction, + am30EncodeReceiverLight, + am30FirmwareLabels, + am30ReceiverFirmwareLabels, + ANGRY_MIAO_INFINITY_PROFILE, + ANGRY_MIAO_PRODUCTS, + ANGRY_MIAO_PROFILES, +} from "@openmouse/protocol/angry-miao"; + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +interface Am30DpiStage { + x: number; + y: number; + rgb: number; +} + +/** Receiver light effects 1..8 in the vendor's order (always on, breathing, neon, light wave, ...). */ +const RECEIVER_EFFECTS: readonly MouseLightingMode[] = [ + "Static", "Breathing single", "Neon", "Wave", "Marquee", "Ring", "Buffer", "Chase", +]; + +/** + * Angry Miao Infinity .100 (AM30) on the Yichip protocol. This client owns its + * whole stack: feature-report I/O, the receiver relay, the settings layout + * (`@openmouse/protocol/angry-miao`), the battery, motion sync, Blast Mode and + * both lights. Nothing is inherited from the other Yichip brands' driver. + */ +export class AngryMiaoHidClient { + device: HIDDevice; + currentProfile = 0; + + private readonly transportEntry: AngryMiaoTransport | undefined; + /** False until `85` answers, so button mappings never go to a guessed profile. */ + private profileConfirmed = false; + /** The model for the last `8F` device id, or null when it is not one we know. */ + private resolvedProfile: AngryMiaoProfile | null = null; + /** The relay is stateful, so exchanges run one at a time. */ + private queue: Promise = Promise.resolve(); + /** Setting changes and status reads, one whole step at a time (see `exclusive`). */ + private settingsQueue: Promise = Promise.resolve(); + /** Last Blast Mode write; on SoC firmware 1.1.1 `E2` does not reflect it. */ + private blastMode: boolean | null = null; + /** `80` reply from the last status read. */ + private firmwareCode: number | null = null; + /** Receiver version replies, kept once each answers, so a later status read retries only the missing ones. */ + private receiverFirmware: { usb: Uint8Array | null; rf: Uint8Array | null; led: Uint8Array | null } = { + usb: null, rf: null, led: null, + }; + /** `8F` device id from the last status read; writes need a known one. */ + private deviceId: number | null = null; + + constructor(device: HIDDevice) { + this.device = device; + this.transportEntry = ANGRY_MIAO_PRODUCTS.get(device.productId); + } + + static isSupported(device: HIDDevice): boolean { + const entry = ANGRY_MIAO_PRODUCTS.get(device.productId); + if (device.vendorId !== ANGRY_MIAO_VENDOR_ID || !entry) return false; + // Other brands reuse these product ids, so the name has to be Angry Miao's too. + if (!ANGRY_MIAO_PRODUCT_NAME.test(device.productName ?? "")) return false; + const hasControl = (collections: readonly HIDCollectionInfo[]): boolean => + collections.some((c) => (c.usagePage === entry.usagePage && c.usage === entry.usage) || hasControl(c.children ?? [])); + return hasControl(device.collections); + } + + get transport(): "dongle" | "direct" | "bluetooth" { + return this.transportEntry?.transport ?? "direct"; + } + + private get profile(): AngryMiaoProfile { + return this.resolvedProfile ?? ANGRY_MIAO_INFINITY_PROFILE; + } + + get supportedPollingRates(): number[] { + return AM30_RATES.filter((hz) => hz <= this.profile.maxPollingHz); + } + + /** Every writable DPI step; the app validates typed stage values against it. */ + getDpiOptions(): number[] { + const { minDpi, maxDpi, dpiStep } = this.profile; + return Array.from({ length: Math.floor((maxDpi - minDpi) / dpiStep) + 1 }, (_, i) => minDpi + i * dpiStep); + } + + async open(): Promise { + if (!this.device.opened) await this.device.open(); + } + + async close(): Promise { + if (this.device.opened) await this.device.close(); + } + + // ── Feature-report I/O and the receiver relay ───────────────────────────── + + private enqueue(task: () => Promise): Promise { + const run = this.queue.then(task, task); + this.queue = run.catch(() => undefined); + return run; + } + + /** + * Runs a whole setting change or status read before the next one starts, as the 8BitDo driver does. + * Reads, edits and writes inside it still go through `enqueue` one report at a time. Nothing else can + * change the device id or the profile mid-step, so a step checks them once, at its start. + */ + private exclusive(operation: () => Promise): Promise { + const run = this.settingsQueue.then(operation, operation); + this.settingsQueue = run.catch(() => undefined); + return run; + } + + private async rawSend(bytes: readonly number[] | Uint8Array): Promise { + const buf = new Uint8Array(AM30_REPORT_SIZE); + buf.set(bytes instanceof Uint8Array ? bytes.subarray(0, AM30_REPORT_SIZE) : bytes.slice(0, AM30_REPORT_SIZE)); + await this.device.sendFeatureReport(AM30_REPORT_ID, buf); + } + + private async rawRead(): Promise { + const view = await this.device.receiveFeatureReport(AM30_REPORT_ID); + return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)); + } + + /** `F7`: byte 0 = 1 when a reply is ready, byte 5 = 1 when the receiver takes a command. */ + private async pollStatus(): Promise { + await this.rawSend([AM30_RELAY.GET_STATUS]); + await delay(10); + return this.rawRead(); + } + + private async waitReady(byte: 0 | 5): Promise { + for (let attempt = 0; attempt < 8; attempt++) { + await delay(100); + if ((await this.pollStatus())[byte] === 1) return true; + } + return false; + } + + /** The vendor app selects the mouse and sends `FE 40` before every relayed command. */ + private async prepareRelay(): Promise { + await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_MOUSE]); + await delay(50); + if (!(await this.waitReady(5))) throw new Error("The 2.4 GHz receiver never became ready to send."); + await this.rawSend([AM30_RELAY.SET_LENGTH, AM30_RELAY_LENGTH]); + await delay(10); + } + + /** A reply of 64 zeros means the command was not answered; most replies echo the command id. */ + private verifyReply(resp: Uint8Array, cmd: number, echoes: boolean): Uint8Array { + const id = `0x${cmd.toString(16)}`; + if (resp.length < AM30_REPORT_SIZE) throw new Error(`Command ${id} returned ${resp.length} bytes, expected ${AM30_REPORT_SIZE}.`); + if (resp.every((byte) => byte === 0)) throw new Error(`Command ${id} was not answered (all-zero response).`); + if (echoes && resp[0] !== cmd) throw new Error(`Command ${id} answered with id 0x${resp[0].toString(16)}.`); + return resp; + } + + /** Retries a relayed exchange, then sends `F6 00` so a failed relay does not leave the receiver stuck. */ + private async relay(exchange: () => Promise): Promise { + let failure: unknown; + for (let attempt = 0; attempt < AM30_RELAY_ATTEMPTS; attempt++) { + if (attempt > 0) await delay(100); + try { + return await exchange(); + } catch (error) { + failure = error; + } + } + await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_NONE]).catch(() => undefined); + throw failure; + } + + /** One mouse command and its reply, relayed on 2.4 GHz. */ + async command(bytes: readonly number[], opts: { echoes?: boolean } = {}): Promise { + // Copied now, so a caller that reuses its array cannot change a command still waiting in the queue. + const request = [...bytes]; + const echoes = opts.echoes ?? true; + return this.enqueue(() => this.exchange(request, echoes)); + } + + /** The body of `command`. Call it only from a task that already holds the queue. */ + private async exchange(bytes: readonly number[], echoes: boolean): Promise { + const encoded = am30EncodeCommand(bytes); + await this.open(); + if (this.transport === "bluetooth") return this.exchangeBluetooth(encoded, bytes[0], echoes); + if (this.transport === "direct") { + await this.rawSend(encoded); + await delay(10); + return this.verifyReply(await this.rawRead(), bytes[0], echoes); + } + return this.relay(async () => { + await this.prepareRelay(); + await this.rawSend(encoded); + if (!(await this.waitReady(0))) throw new Error("The 2.4 GHz receiver never became ready to read."); + await this.rawSend([AM30_RELAY.NOTICE_READ]); + await delay(10); + return this.verifyReply(await this.rawRead(), bytes[0], echoes); + }); + } + + /** Product ids and names are shared, so only a device id we have tested may be written to. */ + private async sendWrite(cmd: Uint8Array): Promise { + this.assertModelVerified(); + return this.enqueue(() => this.transmit(cmd)); + } + + /** The body of `sendWrite`. Call it only from a task that already holds the queue. */ + private async transmit(cmd: Uint8Array): Promise { + const encoded = am30EncodeCommand([...cmd]); + await this.open(); + if (this.transport === "bluetooth") { + await this.device.sendReport(AM30_BT_REPORT_ID, am30BluetoothPacket(encoded)); + await delay(60); + return; + } + if (this.transport === "direct") { + await this.rawSend(encoded); + await delay(10); + return; + } + // A retry only happens before the write is sent: `prepareRelay` is the step that can fail. + await this.relay(() => this.prepareRelay()); + try { + await this.rawSend(encoded); + } catch (error) { + // No retry, because the receiver may already hold the write. Release it so it does not stay on the mouse. + await this.rawSend([AM30_RELAY.SELECT_TARGET, AM30_TARGET_NONE]).catch(() => undefined); + throw error; + } + await delay(50); + } + + private assertModelVerified(): void { + if (!this.modelVerified) { + throw new Error(`Device id ${this.deviceId ?? "unknown"} is not a verified Angry Miao model; settings are read-only.`); + } + } + + private get modelVerified(): boolean { + return this.deviceId !== null && ANGRY_MIAO_PROFILES.has(this.deviceId); + } + + /** Bluetooth replies arrive as input report 6; null from `decode` skips an unrelated report. */ + private requestBluetooth(request: Uint8Array, decode: (packet: Uint8Array) => T | null): Promise { + return new Promise((resolve, reject) => { + const cleanup = () => { + clearTimeout(timer); + this.device.removeEventListener("inputreport", onReport); + }; + const onReport = (event: HIDInputReportEvent) => { + if (event.reportId !== AM30_BT_REPORT_ID) return; + const packet = new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength); + if (packet.length !== AM30_BT_REPORT_SIZE) return; + try { + const result = decode(packet); + if (result === null) return; + cleanup(); + resolve(result); + } catch (error) { + cleanup(); + reject(error); + } + }; + const timer = setTimeout(() => { + cleanup(); + reject(new Error("The mouse did not answer over Bluetooth. Move it and try again.")); + }, 2000); + this.device.addEventListener("inputreport", onReport); + this.device.sendReport(AM30_BT_REPORT_ID, request).catch((error) => { + cleanup(); + reject(error); + }); + }); + } + + private exchangeBluetooth(encoded: Uint8Array, cmd: number, echoes: boolean): Promise { + return this.requestBluetooth(am30BluetoothPacket(encoded), (packet) => { + if (packet[0] !== AM30_BT_ENVELOPE) return null; + const reply = packet.slice(1); + if (echoes && reply[0] !== cmd) return null; + return this.verifyReply(reply, cmd, echoes); + }); + } + + /** `77`: battery percent in byte 1. The mouse answers `88` while asleep. */ + private bluetoothBattery(): Promise { + return this.enqueue(async () => { + await this.open(); + const request = new Uint8Array(AM30_BT_REPORT_SIZE); + request[0] = AM30_BT_BATTERY; + return this.requestBluetooth(request, (packet) => { + if (packet[0] === AM30_BT_SLEEPING) throw new Error("The mouse is asleep."); + if (packet[0] !== AM30_BT_BATTERY) return null; + if (packet[1] > 100) throw new Error("The mouse returned an invalid battery percentage."); + return packet[1]; + }); + }); + } + + // ── Reads ───────────────────────────────────────────────────────────────── + + /** `8F` bytes 1-4, LE32. */ + async getDeviceId(): Promise { + const resp = await this.command([AM30_CMD.GET_DEVICE_ID]); + return (resp[1] | (resp[2] << 8) | (resp[3] << 16) | (resp[4] << 24)) >>> 0; + } + + async getFirmwareVersion(): Promise { + const resp = await this.command([AM30_CMD.GET_FIRMWARE]); + this.firmwareCode = (resp[2] << 8) | resp[1]; + return this.firmwareCode; + } + + async getOptionParam0(): Promise { + return this.command([AM30_CMD.GET_OPTIONS]); + } + + async getReportRate(): Promise { + const code = (await this.getOptionParam0())[AM30_OPT0_REPORT_RATE]; + const hz = AM30_RATE_DECODE[code]; + if (hz === undefined) throw new Error(`Unknown report-rate code ${code}.`); + return hz; + } + + /** 14 slots x 4 bytes with no echo byte. Read late in a status read, so it retries once. */ + async getKeyMatrix(profile = 0): Promise { + const read = async () => { + const reply = await this.command([AM30_CMD.GET_KEYMATRIX, profile], { echoes: false }); + // A lost relay reply can leave an echoed command buffered; actions never start at 0x80 or above. + if (reply[0] >= 0x80) throw new Error("The mouse returned a stale command instead of button mappings."); + return reply; + }; + try { + return await read(); + } catch { + return await read(); + } + } + + /** + * Read-modify-write of the whole options block; bytes not overridden are written back as read. + * The read and the write run as one exclusive step, so another change cannot land between them. + */ + private patchOptionParam0( + overrides: Record number)>, + ): Promise { + return this.exclusive(() => this.patchOptions(overrides)); + } + + /** The body of `patchOptionParam0`. Call it only from inside `exclusive`. */ + private async patchOptions( + overrides: Record number)>, + ): Promise { + this.assertModelVerified(); + const current = await this.getOptionParam0(); + const block = new Uint8Array(AM30_REPORT_SIZE); + block.set(current.subarray(8, AM30_REPORT_SIZE), 8); + block[0] = AM30_CMD.SET_OPTIONS; + for (const [offset, value] of Object.entries(overrides)) { + const i = Number(offset); + block[i] = (typeof value === "function" ? value(current[i], current) : value) & 0xff; + } + await this.sendWrite(block); + // Read the block back, as the maintainer asked: the mouse reports every byte this setter changed. + const kept = await this.getOptionParam0(); + const lost = Object.keys(overrides).map(Number).find((i) => kept[i] !== block[i]); + if (lost !== undefined) { + throw new Error(`The mouse did not keep the change: options byte ${lost} reads ${kept[lost]}, not ${block[lost]}.`); + } + } + + // ── Settings ────────────────────────────────────────────────────────────── + + private buttonSlots() { + return this.profile.buttons; + } + + /** Active onboard profile, 0-based, or null when `85` is not answered. */ + private async readProfile(): Promise { + const active = (await this.command([AM30_GET_PROFILE]))[1]; + return active < AM30_PROFILE_COUNT ? active : null; + } + + /** 1-based. The vendor app confirms with `85`, then always turns Blast Mode off. */ + setProfile(profile: number): Promise { + return this.exclusive(() => this.switchProfile(profile)); + } + + private async switchProfile(profile: number): Promise { + if (!Number.isInteger(profile) || profile < 1 || profile > AM30_PROFILE_COUNT) { + throw new Error(`The Angry Miao Infinity .100 has onboard profiles 1 to ${AM30_PROFILE_COUNT}.`); + } + // Unknown from here on: the mouse may switch even if the send or every confirmation fails. + this.profileConfirmed = false; + await this.sendWrite(Uint8Array.from([AM30_SET_PROFILE, profile - 1, AM30_PROFILE_COUNT])); + let active: number | null = null; + for (let attempt = 0; attempt < 3 && active !== profile - 1; attempt++) { + if (attempt > 0) await delay(100); + // One unanswered read does not mean the switch failed, so the remaining attempts still run. + try { active = await this.readProfile(); } catch { active = null; } + } + if (active !== profile - 1) { + this.profileConfirmed = active !== null; + if (active !== null) this.currentProfile = active; + throw new Error(active === null + ? `The mouse did not confirm the switch to profile ${profile}. Read the status again.` + : `The mouse stayed on profile ${active + 1}.`); + } + this.currentProfile = active; + this.profileConfirmed = true; + await this.writeBlastMode(false); + return profile; + } + + /** `50` and `D0` name a profile, so the mappings stay read-only until `85` confirms the active one. */ + private confirmedProfile(): number { + if (!this.profileConfirmed) { + throw new Error("The active profile is unknown, so button mappings are read-only. Read the status again."); + } + return this.currentProfile; + } + + getButtonOptions(): string[] { + return AM30_BUTTON_ACTIONS.map(([label]) => label); + } + + /** The vendor app locks Left to Left Click so the mouse always keeps a primary click. */ + setButtonMapping(button: string, action: string): Promise { + return this.exclusive(() => this.writeButton(this.confirmedProfile(), button, action)); + } + + private async writeButton(profile: number, button: string, action: string): Promise { + const target = this.buttonSlots().find((b) => b.name === button); + if (!target) throw new Error(`Unknown button "${button}".`); + const value = am30EncodeButtonAction(button === "Left" ? "Left Click" : action); + if (!value) throw new Error(`Unsupported button action "${action}".`); + const cmd = new Uint8Array(AM30_REPORT_SIZE); + cmd.set([AM30_CMD.SET_KEYMATRIX, profile, target.slot]); + cmd.set(value, 8); + await this.sendWrite(cmd); + } + + /** Rewrites each button that differs from its factory action, as the vendor's restore does. */ + resetButtonMappings(): Promise { + return this.exclusive(async () => { + // The comparison and every write use the one profile read here. + const profile = this.confirmedProfile(); + const matrix = await this.getKeyMatrix(profile); + for (const { name, slot } of this.buttonSlots()) { + const action = AM30_DEFAULT_BUTTON_MAPPINGS[name]; + if (am30DecodeButtonAction(matrix.subarray(slot * 4, slot * 4 + 4)) !== action) { + await this.writeButton(profile, name, action); + } + } + }); + } + + /** All eight stage slots; stages past the count keep their values for when it grows again. */ + async getDpi(): Promise<{ stages: Am30DpiStage[]; activeIndex: number; count: number }> { + // No profile byte: `D4` answers for the active profile, as the vendor app reads it. + const resp = await this.command([AM30_CMD.GET_DPI]); + const count = Math.min(resp[3], AM30_MAX_DPI_STAGES); + if (count === 0) throw new Error("The Angry Miao Infinity .100 reported no DPI stages."); + const stages: Am30DpiStage[] = []; + for (let i = 0; i < AM30_MAX_DPI_STAGES; i++) { + const rgb = AM30_DPI_RGB_OFFSET + i * 3; + stages.push({ + x: resp[AM30_DPI_X_OFFSET + i * 2] | (resp[AM30_DPI_X_OFFSET + 1 + i * 2] << 8), + y: resp[AM30_DPI_Y_OFFSET + i * 2] | (resp[AM30_DPI_Y_OFFSET + 1 + i * 2] << 8), + rgb: (resp[rgb] << 16) | (resp[rgb + 1] << 8) | resp[rgb + 2], + }); + } + return { stages, activeIndex: Math.min(resp[2], count - 1), count }; + } + + /** `54`: the whole eight-stage table with the active stage and the count. */ + private async writeStageTable(stages: Am30DpiStage[], active: number, count: number): Promise { + const cmd = new Uint8Array(AM30_REPORT_SIZE); + cmd.set([AM30_CMD.SET_DPI, 0, active, count]); + stages.forEach((stage, i) => { + cmd.set([stage.x & 0xff, stage.x >> 8], AM30_DPI_X_OFFSET + i * 2); + cmd.set([stage.y & 0xff, stage.y >> 8], AM30_DPI_Y_OFFSET + i * 2); + cmd.set([(stage.rgb >> 16) & 0xff, (stage.rgb >> 8) & 0xff, stage.rgb & 0xff], AM30_DPI_RGB_OFFSET + i * 3); + }); + await this.sendWrite(cmd); + } + + setDpiForStage(x: number, y: number, index: number): Promise { + return this.exclusive(() => this.writeStageDpi(x, y, index)); + } + + /** Reads the table, edits one stage and writes it back; out-of-range `index` means the active stage. */ + private async writeStageDpi(x: number, y: number, index: number): Promise { + const { minDpi, maxDpi, dpiStep } = this.profile; + if (![x, y].every((v) => Number.isInteger(v) && v >= minDpi && v <= maxDpi && (v - minDpi) % dpiStep === 0)) { + throw new Error(`DPI must be ${minDpi}..${maxDpi} in ${dpiStep} DPI steps.`); + } + const { stages, activeIndex, count } = await this.getDpi(); + const target = index >= 0 && index < count ? index : activeIndex; + stages[target] = { ...stages[target], x, y }; + await this.writeStageTable(stages, activeIndex, count); + return x; + } + + /** The stage editor's shared entry point; one value sets both axes. */ + setDpiStageValue(stage: number, dpi: number): Promise { + return this.exclusive(() => this.writeStageDpi(dpi, dpi, stage)); + } + + async setDpi(dpi: number, dpiY = dpi): Promise { + // An out-of-range stage targets the active stage of the table `writeStageDpi` reads, so `D4` runs once. + await this.exclusive(() => this.writeStageDpi(dpi, dpiY, -1)); + return dpi; + } + + setDpiStageColor(index: number, color: string): Promise { + return this.exclusive(async () => { + const match = /^#?([0-9a-f]{6})$/i.exec(color); + if (!match) throw new Error(`Invalid DPI stage colour "${color}".`); + const rgb = parseInt(match[1], 16); + const { stages, activeIndex, count } = await this.getDpi(); + const target = index >= 0 && index < count ? index : activeIndex; + stages[target] = { ...stages[target], rgb }; + await this.writeStageTable(stages, activeIndex, count); + return `#${match[1].toLowerCase()}`; + }); + } + + setActiveDpiStage(index: number): Promise { + return this.exclusive(async () => { + const { stages, count } = await this.getDpi(); + const target = Math.max(0, Math.min(index, count - 1)); + await this.writeStageTable(stages, target, count); + return target; + }); + } + + /** The DPI button cycles through the first `count` stages; the active stage clamps to the last. */ + setDpiStageCount(count: number): Promise { + return this.exclusive(async () => { + if (!Number.isInteger(count) || count < 1 || count > AM30_MAX_DPI_STAGES) { + throw new Error(`The Angry Miao Infinity .100 holds 1 to ${AM30_MAX_DPI_STAGES} DPI stages.`); + } + const { stages, activeIndex } = await this.getDpi(); + // The vendor app fills a slot it does not hold with 800 DPI, red. + const filled = stages.map((stage) => (stage.x === 0 ? { x: 800, y: 800, rgb: 0xff0000 } : stage)); + await this.writeStageTable(filled, Math.min(activeIndex, count - 1), count); + return count; + }); + } + + async setReportRate(hz: number): Promise { + const code = AM30_RATE_ENCODE[hz]; + if (code === undefined || !this.supportedPollingRates.includes(hz)) { + throw new Error(`Unsupported rate ${hz} Hz. Supported: ${this.supportedPollingRates.join(", ")}`); + } + // Keep the debounce stop, as the vendor app does: its raw bytes are per rate. + const raw = (block: Uint8Array) => am30DebounceRaw( + hz, + am30DebounceGear(AM30_RATE_DECODE[block[AM30_OPT0_REPORT_RATE]], block[AM30_OPT0_DEBOUNCE]), + ); + await this.patchOptionParam0({ + [AM30_OPT0_REPORT_RATE]: code, + [AM30_OPT0_DEBOUNCE]: (_, block) => raw(block).usb, + [AM30_OPT0_DEBOUNCE_24G]: (_, block) => raw(block).rf, + [AM30_OPT0_DEBOUNCE_BT]: (_, block) => raw(block).bt, + }); + return hz; + } + + async setPollingRate(rate: number): Promise { + return this.setReportRate(rate); + } + + async setLiftOffDistance(level: Am30LiftOff): Promise { + const index = AM30_LIFT_OFF_LEVELS.indexOf(level); + if (index < 0) throw new Error(`Lift-off level "${level}" is not available on this model.`); + await this.patchOptionParam0({ [AM30_OPT0_LIFT_OFF]: index }); + return level; + } + + async setAngleSnapping(enabled: boolean): Promise { + await this.patchOptionParam0({ [AM30_OPT0_ANGLE_SNAP]: enabled ? 1 : 0 }); + return enabled; + } + + getDebounceMaxMs(): number { + return Math.max(...AM30_DEBOUNCE_GEARS_MS); + } + + getDebounceOptions(): number[] { + return [...AM30_DEBOUNCE_GEARS_MS].sort((a, b) => a - b); + } + + /** One slider sets all three links, as in the vendor app. */ + async setDebounceTime(ms: number): Promise { + const distance = AM30_DEBOUNCE_GEARS_MS.map((label) => Math.abs(label - ms)); + const gear = distance.indexOf(Math.min(...distance)); + const raw = (block: Uint8Array) => am30DebounceRaw(AM30_RATE_DECODE[block[AM30_OPT0_REPORT_RATE]], gear); + await this.patchOptionParam0({ + [AM30_OPT0_DEBOUNCE]: (_, block) => raw(block).usb, + [AM30_OPT0_DEBOUNCE_24G]: (_, block) => raw(block).rf, + [AM30_OPT0_DEBOUNCE_BT]: (_, block) => raw(block).bt, + }); + return AM30_DEBOUNCE_GEARS_MS[gear]; + } + + getSleepOptions(): number[] { + return [...AM30_SLEEP_OPTIONS]; + } + + /** The vendor app edits each link's timer on its own, so only the current link's is written. */ + async setSleepTimeout(seconds: number): Promise { + const s = Math.max(0, Math.min(0xffff, Math.round(seconds))); + const raw = s === 0 ? AM30_SLEEP_NEVER : s; + const offset = this.sleepOffset; + await this.patchOptionParam0({ [offset]: raw & 0xff, [offset + 1]: (raw >> 8) & 0xff }); + return s; + } + + private get sleepOffset(): number { + return this.transport === "bluetooth" ? AM30_OPT0_SLEEP_BT : AM30_OPT0_SLEEP_24G; + } + + async setRippleControl(enabled: boolean): Promise { + await this.patchOptionParam0({ + [AM30_OPT0_FLAGS]: (current) => enabled ? current | AM30_OPT0_FLAG_RIPPLE : current & ~AM30_OPT0_FLAG_RIPPLE, + }); + return enabled; + } + + async setMotionSync(enabled: boolean): Promise { + await this.patchOptionParam0({ [AM30_OPT0_MOTION_SYNC]: enabled ? 1 : 0 }); + return enabled; + } + + /** Angry Miao's "Blast Mode". */ + setTurboMode(enabled: boolean): Promise { + return this.exclusive(() => this.writeBlastMode(enabled)); + } + + private async writeBlastMode(enabled: boolean): Promise { + await this.sendWrite(Uint8Array.from([AM30_SET_BLAST_MODE, enabled ? 1 : 0])); + this.blastMode = enabled; + return enabled; + } + + private mouseLight(opt0: Uint8Array): MouseLighting { + const rgb = opt0.subarray(AM30_OPT0_LIGHT_COLOR, AM30_OPT0_LIGHT_COLOR + 3); + return { + zone: "Mouse", + modes: ["Off", "Static"], + mode: opt0[AM30_OPT0_LIGHT] ? "Static" : "Off", + color: `#${Array.from(rgb, (b) => b.toString(16).padStart(2, "0")).join("")}`, + color2: null, + colorModes: ["Static"], + dualColorModes: [], + reactiveModes: [], + speeds: [], + speed: null, + }; + } + + /** The vendor's mouse light panel writes its one colour into both RGB slots. */ + setLighting( + lighting: Pick & Partial>, + ): Promise { + return this.exclusive(() => this.writeLighting(lighting)); + } + + private async writeLighting( + lighting: Pick & Partial>, + ): Promise { + if (lighting.zone === "Receiver") return this.setReceiverLight(lighting); + if (lighting.mode !== "Off" && lighting.mode !== "Static") { + throw new Error(`Unsupported lighting mode: ${lighting.mode}.`); + } + const overrides: Record = { [AM30_OPT0_LIGHT]: lighting.mode === "Static" ? 1 : 0 }; + if (lighting.mode === "Static" && lighting.color) { + const match = /^#?([0-9a-f]{6})$/i.exec(lighting.color); + if (!match) throw new Error(`Invalid lighting colour: ${lighting.color}.`); + const value = parseInt(match[1], 16); + [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff].forEach((byte, i) => { + overrides[AM30_OPT0_LIGHT_COLOR + i] = byte; + overrides[AM30_OPT0_LIGHT_COLOR_2 + i] = byte; + }); + } + await this.patchOptions(overrides); + return this.mouseLight(await this.getOptionParam0()); + } + + /** Commands for the receiver itself: straight to it, never relayed to the mouse. */ + private receiverCommand(packet: Uint8Array, expectReply: boolean, echoes = true): Promise { + return this.enqueue(async () => { + await this.open(); + await this.rawSend(packet); + await delay(10); + return expectReply ? this.verifyReply(await this.rawRead(), packet[0], echoes) : null; + }); + } + + /** Raw `F7` status reply, which carries no checksum and no echo byte. */ + private readReceiverStatus(): Promise { + return this.enqueue(async () => { + await this.open(); + await this.rawSend([AM30_RELAY.GET_STATUS]); + await delay(10); + return this.rawRead(); + }); + } + + /** The vendor app's order: USB, a 500 ms pause, RF, LED. */ + private async readReceiverFirmware(): Promise { + const known = this.receiverFirmware; + const read = async (command: number, echoes = true) => { + try { return await this.receiverCommand(am30EncodeCommand([command]), true, echoes); } catch { return null; } + }; + // A failed read never replaces a version that is already known. + if (!known.usb) { + known.usb = await read(AM30_RECEIVER_GET_USB_VERSION) ?? known.usb; + if (!known.rf) await delay(500); + } + if (!known.rf) known.rf = await read(AM30_RECEIVER_GET_RF_VERSION, false) ?? known.rf; + if (!known.led) known.led = await read(AM30_RECEIVER_GET_LED_VERSION) ?? known.led; + return am30ReceiverFirmwareLabels(known.usb, known.rf, known.led); + } + + /** The receiver answers on its own while the mouse sleeps, is off, or is on another link. */ + private async receiverOnlyStatus(receiverStatus: Uint8Array): Promise { + let receiverLight: MouseLighting | undefined; + try { receiverLight = await this.readReceiverLight(); } catch { /* Optional: the zone stays hidden. */ } + const firmware = await this.readReceiverFirmware(); + const spareBattery = am30DecodeSpareBattery(receiverStatus); + const { brand } = ANGRY_MIAO_INFINITY_PROFILE; + // No mouse answers, so the receiver gets its own name instead of the mouse's. + const name = `${brand} Receiver`; + return { + brand, + name, + ui: { + family: "angry-miao", + settingsReady: false, + receiverOnly: true, + defaultDisplayName: name, + hideAdvancedLighting: true, + separateLightingZones: true, + statusNote: "The receiver is connected, but the mouse is not answering. Wake it, or switch it to 2.4 GHz.", + }, + batteryPercent: null, + batteryState: "Unknown", + dpi: 0, + pollingRateHz: 0, + activeProfile: null, + liftOffDistance: null, + connectionType: "Wireless", + connectionDetail: "2.4 GHz", + firmware, + ...(spareBattery ? { spareBattery } : {}), + ...(receiverLight ? { lightingZones: [receiverLight] } : {}), + }; + } + + private async readReceiverLight(): Promise { + const light = await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_GET_LIGHT]), true); + const power = await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_GET_LIGHT_SWITCH]), true); + const decoded = am30DecodeReceiverLight(light!, power!); + return { + zone: "Receiver", + modes: ["Off", ...RECEIVER_EFFECTS], + mode: decoded.enabled ? RECEIVER_EFFECTS[decoded.effect - 1] : "Off", + color: decoded.color, + color2: null, + // The vendor panel hides the colour for neon and the speed for always on. + colorModes: RECEIVER_EFFECTS.filter((mode) => mode !== "Neon"), + dualColorModes: [], + reactiveModes: RECEIVER_EFFECTS.filter((mode) => mode !== "Static"), + speeds: [...AM30_RECEIVER_SPEEDS], + speed: decoded.speed, + brightness: decoded.brightness, + brightnessLevels: [...AM30_RECEIVER_BRIGHTNESS], + }; + } + + private async setReceiverLight( + lighting: Pick & Partial>, + ): Promise { + if (this.transport !== "dongle") throw new Error("The receiver light needs the 2.4 GHz receiver."); + if (lighting.mode !== "Off") { + const effect = lighting.mode ? RECEIVER_EFFECTS.indexOf(lighting.mode) + 1 : 0; + if (effect < 1) throw new Error(`Unsupported receiver light effect: ${lighting.mode}.`); + await this.receiverCommand(am30EncodeReceiverLight({ + effect, + speed: lighting.speed ?? 1, + brightness: lighting.brightness ?? 100, + color: lighting.color ?? "#ffffff", + }), false); + await delay(30); + } + await this.receiverCommand(am30EncodeCommand([AM30_RECEIVER_SET_LIGHT_SWITCH, lighting.mode === "Off" ? 0 : 1]), false); + return this.readReceiverLight(); + } + + readStatus(): Promise { + return this.exclusive(() => this.readStatusNow()); + } + + private async readStatusNow(): Promise { + await this.open(); + this.firmwareCode = null; + // The last verified id stays until `8F` answers again, so a write made during this read still goes out. + let receiverStatus: Uint8Array | null = null; + if (this.transport === "dongle") { + receiverStatus = await this.readReceiverStatus(); + if (receiverStatus[AM30_STATUS_MOUSE_OFFLINE] !== 0) { + // The mouse is absent, so nothing it reported earlier holds any more. + this.deviceId = null; + this.resolvedProfile = null; + this.profileConfirmed = false; + return this.receiverOnlyStatus(receiverStatus); + } + } + // Read first: `D0` and `50` take the profile index. + let profile: number | null = null; + try { profile = await this.readProfile(); } catch { /* Optional: the profile selector stays hidden. */ } + this.profileConfirmed = profile !== null; + if (profile !== null) this.currentProfile = profile; + let deviceId: number | null = null; + try { deviceId = await this.getDeviceId(); } catch { /* Unknown: settings stay read-only. */ } + this.deviceId = deviceId; + this.resolvedProfile = this.deviceId === null ? null : ANGRY_MIAO_PROFILES.get(this.deviceId) ?? null; + const model = this.profile; + const name = this.resolvedProfile + ? `${model.brand} ${model.model}` + : this.device.productName?.trim() || "Angry Miao mouse"; + + // The DPI read has to work: it proves the relay and checksum path. + const dpi = await this.getDpi(); + const active = dpi.stages[dpi.activeIndex] ?? dpi.stages[0]; + const [opt0Result, matrixResult] = await Promise.allSettled([ + this.getOptionParam0(), + // Without a confirmed profile the mappings stay hidden rather than show a guessed profile's. + profile !== null ? this.getKeyMatrix(profile) : Promise.resolve(null), + this.getFirmwareVersion(), + ]); + const opt0 = opt0Result.status === "fulfilled" ? opt0Result.value : null; + // Only this read's own `D0` reply, never another call's. + const matrix = matrixResult.status === "fulfilled" ? matrixResult.value : null; + const buttonMappings = matrix && Object.fromEntries(this.buttonSlots().map(({ name, slot }) => [ + name, am30DecodeButtonAction(matrix.subarray(slot * 4, slot * 4 + 4)), + ])); + const { count } = dpi; + + // F7 byte 2 mirrors the mouse battery through the receiver; D6 reads it from the mouse itself. + let battery: ReturnType = { percent: null, state: "Unknown" }; + try { battery = am30DecodeBattery(await this.command([AM30_GET_BATTERY])); } catch { /* Optional. */ } + if (battery.percent === null && this.transport === "bluetooth") { + try { battery = { percent: await this.bluetoothBattery(), state: "Unknown" }; } catch { /* Optional. */ } + } + let turboMode: boolean | undefined; + try { + turboMode = this.blastMode ?? (await this.command([AM30_GET_BLAST_MODE]))[1] === 1; + } catch { /* Optional: the switch stays hidden. */ } + let usbCode: number | null = null; + // The vendor app reads `AD` on the cable only; through the receiver it reads 0. + if (this.transport === "direct") { + try { + const reply = await this.command([AM30_GET_USB_VERSION]); + usbCode = reply[1] | (reply[2] << 8); + } catch { /* Optional: the package version needs it. */ } + } + const firmware = am30FirmwareLabels(usbCode, this.firmwareCode || null); + let receiverLight: MouseLighting | undefined; + let spareBattery: ReturnType = null; + if (this.transport === "dongle") { + try { receiverLight = await this.readReceiverLight(); } catch { /* Optional: the zone stays hidden. */ } + firmware.push(...await this.readReceiverFirmware()); + if (receiverStatus) spareBattery = am30DecodeSpareBattery(receiverStatus); + } + const mouseLight = opt0 ? this.mouseLight(opt0) : undefined; + const rawSleep = opt0 ? opt0[this.sleepOffset] | (opt0[this.sleepOffset + 1] << 8) : null; + const wireless = this.transport !== "direct"; + + return { + brand: model.brand, + name, + ui: { + family: "angry-miao", + settingsReady: this.modelVerified, + defaultDisplayName: name, + hideAdvancedLighting: true, + separateLightingZones: true, + dpiStageEditor: { + maxStages: AM30_MAX_DPI_STAGES, + minDpi: model.minDpi, + maxDpi: model.maxDpi, + stepDpi: model.dpiStep, + countEditable: true, + }, + ...(this.modelVerified ? {} : { + statusNote: `This mouse reports device id ${this.deviceId ?? "unknown"}, which OpenMouse has not verified, so its settings are read-only.`, + }), + }, + dpi: active.x, + dpiY: active.y, + supportsSeparateDpiAxes: true, + dpiStages: dpi.stages.slice(0, count).map((stage) => stage.x), + dpiStageColors: dpi.stages.slice(0, count).map((stage) => `#${stage.rgb.toString(16).padStart(6, "0")}`), + activeDpiStage: dpi.activeIndex, + pollingRateHz: (opt0 && AM30_RATE_DECODE[opt0[AM30_OPT0_REPORT_RATE]]) || 1000, + supportedPollingRates: this.supportedPollingRates, + connectionType: wireless ? "Wireless" : "Wired", + connectionDetail: { bluetooth: "Bluetooth", dongle: "2.4 GHz", direct: "USB" }[this.transport], + liftOffDistance: opt0 ? AM30_LIFT_OFF_LEVELS[opt0[AM30_OPT0_LIFT_OFF]] ?? AM30_LIFT_OFF_LEVELS[0] : null, + angleSnapping: opt0 ? opt0[AM30_OPT0_ANGLE_SNAP] !== 0 : null, + debounceMs: null, + rippleControl: null, + sleepTimeout: rawSleep === AM30_SLEEP_NEVER ? 0 : rawSleep, + activeProfile: profile === null ? null : profile + 1, + ...(profile !== null ? { profileCount: AM30_PROFILE_COUNT } : {}), + firmware: [...firmware, model.sensor], + batteryPercent: battery.percent, + batteryState: battery.state, + ...(spareBattery ? { spareBattery } : {}), + ...(opt0 ? { + debounceMs: AM30_DEBOUNCE_GEARS_MS[am30DebounceGear(AM30_RATE_DECODE[opt0[AM30_OPT0_REPORT_RATE]], opt0[AM30_OPT0_DEBOUNCE])], + rippleControl: (opt0[AM30_OPT0_FLAGS] & AM30_OPT0_FLAG_RIPPLE) !== 0, + motionSync: opt0[AM30_OPT0_MOTION_SYNC] === 1, + lighting: mouseLight, + } : {}), + ...(receiverLight ? { lightingZones: [...(mouseLight ? [mouseLight] : []), receiverLight] } : {}), + ...(turboMode !== undefined ? { turboMode } : {}), + ...(buttonMappings ? { + buttonMappings, + buttonOptions: this.getButtonOptions(), + defaultButtonMappings: { ...AM30_DEFAULT_BUTTON_MAPPINGS }, + fixedButtons: ["Left"], + } : {}), + }; + } +} diff --git a/src/drivers/mouse-types.ts b/src/drivers/mouse-types.ts index 43943af3..97cd3b17 100644 --- a/src/drivers/mouse-types.ts +++ b/src/drivers/mouse-types.ts @@ -10,6 +10,8 @@ import type { Rival650ButtonMappings } from "../steelseries/rival650.js"; export interface MouseUiHints { /** This connection is carried by a receiver with its own configurable controls. */ receiverControls?: boolean; + /** Only the receiver answered: its mouse is off, asleep or on another link, so show the receiver, not the mouse. */ + receiverOnly?: boolean; /** Stable driver id, e.g. "egg-we". */ family?: string; /** When false, core settings grid stays hidden. Default true. */ @@ -54,6 +56,8 @@ export interface MouseUiHints { showAdvancedSection?: boolean; /** Keep RGB controls in the Lighting tab without duplicating them under Advanced. */ hideAdvancedLighting?: boolean; + /** Show each lighting zone as its own card (e.g. mouse and receiver) instead of one card with a zone picker. */ + separateLightingZones?: boolean; /** Always show battery column (even wired with null %). */ forceShowBattery?: boolean; /** Group the device's battery, DPI-indicator, and sleep controls on Overview. */ @@ -164,7 +168,11 @@ export type MouseLightingMode = | "Breathing Loop" | "Static DPI" | "Breathing DPI" - | "Single color flow"; + | "Single color flow" + | "Marquee" + | "Ring" + | "Buffer" + | "Chase"; export interface AtkStoredButton { id: "left" | "right" | "middle" | "back" | "forward" | "bottom"; @@ -259,7 +267,7 @@ export interface MouseStatus { dynamicDpi: KeychronDynamicDpi | null; factoryReset: boolean; }; - 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" | "UtechSmart" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "AULA" | "Sades" | "Xiaomi" | "LEOBOG" | "Kmart" | "Cosmic Byte" | "Fallen" | "Zaopin" | "8BitDo" | "A4Tech"; + 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" | "Angry Miao" | "Corsair" | "Microsoft" | "Dareu" | "Redragon" | "UtechSmart" | "Incott" | "HyperX" | "ASUS" | "Ryunix" | "Amkette" | "Delux" | "GravaStar" | "IPI" | "Rapoo" | "Fater" | "Cooler Master" | "AJAZZ" | "Scyrox" | "Hitscan" | "ROCCAT" | "Thermaltake" | "Redgear" | "AULA" | "Sades" | "Xiaomi" | "LEOBOG" | "Kmart" | "Cosmic Byte" | "Fallen" | "Zaopin" | "8BitDo" | "A4Tech"; name: string; /** Optional LunaFury controls, populated only after successful device reads. */ lunafury?: import("../lamzu/lunafury.js").LunaFurySettings; @@ -268,6 +276,8 @@ export interface MouseStatus { batteryPercent: number | null; batteryVoltageMv?: number | null; batteryState: "Charging" | "Charging slowly" | "Almost full" | "Full" | "Discharging" | "Unknown"; + /** A second battery outside the mouse, such as a spare charging in the receiver dock. Unset when there is none. */ + spareBattery?: { percent: number; state: "Charging" | "Full" }; dpi: number; dpiY?: number; supportsSeparateDpiAxes?: boolean; diff --git a/src/drivers/registry.test.ts b/src/drivers/registry.test.ts index bca2272b..32b8b623 100644 --- a/src/drivers/registry.test.ts +++ b/src/drivers/registry.test.ts @@ -278,6 +278,10 @@ const NAMED_PROBES = [ productName: "USB Gaming Mouse", collections: [collection(0x0b, 0, { feature: [4, 6] })], }, + // Angry Miao is claimed by name: other brands reuse both product ids. + { vendorId: 0x3151, productId: 0x402a, productName: "Angry Miao Infinity", collections: [collection(0xffff, 0x02)] }, + { vendorId: 0x3151, productId: 0x5007, productName: "AM INFINITY 8K MOUSE", collections: [collection(0xffff, 0x02)] }, + { vendorId: 0x3151, productId: 0x402c, productName: "AM INFINITY BT MOUSE", collections: [collection(0xff55, 0x0202)] }, ] as const; function claimsFor( @@ -381,7 +385,9 @@ test("every product id offered in the picker has a driver", () => { for (const filter of SUPPORTED_HID_FILTERS) { const { vendorId, productId } = filter; if (vendorId === undefined || productId === undefined) continue; - const claimed = SHAPES.some((collections) => claimsFor(vendorId, productId, collections).length > 0); + const claimed = SHAPES.some((collections) => claimsFor(vendorId, productId, collections).length > 0) + || NAMED_PROBES.some((named) => named.vendorId === vendorId && named.productId === productId + && claimsFor(vendorId, productId, [...named.collections], named.productName).length > 0); if (!claimed) orphans.push(`vid 0x${vendorId.toString(16)} pid 0x${productId.toString(16)}`); } assert.deepEqual( diff --git a/src/drivers/registry.ts b/src/drivers/registry.ts index fb65edb0..4d690a50 100644 --- a/src/drivers/registry.ts +++ b/src/drivers/registry.ts @@ -9,6 +9,7 @@ import { EggOp1HidClient } from "./endgame/egg-op1-hid.ts"; import { EggOtHidClient } from "./endgame/egg-ot-hid.ts"; import { FantechHidClient } from "./fantech/hid.ts"; import { GearHubHidClient } from "./gearhub/hid.ts"; +import { AngryMiaoHidClient } from "./angry-miao/hid.ts"; import { eggWeCreate, eggWeIsSupported, eggWeSupportScore, isEggWeClient, type EggWeHidClient } from "./endgame/egg-we-control.ts"; import { FinalmouseHidClient } from "./finalmouse/hid.ts"; import { Keychron1kHidClient } from "./keychron/mouse-1k-hid.ts"; @@ -116,7 +117,7 @@ import { XiaomiHidClient } from "./xiaomi/hid.ts"; import { A4techHidClient } from "./a4tech/a4tech-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 | AttackSharkCompxHidClient | 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 | UtechsmartVenusHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | ZaopinHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient | InstantA825HidClient | XiaomiHidClient | LeobogGm3HidClient | Sinowealth520HidClient | KmartHidClient | EightBitDoHidClient | A4techHidClient; +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 | AttackSharkCompxHidClient | 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 | UtechsmartVenusHidClient | RedragonM690ProHidClient | RedragonM719ProHidClient | IncottHidClient | HyperXHidClient | MchoseV3HidClient | AsusHidClient | KyuProMx1Client | AmketteXsHidClient | DeluxHidClient | BytechHidClient | RapooHidClient | FaterHidClient | CoolerMasterHidClient | AjazzHidClient | AjazzAj200pHidClient | AjazzAk820HidClient | ScyroxHidClient | ZaopinHidClient | HitscanHidClient | RoccatHidClient | ThermaltakeHidClient | RedgearX13HidClient | AulaSc380ProHidClient | InstantA825HidClient | XiaomiHidClient | LeobogGm3HidClient | Sinowealth520HidClient | KmartHidClient | EightBitDoHidClient | A4techHidClient | AngryMiaoHidClient; export interface DeviceDriver { brand: string; supports(device: HIDDevice): boolean; @@ -213,8 +214,11 @@ export const DEVICE_DRIVERS: readonly DeviceDriver[] = [ // product ids so it cannot shadow Fantech's own hardware. The client // identifies the specific model from the device id after connecting; the // registry label is the M5 Pro's brand (the fallback identity). - { brand: "Lingbao", supports: (device) => GearHubHidClient.isSupported(device), create: (device) => new GearHubHidClient(device), score: () => 7 }, - { brand: "Fantech", supports: (device) => FantechHidClient.isSupported(device), create: (device) => new FantechHidClient(device), score: () => 5 }, + // Angry Miao reuses Yichip product ids (cable, receiver and the AJ179 PRO's + // Bluetooth id); its own driver claims them by name, so these two step aside. + { brand: "Lingbao", supports: (device) => GearHubHidClient.isSupported(device) && !AngryMiaoHidClient.isSupported(device), create: (device) => new GearHubHidClient(device), score: () => 7 }, + { brand: "Angry Miao", supports: (device) => AngryMiaoHidClient.isSupported(device), create: (device) => new AngryMiaoHidClient(device), score: () => 7 }, + { brand: "Fantech", supports: (device) => FantechHidClient.isSupported(device) && !AngryMiaoHidClient.isSupported(device), create: (device) => new FantechHidClient(device), score: () => 5 }, { brand: "Wooting", supports: (device) => WootingHidClient.isSupported(device), create: (device) => new WootingHidClient(device), score: () => 6 }, { brand: "WALLHACK", supports: (device) => WallhackMouseHidClient.isSupported(device), create: (device) => new WallhackMouseHidClient(device), score: () => 8 }, { brand: "WALLHACK", supports: (device) => WallhackKeyboardHidClient.isSupported(device), create: (device) => new WallhackKeyboardHidClient(device), score: () => 8 }, diff --git a/src/drivers/vendors.ts b/src/drivers/vendors.ts index 067b0ab6..2a894df3 100644 --- a/src/drivers/vendors.ts +++ b/src/drivers/vendors.ts @@ -37,6 +37,7 @@ import { GEARHUB_PRODUCTS, GEARHUB_VENDOR_ID, } from "@openmouse/protocol/gearhub"; +import { ANGRY_MIAO_PRODUCTS, ANGRY_MIAO_VENDOR_ID } from "@openmouse/protocol/angry-miao"; import { GWOLVES_PRODUCTS } from "./gwolves/products.ts"; import { LAMZU_INCA_PRODUCTS, LAMZU_INCA_VENDOR_ID } from "@openmouse/protocol/lamzu"; import { @@ -924,6 +925,11 @@ export const GEARHUB_HID_FILTERS: HIDDeviceFilter[] = [...GEARHUB_PRODUCTS.entri }), ); +/** Angry Miao mice and receivers, on Yichip's shared vendor id. */ +export const ANGRY_MIAO_HID_FILTERS: HIDDeviceFilter[] = [...ANGRY_MIAO_PRODUCTS].map( + ([productId, { usagePage, usage }]) => ({ vendorId: ANGRY_MIAO_VENDOR_ID, productId, usagePage, usage }), +); + // Corsair NXP-family mice answer on the interface whose collection is usage // page 0xffc2, usage 4 (64-byte feature reports on id 0). MI_00 also carries // an 0xffc2 collection (usage 3) that never answers, so the usage is required @@ -1189,6 +1195,7 @@ export const SUPPORTED_HID_FILTERS: HIDDeviceFilter[] = [ ...LOGITECH_RECEIVER_FILTERS, ...LOGITECH_BLUETOOTH_FILTERS, ...GEARHUB_HID_FILTERS, + ...ANGRY_MIAO_HID_FILTERS, // Fantech mice use vendor usage page 0xFFFF, usage 0x02 for configuration. { vendorId: VENDOR_ID.fantech, usagePage: 0xffff, usage: 0x02 }, ...WALLHACK_HID_FILTERS, diff --git a/src/index.ts b/src/index.ts index 1fd1141d..36dbf971 100644 --- a/src/index.ts +++ b/src/index.ts @@ -54,6 +54,7 @@ export * as thermaltake from "./thermaltake/index.js"; export * as coolermaster from "./coolermaster/index.js"; export * as redgear from "./redgear/index.ts"; export * as ajazz from "./ajazz/index.js"; +export * as angryMiao from "./angry-miao/index.js"; export * as scyrox from "./scyrox/index.js"; export * as zaopin from "./zaopin/index.js"; export * as roccat from "./roccat/index.js"; diff --git a/tsconfig.json b/tsconfig.json index e6885a81..c9da7912 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -28,6 +28,7 @@ "@openmouse/protocol/endgame-gear-op1": ["./src/endgame-gear/op1.ts"], "@openmouse/protocol/finalmouse": ["./src/finalmouse/index.ts"], "@openmouse/protocol/gearhub": ["./src/gearhub/index.ts"], + "@openmouse/protocol/angry-miao": ["./src/angry-miao/index.ts"], "@openmouse/protocol/incott": ["./src/incott/index.ts"], "@openmouse/protocol/keychron": ["./src/keychron/index.ts"], "@openmouse/protocol/lamzu": ["./src/lamzu/index.ts"],