52 lines
2.1 KiB
Swift
52 lines
2.1 KiB
Swift
import Foundation
|
|
|
|
nonisolated struct PowerReading: Sendable, Equatable {
|
|
enum Source: Sendable { case smc, telemetry, instantaneous, average, balance }
|
|
let watts: Double
|
|
var source: Source = .telemetry
|
|
}
|
|
|
|
nonisolated struct BatteryPowerFlow: Sendable {
|
|
var connected: Bool?
|
|
var externalSupply: Bool?
|
|
var charging: Bool?
|
|
var battery: PowerReading?
|
|
var input: PowerReading?
|
|
var load: PowerReading?
|
|
var adapterCapacity: Double?
|
|
|
|
mutating func applyBatterySensor(_ watts: Double) {
|
|
// The gauge may still report the last charging sample just after unplugging.
|
|
guard watts <= 0 || (externalSupply != false && connected != false) else { return }
|
|
battery = PowerReading(watts: watts, source: .smc)
|
|
// Estimates made from older registry measurements no longer share a sampling window.
|
|
if load?.source == .balance { load = nil }
|
|
if input?.source == .balance { input = nil }
|
|
if connected == false, load == nil, watts < 0 {
|
|
load = PowerReading(watts: -watts, source: .balance)
|
|
}
|
|
}
|
|
|
|
enum State: Sendable {
|
|
case charging, combined, battery, discharging, external, unknown
|
|
}
|
|
|
|
var state: State {
|
|
if let battery {
|
|
// Differences of two sensors are less precise than a battery-terminal reading.
|
|
let threshold = battery.source == .balance ? 0.5 : 0.05
|
|
if battery.watts >= threshold { return .charging }
|
|
if battery.watts <= -threshold {
|
|
if connected == true, let input, input.source != .balance, input.watts >= 0.05 { return .combined }
|
|
if connected == false || externalSupply == false || input?.watts == 0 { return .battery }
|
|
return .discharging
|
|
}
|
|
}
|
|
if battery == nil, charging == true, connected != false, externalSupply != false { return .charging }
|
|
if externalSupply == false { return .battery }
|
|
if externalSupply == true || (input?.watts ?? 0) > 0 { return .external }
|
|
if connected == false { return .battery }
|
|
return .unknown
|
|
}
|
|
}
|