feat(power): 展示电池实际充放电功率并及时响应电源切换

保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
This commit is contained in:
2026-11-15 23:54:19 +08:00
parent 1595af6d13
commit 4b8deb2e48
31 changed files with 739 additions and 119 deletions
+17 -3
View File
@@ -1,7 +1,7 @@
import Foundation
import IOKit
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system power keys; never write keys.
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system and battery power keys; never write keys.
nonisolated final class CPUTemperatureMonitor {
static let highTemperatureThreshold = 90.0
@@ -105,9 +105,21 @@ nonisolated final class CPUTemperatureMonitor {
return watts
}
private func readNumber(_ key: UInt32) -> Double? {
/// B0AP on Apple Silicon is a signed, little-endian milliwatt reading at the battery.
func sampleBatteryPower() -> Double? {
#if arch(arm64)
guard openConnection(), let milliwatts = readNumber(0x42304150, expectedType: 0x73693332),
abs(milliwatts) <= 500_000 else { return nil }
return milliwatts / 1000
#else
return nil
#endif
}
private func readNumber(_ key: UInt32, expectedType: UInt32? = nil) -> Double? {
var request = Request(); request.key = key; request.command = 9
guard let metadata = call(&request), metadata.info.size <= 32 else { return nil }
guard let metadata = call(&request), metadata.info.size <= 32,
expectedType == nil || metadata.info.type == expectedType else { return nil }
request.command = 5; request.info.size = metadata.info.size
guard let response = call(&request) else { return nil }
let bytes = withUnsafeBytes(of: response.bytes) { Array($0.prefix(Int(metadata.info.size))) }
@@ -116,6 +128,8 @@ nonisolated final class CPUTemperatureMonitor {
static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? {
switch (type, bytes.count) {
case (0x73693332, 4): // si32, little-endian signed integer
return Double(bytes.withUnsafeBytes { Int32(littleEndian: $0.loadUnaligned(as: Int32.self)) })
case (0x666c7420, 4): // flt, little-endian IEEE754
let bits = UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24
let value = Double(Float(bitPattern: bits))