Repository navigation
Expand file tree
/
Copy pathmxprobe.swift
More file actions
652 lines (583 loc) · 23.4 KB
/
Copy pathmxprobe.swift
File metadata and controls
652 lines (583 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
// mxprobe — read-only HID++ 2.0 prober for Logitech devices on macOS.
//
// Sends only whitelisted getter functions. Never writes device state.
// Talks to the vendor collection (BLE usage page 0xFF43 / USB 0xFF00) that
// macOS exposes on the same IOHIDDevice as the mouse collection.
import Foundation
import IOKit
import IOKit.hid
// MARK: - HID++ wire constants
let kVendorLogitech = 0x046D
let kReportShort: UInt8 = 0x10
let kReportLong: UInt8 = 0x11
let kLenShort = 7
let kLenLong = 20
/// 0xFF addresses a directly-connected (Bluetooth/BLE) device.
/// Receiver-attached devices use 0x01...0x06.
var gDeviceIndex: UInt8 = 0xFF
/// Software ID occupies the low nibble of byte 3. Must be non-zero;
/// zero is reserved for device-originated notifications.
let kSoftwareID: UInt8 = 0x0A
// MARK: - Feature registry
let featureNames: [UInt16: String] = [
0x0000: "Root",
0x0001: "Feature Set",
0x0003: "Device FW Version",
0x0005: "Device Name / Type",
0x0007: "Device Friendly Name",
0x0008: "Keep-Alive",
0x0020: "Config Change",
0x0021: "Unique Identifier",
0x00c2: "DFU Control",
0x1000: "Battery Status",
0x1001: "Battery Voltage",
0x1004: "Unified Battery",
0x1300: "LED Control",
0x1802: "Device Reset",
0x1814: "Change Host",
0x1815: "Hosts Info",
0x1830: "Low-Power Mode",
0x1890: "RF Test",
0x18a1: "LED Test",
0x1b04: "Reprogrammable Controls v4",
0x1d4b: "Wireless Device Status",
0x1df3: "e-RGB Direct",
0x1e00: "Enable Hidden Features",
0x1e22: "SPI Direct Access",
0x1f03: "Equalizer",
0x1f20: "ADC Measurement",
0x2100: "Vertical Scrolling",
0x2110: "SmartShift",
0x2111: "SmartShift Enhanced",
0x2120: "Hi-Res Scrolling",
0x2121: "Hi-Res Wheel",
0x2130: "Ratchet Wheel",
0x2150: "Thumb Wheel",
0x2201: "Adjustable DPI",
0x2202: "Extended Adjustable DPI",
0x2205: "Pointer Motion Scaling",
0x2250: "Analysis Mode",
0x8060: "Report Rate",
0x8061: "Extended Report Rate",
0x8100: "Onboard Profiles",
0x8110: "Mouse Button Spy",
]
/// Control IDs reported by feature 0x1b04. These are the remap targets.
let controlNames: [UInt16: String] = [
0x0050: "Left Click",
0x0051: "Right Click",
0x0052: "Middle Mouse Button",
0x0053: "Back",
0x0056: "Forward",
0x005b: "Wheel Left Tilt",
0x005d: "Wheel Right Tilt",
0x00c3: "Gesture Button",
0x00c4: "SmartShift / Mode Shift Button",
0x00d7: "Virtual Gesture Button",
0x00e0: "Thumb Wheel Scroll",
0x00e1: "Thumb Wheel Click",
]
let hidppErrors: [UInt8: String] = [
0x00: "no error",
0x01: "unknown",
0x02: "invalid argument",
0x03: "out of range",
0x04: "hardware error",
0x05: "logitech internal",
0x06: "invalid feature index",
0x07: "invalid function id",
0x08: "busy",
0x09: "unsupported",
]
func featureName(_ id: UInt16) -> String {
featureNames[id] ?? "unknown"
}
func hex(_ bytes: [UInt8]) -> String {
bytes.map { String(format: "%02x", $0) }.joined(separator: " ")
}
// MARK: - Transport
final class HIDPP {
enum CallError: Error {
case io(IOReturn)
case timeout
case device(UInt8)
case malformed(String)
}
let device: IOHIDDevice
private var inbox: [[UInt8]] = []
private let lock = NSLock()
private let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
/// Set once by the ping step so we can report the observed wire format.
private(set) var sawReportIDInBuffer: Bool?
/// Output report IDs the vendor collection declares, mapped to payload length
/// in bytes (excluding the report ID). BLE declares only 0x11; USB and Bolt
/// receivers declare both 0x10 and 0x11.
let vendorReports: [UInt8: Int]
init(device: IOHIDDevice, vendorReports: [UInt8: Int]) {
self.device = device
self.vendorReports = vendorReports
buf.initialize(repeating: 0, count: 64)
}
func open() -> IOReturn {
let r = IOHIDDeviceOpen(device, IOOptionBits(kIOHIDOptionsTypeNone))
guard r == kIOReturnSuccess else { return r }
let ctx = Unmanaged.passUnretained(self).toOpaque()
IOHIDDeviceRegisterInputReportCallback(device, buf, 64, hidppInputCallback, ctx)
IOHIDDeviceScheduleWithRunLoop(
device, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)
return kIOReturnSuccess
}
fileprivate func deliver(reportID: UInt32, raw: [UInt8]) {
var bytes = raw
// macOS is inconsistent about whether the report ID is included in the
// callback buffer. Normalize so byte 0 is always the report ID.
if bytes.first != UInt8(truncatingIfNeeded: reportID) {
if sawReportIDInBuffer == nil { sawReportIDInBuffer = false }
bytes.insert(UInt8(truncatingIfNeeded: reportID), at: 0)
} else if sawReportIDInBuffer == nil {
sawReportIDInBuffer = true
}
lock.lock()
inbox.append(bytes)
lock.unlock()
}
private func drain() -> [[UInt8]] {
lock.lock()
let out = inbox
inbox.removeAll()
lock.unlock()
return out
}
/// Issue a HID++ request and wait for the matching reply.
func call(
feature featureIndex: UInt8,
function fn: UInt8,
params: [UInt8] = [],
timeout: TimeInterval = 1.2
) throws -> [UInt8] {
// Use the short report only when the payload fits AND the device declares
// it. Bluetooth LE devices declare 0x11 exclusively.
let fitsShort = params.count <= 3 && vendorReports[kReportShort] != nil
let reportID = fitsShort ? kReportShort : kReportLong
guard let payloadLen = vendorReports[reportID] else {
throw CallError.malformed(
"device declares no output report 0x\(String(format: "%02x", reportID))")
}
let total = payloadLen + 1
var pkt = [UInt8](repeating: 0, count: total)
pkt[0] = reportID
pkt[1] = gDeviceIndex
pkt[2] = featureIndex
pkt[3] = (fn << 4) | kSoftwareID
for (i, p) in params.enumerated() where 4 + i < total { pkt[4 + i] = p }
_ = drain()
let r = IOHIDDeviceSetReport(
device, kIOHIDReportTypeOutput, CFIndex(reportID), pkt, CFIndex(total))
guard r == kIOReturnSuccess else { throw CallError.io(r) }
let tag = (fn << 4) | kSoftwareID
let deadline = Date().addingTimeInterval(timeout)
while Date() < deadline {
CFRunLoopRunInMode(.defaultMode, 0.02, true)
for msg in drain() {
guard msg.count >= 6, msg[1] == gDeviceIndex else { continue }
// HID++ 2.0 error: byte 2 == 0xFF, then echoed feature/function.
if msg[2] == 0xFF, msg[3] == featureIndex, msg[4] == tag {
throw CallError.device(msg[5])
}
// HID++ 1.0 error: byte 2 == 0x8F.
if msg[2] == 0x8F, msg[3] == featureIndex, msg[4] == tag {
throw CallError.device(msg[5])
}
if msg[2] == featureIndex, msg[3] == tag {
return Array(msg[4...])
}
}
}
throw CallError.timeout
}
/// Root/0x0000 function 0: resolve a feature ID to its runtime index.
func featureIndex(of featureID: UInt16) throws -> (index: UInt8, type: UInt8, version: UInt8) {
let r = try call(
feature: 0x00, function: 0x00,
params: [UInt8(featureID >> 8), UInt8(featureID & 0xFF)])
guard r.count >= 1 else { throw CallError.malformed("short getFeature reply") }
return (r[0], r.count > 1 ? r[1] : 0, r.count > 2 ? r[2] : 0)
}
/// Root/0x0000 function 1: protocol ping. Echoes the third parameter.
func ping() throws -> (major: UInt8, minor: UInt8) {
let r = try call(feature: 0x00, function: 0x01, params: [0x00, 0x00, 0xAA])
guard r.count >= 3, r[2] == 0xAA else {
throw CallError.malformed("ping echo mismatch: \(hex(r))")
}
return (r[0], r[1])
}
}
private let hidppInputCallback: IOHIDReportCallback = {
context, _, _, _, reportID, report, reportLength in
guard let context, reportLength > 0 else { return }
let me = Unmanaged<HIDPP>.fromOpaque(context).takeUnretainedValue()
let bytes = Array(UnsafeBufferPointer(start: report, count: Int(reportLength)))
me.deliver(reportID: reportID, raw: bytes)
}
// MARK: - Device discovery
func usagePages(of device: IOHIDDevice) -> [(page: Int, usage: Int)] {
guard let raw = IOHIDDeviceGetProperty(device, kIOHIDDeviceUsagePairsKey as CFString),
let pairs = raw as? [[String: Any]]
else { return [] }
return pairs.compactMap { pair in
guard let p = pair[kIOHIDDeviceUsagePageKey] as? Int,
let u = pair[kIOHIDDeviceUsageKey] as? Int
else { return nil }
return (p, u)
}
}
func intProp(_ device: IOHIDDevice, _ key: String) -> Int? {
IOHIDDeviceGetProperty(device, key as CFString) as? Int
}
func strProp(_ device: IOHIDDevice, _ key: String) -> String? {
IOHIDDeviceGetProperty(device, key as CFString) as? String
}
/// A vendor collection carrying HID++. 0xFF00 over USB/Unifying, 0xFF43 over BLE.
func hasHIDPPCollection(_ device: IOHIDDevice) -> Bool {
usagePages(of: device).contains { $0.page == 0xFF00 || $0.page == 0xFF43 }
}
func reportDescriptor(_ device: IOHIDDevice) -> [UInt8] {
guard let data = IOHIDDeviceGetProperty(device, "ReportDescriptor" as CFString) as? Data
else { return [] }
return [UInt8](data)
}
/// Walk the HID report descriptor and collect every Output report declared inside
/// a Logitech vendor collection. Returns report ID -> payload length in bytes.
///
/// This is the only reliable way to know which HID++ reports a device accepts:
/// the answer differs between USB, Bolt receiver, and Bluetooth LE on the very
/// same mouse.
func parseVendorOutputReports(_ descriptor: [UInt8]) -> [UInt8: Int] {
var reports: [UInt8: Int] = [:]
var usagePage: UInt32 = 0
var reportID: UInt8 = 0
var reportSize = 0
var reportCount = 0
var i = 0
while i < descriptor.count {
let prefix = descriptor[i]
if prefix == 0xFE { // long item: [0xFE, dataSize, tag, data...]
guard i + 1 < descriptor.count else { break }
i += Int(descriptor[i + 1]) + 3
continue
}
let sizeCode = Int(prefix & 0x03)
let length = sizeCode == 3 ? 4 : sizeCode
let type = (prefix >> 2) & 0x03
let tag = (prefix >> 4) & 0x0F
guard i + 1 + length <= descriptor.count else { break }
var value: UInt32 = 0
for b in 0..<length { value |= UInt32(descriptor[i + 1 + b]) << (8 * b) }
switch (type, tag) {
case (1, 0): usagePage = value // Usage Page
case (1, 7): reportSize = Int(value) // Report Size
case (1, 8): reportID = UInt8(truncatingIfNeeded: value) // Report ID
case (1, 9): reportCount = Int(value) // Report Count
case (0, 9): // Output
if usagePage == 0xFF00 || usagePage == 0xFF43, reportID != 0 {
reports[reportID] = (reportSize * reportCount) / 8
}
default: break
}
i += 1 + length
}
return reports
}
func findLogitechDevices() -> [IOHIDDevice] {
let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone))
IOHIDManagerSetDeviceMatching(
manager, [kIOHIDVendorIDKey: kVendorLogitech] as CFDictionary)
IOHIDManagerOpen(manager, IOOptionBits(kIOHIDOptionsTypeNone))
guard let set = IOHIDManagerCopyDevices(manager) as? Set<IOHIDDevice> else { return [] }
return Array(set)
}
// MARK: - Decoders
func describeBatteryStatus(_ r: [UInt8]) -> String {
guard r.count >= 3 else { return "malformed" }
let status: [UInt8: String] = [
0: "discharging", 1: "recharging", 2: "charge nearly full",
3: "charge complete", 4: "charging error", 5: "invalid battery",
6: "thermal error",
]
return "\(r[0])% (next level \(r[1])%), \(status[r[2]] ?? "status \(r[2])")"
}
func describeUnifiedBattery(_ r: [UInt8]) -> String {
guard r.count >= 4 else { return "malformed" }
let charging: [UInt8: String] = [
0: "discharging", 1: "charging", 2: "charging (slow)",
3: "charge complete", 4: "charging error",
]
let levelBits = [(0x01, "critical"), (0x02, "low"), (0x04, "good"), (0x08, "full")]
let level = levelBits.first { r[1] & UInt8($0.0) != 0 }?.1 ?? "level 0x\(String(r[1], radix: 16))"
let external = r[3] != 0 ? "external power connected" : "on battery"
return "\(r[0])% — \(level), \(charging[r[2]] ?? "state \(r[2])"), \(external)"
}
func describeWheelMode(_ v: UInt8) -> String {
switch v {
case 0: return "0 (do not change)"
case 1: return "1 (FREESPIN)"
case 2: return "2 (RATCHET)"
default: return "\(v) (unrecognized)"
}
}
/// Replies are always zero-padded to the full report length, so response length
/// tells us nothing about which fields are real. The feature ID does: only
/// 0x2111 carries the torque block.
func describeSmartShift(_ r: [UInt8], enhanced: Bool) -> [String] {
guard r.count >= 3 else { return ["malformed: \(hex(r))"] }
let threshold =
r[1] == 0
? "\(r[1]) <- SmartShift disabled"
: "\(r[1]) (scroll-speed threshold to break into freespin)"
var out = [
"wheel mode: \(describeWheelMode(r[0]))",
"auto-disengage: \(threshold)",
"auto-disengage default: \(r[2])",
]
if enhanced, r.count >= 6 {
out.append("current torque: \(r[3])%")
out.append("default torque: \(r[4])%")
out.append("max force: \(r[5])")
}
return out
}
func describeHiResWheelMode(_ r: [UInt8]) -> [String] {
guard r.count >= 1 else { return ["malformed"] }
let f = r[0]
return [
"invert: \((f & 0x04) != 0)",
"hi-res resolution: \((f & 0x02) != 0 ? "on" : "off")",
"target: \((f & 0x01) != 0 ? "diverted to software" : "normal HID")",
]
}
func describeDPI(_ r: [UInt8]) -> String {
guard r.count >= 5 else { return "malformed: \(hex(r))" }
let current = Int(r[1]) << 8 | Int(r[2])
let deflt = Int(r[3]) << 8 | Int(r[4])
return "sensor \(r[0]): \(current) dpi (default \(deflt))"
}
// MARK: - Output helpers
var gIndent = ""
func say(_ s: String = "") { print(gIndent + s) }
func header(_ s: String) {
print("")
print("\u{001B}[1m\(s)\u{001B}[0m")
print(String(repeating: "─", count: max(8, s.count)))
}
func explain(_ e: Error) -> String {
guard let e = e as? HIDPP.CallError else { return "\(e)" }
switch e {
case .timeout: return "timeout (no reply)"
case .device(let c):
return "device error 0x\(String(format: "%02x", c)) — \(hidppErrors[c] ?? "undocumented")"
case .io(let r): return "IOKit error 0x\(String(format: "%08x", UInt32(bitPattern: r)))"
case .malformed(let m): return "malformed: \(m)"
}
}
// MARK: - Main
let candidates = findLogitechDevices()
guard !candidates.isEmpty else {
say("No Logitech HID devices found.")
exit(1)
}
header("Logitech HID devices")
for d in candidates {
let name = strProp(d, kIOHIDProductKey) ?? "?"
let pid = intProp(d, kIOHIDProductIDKey) ?? 0
let transport = strProp(d, kIOHIDTransportKey) ?? "?"
let pages = usagePages(of: d)
.map { String(format: "%04x:%04x", $0.page, $0.usage) }
.joined(separator: ", ")
let mark = hasHIDPPCollection(d) ? "\u{001B}[32m✔ HID++\u{001B}[0m" : " no HID++"
say("\(mark) \(name) pid=0x\(String(format: "%04x", pid)) \(transport)")
say(" usages: \(pages)")
}
guard let target = candidates.first(where: hasHIDPPCollection) else {
say("")
say("No device exposes a HID++ vendor collection (0xFF00 / 0xFF43).")
exit(1)
}
let productName = strProp(target, kIOHIDProductKey) ?? "device"
header("HID++ transport")
let descriptor = reportDescriptor(target)
let vendorReports = parseVendorOutputReports(descriptor)
say("report descriptor: \(descriptor.count) bytes")
if vendorReports.isEmpty {
say("no vendor output reports declared — cannot speak HID++ to this device")
exit(1)
}
for (rid, len) in vendorReports.sorted(by: { $0.key < $1.key }) {
let kind = rid == kReportShort ? "short" : (rid == kReportLong ? "long" : "vendor")
say("output report 0x\(String(format: "%02x", rid)): \(len) byte payload (\(kind))")
}
let hidpp = HIDPP(device: target, vendorReports: vendorReports)
header("Opening \(productName)")
let openResult = hidpp.open()
if openResult != kIOReturnSuccess {
say("IOHIDDeviceOpen failed: 0x\(String(format: "%08x", UInt32(bitPattern: openResult)))")
if openResult == kIOReturnNotPermitted {
say("")
say("This is a TCC denial. Grant Input Monitoring to the app running this")
say("binary (Terminal / your IDE) in System Settings > Privacy & Security >")
say("Input Monitoring, then re-run.")
}
exit(1)
}
say("opened")
// The mouse may be in BLE low-power sleep; the first exchange often wakes it.
header("Protocol handshake")
var version: (major: UInt8, minor: UInt8)?
for attempt in 1...4 {
do {
version = try hidpp.ping()
break
} catch {
say("attempt \(attempt) via device index 0x\(String(format: "%02x", gDeviceIndex)): \(explain(error))")
// Fall back to receiver-style addressing if direct addressing is silent.
if attempt == 2 && gDeviceIndex == 0xFF {
gDeviceIndex = 0x01
say("retrying with device index 0x01 (receiver-style addressing)")
}
}
}
guard let version else {
say("")
say("No HID++ response. Move the mouse to wake it and re-run.")
exit(1)
}
say("HID++ \(version.major).\(version.minor) on device index 0x\(String(format: "%02x", gDeviceIndex))")
if let inBuf = hidpp.sawReportIDInBuffer {
say("wire format: input buffer \(inBuf ? "includes" : "omits") the report ID byte")
}
// MARK: Feature enumeration
header("Feature table")
var featureIndexByID: [UInt16: UInt8] = [0x0000: 0x00]
do {
let fs = try hidpp.featureIndex(of: 0x0001)
featureIndexByID[0x0001] = fs.index
let countReply = try hidpp.call(feature: fs.index, function: 0x00)
let count = countReply.first ?? 0
say("\(count) features (excluding root)")
say("")
say(" idx id ver flags name")
for i in 1...max(1, count) {
guard let info = try? hidpp.call(feature: fs.index, function: 0x01, params: [i]),
info.count >= 3
else { continue }
let id = UInt16(info[0]) << 8 | UInt16(info[1])
if id == 0 { continue }
featureIndexByID[id] = i
let type = info[2]
let ver = info.count > 3 ? info[3] : 0
var flags: [String] = []
if type & 0x80 != 0 { flags.append("obsolete") }
if type & 0x40 != 0 { flags.append("hidden") }
if type & 0x20 != 0 { flags.append("engineering") }
let flagStr = flags.isEmpty ? "-" : flags.joined(separator: ",")
say(String(
format: " %3d 0x%04x %-3d %-8@ %@",
Int(i), Int(id), Int(ver), flagStr as NSString, featureName(id) as NSString))
}
} catch {
say("feature enumeration failed: \(explain(error))")
}
// MARK: Whitelisted getters
/// Every entry here is a documented read-only function. Nothing else is called.
struct Getter {
let feature: UInt16
let function: UInt8
let params: [UInt8]
let label: String
let decode: ([UInt8]) -> [String]
}
let getters: [Getter] = [
Getter(feature: 0x1000, function: 0x00, params: [], label: "Battery Status") {
[describeBatteryStatus($0)]
},
Getter(feature: 0x1004, function: 0x01, params: [], label: "Unified Battery") {
[describeUnifiedBattery($0)]
},
Getter(feature: 0x2110, function: 0x00, params: [], label: "SmartShift") {
describeSmartShift($0, enhanced: false)
},
Getter(feature: 0x2111, function: 0x00, params: [], label: "SmartShift Enhanced — capabilities") {
_ in []
},
Getter(feature: 0x2111, function: 0x01, params: [], label: "SmartShift Enhanced — ratchet control") {
describeSmartShift($0, enhanced: true)
},
Getter(feature: 0x2121, function: 0x00, params: [], label: "Hi-Res Wheel — capability") {
$0.count >= 2
? ["multiplier: \($0[0])", "capability flags: 0x\(String(format: "%02x", $0[1]))"]
: ["raw: \(hex($0))"]
},
Getter(feature: 0x2121, function: 0x01, params: [], label: "Hi-Res Wheel — mode") {
describeHiResWheelMode($0)
},
Getter(feature: 0x2150, function: 0x00, params: [], label: "Thumb Wheel — capability") {
_ in []
},
Getter(feature: 0x2201, function: 0x00, params: [], label: "Adjustable DPI — sensor count") {
["sensors: \($0.first.map(String.init) ?? "?")"]
},
Getter(feature: 0x2201, function: 0x02, params: [0x00], label: "Adjustable DPI — current") {
[describeDPI($0)]
},
Getter(feature: 0x8060, function: 0x01, params: [], label: "Report Rate") {
$0.count >= 1 ? ["\($0[0]) ms interval"] : ["raw: \(hex($0))"]
},
Getter(feature: 0x1b04, function: 0x00, params: [], label: "Reprogrammable Controls — count") {
["controls: \($0.first.map(String.init) ?? "?")"]
},
]
header("Device state (read-only)")
for g in getters {
guard let idx = featureIndexByID[g.feature] else { continue }
say("")
say("\u{001B}[1m\(g.label)\u{001B}[0m [0x\(String(format: "%04x", g.feature)) @ idx \(idx)]")
do {
let r = try hidpp.call(feature: idx, function: g.function, params: g.params)
for line in g.decode(r) { say(" \(line)") }
say(" raw: \(hex(r))")
} catch {
say(" \(explain(error))")
}
}
// MARK: Reprogrammable controls
if let idx = featureIndexByID[0x1b04],
let countReply = try? hidpp.call(feature: idx, function: 0x00),
let count = countReply.first, count > 0
{
header("Reprogrammable controls (0x1b04)")
say(" cid task name capabilities")
for i in 0..<count {
guard let r = try? hidpp.call(feature: idx, function: 0x01, params: [i]), r.count >= 9
else { continue }
let cid = UInt16(r[0]) << 8 | UInt16(r[1])
let tid = UInt16(r[2]) << 8 | UInt16(r[3])
let flags = r[4]
let extra = r[8]
var caps: [String] = []
if flags & 0x01 != 0 { caps.append("mouse-btn") }
if flags & 0x10 != 0 { caps.append("remappable") }
if flags & 0x20 != 0 { caps.append("divertable") }
if flags & 0x40 != 0 { caps.append("persist-divert") }
if flags & 0x80 != 0 { caps.append("virtual") }
// `extra` is the high byte of a 16-bit flag field: raw_XY=0x0100,
// force_raw_XY=0x0200, analytics_key_events=0x0400.
if extra & 0x01 != 0 { caps.append("raw-xy") }
if extra & 0x02 != 0 { caps.append("force-raw-xy") }
if extra & 0x04 != 0 { caps.append("analytics") }
let name = (controlNames[cid] ?? "unknown").padding(
toLength: 32, withPad: " ", startingAt: 0)
say(String(format: " 0x%04x 0x%04x ", Int(cid), Int(tid))
+ name + caps.joined(separator: ","))
say(" raw: \(hex(Array(r.prefix(9))))")
}
}
header("Done — no device state was modified")