如何通过AppleScript获取全部已连接蓝牙设备的电池电量?
如何获取所有已连接蓝牙设备的电池电量(macOS Ventura)
问题原因
你的现有脚本仅查询了BatteryPercent键,这是苹果自有蓝牙设备(Magic Mouse/Keyboard等)使用的电量标识,但第三方蓝牙设备(如i12耳机)通常使用其他键存储电量,比如BluetoothBatteryLevel,且设备名称的字段也可能不同(苹果设备用Product,第三方可能用Name)。
解决方案
方案1:扩展ioreg查询逻辑(无需额外工具)
修改脚本,同时查询苹果设备和第三方设备的电量键,并适配不同的设备名称字段:
set batteryInfo to do shell script "ioreg -r -l -k 'BatteryPercent' -k 'BluetoothBatteryLevel'" set deviceList to paragraphs of batteryInfo set currentDevice to "" set currentBatteryLevel to "" set batteryInfo to "" repeat with a in deviceList -- 匹配设备名称:处理苹果设备的Product字段和第三方设备的Name字段 if (a contains "Product" and a does not contain "ProductID") or a contains "\"Name\"" then if a contains "Product" then set currentDevice to text ((offset of "=" in a) + 3) through -2 of a else set currentDevice to text ((offset of "\"Name\" = " in a) + 8) through -2 of a end if end if -- 处理不同的电量字段 if a contains "BatteryPercent" then set currentBatteryLevel to text ((offset of "=" in a) + 2) through -1 of a set batteryInfo to batteryInfo & currentDevice & ": " & currentBatteryLevel & "%\n" else if a contains "BluetoothBatteryLevel" then -- 第三方设备的BluetoothBatteryLevel值为0-255,转换为百分比 set rawLevel to text ((offset of "=" in a) + 2) through -1 of a as integer set currentBatteryLevel to round (rawLevel / 2.55) rounding nearest set batteryInfo to batteryInfo & currentDevice & ": " & currentBatteryLevel & "%\n" end if end repeat if (length of batteryInfo) > 0 then set batteryInfo to text 1 through -2 of batteryInfo end if return batteryInfo
方案2:使用system_profiler(更稳定的设备信息输出)
system_profiler是系统自带工具,能输出所有蓝牙设备的标准化信息,包括电量。通过结合Python解析其JSON输出,可以更可靠地获取数据:
set bluetoothJson to do shell script "system_profiler SPBluetoothDataType -json" set batteryReport to do shell script "python3 -c ' import json, sys data = json.load(sys.stdin) # 定位蓝牙设备列表(Ventura版本的JSON结构) devices = data[\"SPBluetoothDataType\"][0][\"devices\"] result = [] for dev in devices: name = dev.get(\"name\", \"未知设备\") # 处理不同的电量字段 if \"batteryPercent\" in dev: result.append(f\"{name}: {dev[\"batteryPercent\"]}%\") elif \"batteryLevel\" in dev: # 部分设备用0-1的小数表示电量 percent = round(dev[\"batteryLevel\"] * 100) result.append(f\"{name}: {percent}%\") print(\"\\n\".join(result)) ' <<< " & quoted form of bluetoothJson return batteryReport
补充说明
如果上述脚本仍无法捕获特定设备的电量,可以通过以下命令查看该设备的电量键名:
ioreg -r -l | grep -A 20 -B 5 "i12"
在输出中查找包含“battery”或“Battery”的字段,然后将对应的键名添加到脚本的查询逻辑中。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

