You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中用IOKit读取罗技G Pro Wireless电池电压遇错误0xe0005000求助

解决Swift读取罗技G Pro Wireless电池状态的IOKit错误问题

问题概述

尝试用Swift读取罗技G Pro Wireless鼠标电池状态,使用USBDeviceSwift库简化HID设备操作,但调用IOHIDDeviceGetReport时始终返回未定义错误码0xe0005000,调用IOHIDDeviceSetReport也出现相同错误。

错误原因与解决方案

1. 错误码解析

0xe0005000对应kIOReturnNotAuthorized,核心原因是设备访问权限不足——macOS对HID/USB设备有严格的权限管控,尤其是沙箱环境下的应用。

2. 权限配置修复

  • Info.plist添加权限描述:
    在项目的Info.plist中添加以下配置,明确设备访问的用途:
    <key>NSHumanReadableUsageDescription</key>
    <string>需要访问罗技鼠标以读取电池状态</string>
    <key>com.apple.security.device.hid</key>
    <true/>
    
  • 沙箱权限配置:
    打开项目的Signing & Capabilities面板,在App Sandbox中勾选Hardware分类下的USB权限;若手动配置,添加:
    <key>com.apple.security.device.usb</key>
    <true/>
    

3. 确保设备已正确打开

USBDeviceSwift库可能未自动打开设备,需在设备连接时手动调用IOHIDDeviceOpen:

@objc func usbConnected(notification: NSNotification) {
    guard let nobj = notification.object as? NSDictionary else { return }
    guard let deviceInfo: HIDDevice = nobj["device"] as? HIDDevice else { return }
    
    // 手动打开设备
    let openResult = IOHIDDeviceOpen(deviceInfo.device, kIOHIDOptionsTypeNone)
    if openResult != kIOReturnSuccess {
        print("设备打开失败: \(openResult)")
        return
    }
    
    self.deviceInfo = deviceInfo
    write()
}

4. 修正Report数据格式

罗技G Pro Wireless的电池查询短消息应为7字节,原代码payload少1字节,需补充:

func write() {
    // 修正为7字节的查询消息
    let payload: [UInt8] = [
        0x10, // Report ID: 短消息标识
        0xff, // 接收器索引
        0x06, // 特征索引:电池电压
        0x00, 0x00, 0x00, 0x00 // 补充空字节至7字节
    ]
    
    var reportData = Data(payload)
    var reportLength = reportData.count
    
    let ret = IOHIDDeviceGetReport(
        self.deviceInfo.device,
        kIOHIDReportTypeFeature,
        CFIndex(0x10),
        &reportData,
        &reportLength
    )
    
    print("返回码: \(ret)")
    print("返回数据: \([UInt8](reportData))")
}

额外验证点

  • 确认设备PID是否正确:罗技G Pro Wireless的接收器PID通常是0xC539,鼠标本体PID为0xC088,若直接连接鼠标本体需切换PID。
  • 检查HIDDeviceMonitor的reportSize是否匹配设备的Report描述符,可通过IOHIDDeviceGetReportDescriptor获取设备的Report结构信息。

内容的提问来源于stack exchange,提问作者Oschły

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:05:29