import Foundation import IOKit.ps nonisolated struct BatteryMetrics: Sendable { let charge: Double? let charging: Bool let externalPower: Bool var power: Double? = nil var minutesRemaining: Int? var cycles: Int? var health: Double? } nonisolated enum BatteryMonitor { static func normalizedPower(voltageMillivolts: Double?, amperageMilliamps: Double?) -> Double? { guard let voltageMillivolts, let amperageMilliamps, voltageMillivolts.isFinite, amperageMilliamps.isFinite, voltageMillivolts > 0, voltageMillivolts <= 30_000, abs(amperageMilliamps) <= 20_000 else { return nil } let watts = abs(voltageMillivolts * amperageMilliamps) / 1_000_000 return watts.isFinite && watts <= 500 ? watts : nil } static func positiveMinutes(_ value: Int?) -> Int? { value.flatMap { $0 > 0 ? $0 : nil } } static func estimatedMinutes(charging: Bool, externalPower: Bool, sourceMinutes: Int?, systemSeconds: Double) -> Int? { guard charging || !externalPower else { return nil } if let minutes = positiveMinutes(sourceMinutes) { return minutes } // The global estimate applies to discharge only and reports seconds. guard !charging, !externalPower, systemSeconds.isFinite, systemSeconds > 0, systemSeconds < Double(Int.max) else { return nil } return max(1, Int((systemSeconds / 60).rounded(.up))) } static func availability() -> BatteryAvailability { guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return .failed } for source in sources { guard let item = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any] else { return .failed } if item[kIOPSTypeKey] as? String == kIOPSInternalBatteryType { return .present } } return .absent } static func sample() -> BatteryMetrics? { guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil } for source in sources { guard let item = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any], item[kIOPSTypeKey] as? String == kIOPSInternalBatteryType else { continue } let current = item[kIOPSCurrentCapacityKey] as? Double let maximum = item[kIOPSMaxCapacityKey] as? Double let charge = current.flatMap { c in maximum.flatMap { $0 > 0 ? min(1, max(0, c / $0)) : nil } } let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery")) var properties: [String: Any] = [:] if service != 0 { defer { IOObjectRelease(service) } var raw: Unmanaged? if IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS { properties = raw?.takeRetainedValue() as? [String: Any] ?? [:] } } let charging = item[kIOPSIsChargingKey] as? Bool ?? false let external = item[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue let minutes = charging ? item[kIOPSTimeToFullChargeKey] as? Int : external ? nil : item[kIOPSTimeToEmptyKey] as? Int let batteryData = properties["BatteryData"] as? [String: Any] ?? [:] let voltage = firstNumber([properties["Voltage"], batteryData["Voltage"], batteryData["AppleRawBatteryVoltage"]]) let amperage = firstNumber([properties["InstantAmperage"], batteryData["InstantAmperage"], properties["Amperage"], batteryData["Amperage"]]) return BatteryMetrics(charge: charge, charging: item[kIOPSIsChargingKey] as? Bool ?? false, externalPower: external, power: normalizedPower(voltageMillivolts: voltage, amperageMilliamps: amperage), minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()), cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil }) } return nil } private static func firstNumber(_ values: [Any?]) -> Double? { for case let value? in values { if let number = value as? NSNumber, number.doubleValue.isFinite { return number.doubleValue } } return nil } }