diff --git a/.changeset/instant-limit-and-cable-through-cut.md b/.changeset/instant-limit-and-cable-through-cut.md new file mode 100644 index 0000000..2539f58 --- /dev/null +++ b/.changeset/instant-limit-and-cable-through-cut.md @@ -0,0 +1,5 @@ +--- +"ewiz": patch +--- + +**Switching the charge limit on stops charging at once, and the cable no longer reads as unplugged while the battery runs down to the limit.** On Macs that limit through macOS's own charge limit, macOS took about 40 seconds to act after the limit was set, so the battery kept charging past it and the panel said "Charging". eWiz now cuts the adapter for that gap: charging stops in about a second, and macOS's limit takes over within 90 seconds. On these Macs, an adapter cut (eWiz's, or macOS's own while it drains to the limit) also looked exactly like pulling the cable, so the panel said "On battery" and a hold could play the unplug sound. eWiz now reads the cable from the charger's own "can charge" signal, which only a real unplug clears. diff --git a/Sources/EWizKit/BatteryMonitor.swift b/Sources/EWizKit/BatteryMonitor.swift index 6af4c0c..f7608cf 100644 --- a/Sources/EWizKit/BatteryMonitor.swift +++ b/Sources/EWizKit/BatteryMonitor.swift @@ -104,6 +104,18 @@ public enum BatteryMonitor { flag || (cableIn && !full && amperage >= chargingCurrentFloor) } + /// Whether the cable is physically in. + /// + /// `ExternalConnected` alone isn't it. On Macs that limit through macOS's own charge + /// limit, an adapter cut (macOS running the battery down to its limit, or eWiz standing + /// in for it) clears `ExternalConnected` exactly as a pull does, and the app said "On + /// battery" over a cable that was in. Traced on such a Mac: through a cut + /// `ExternalChargeCapable` stays Yes; on a real unplug both go No in the same sample. + /// The adapter's details are no help here, as they linger for a second after a pull. + public static func cablePresent(externalConnected: Bool, chargeCapable: Bool?) -> Bool { + externalConnected || chargeCapable == true + } + // MARK: - AppleSmartBattery (hardware detail) private static func readSmartBattery(into snap: inout BatterySnapshot) { @@ -121,7 +133,8 @@ public enum BatteryMonitor { // Physical adapter presence — true even while force-discharging, unlike the // providing-source flag. Overrides the baseline. if let ext = props["ExternalConnected"] as? Bool { - snap.isExternalConnected = ext + snap.isExternalConnected = Self.cablePresent( + externalConnected: ext, chargeCapable: props["ExternalChargeCapable"] as? Bool) } // Signed mA, positive into the battery. CFNumber keeps the sign; the ioreg text diff --git a/Sources/EWizKit/Control.swift b/Sources/EWizKit/Control.swift index e11b353..cf11dec 100644 --- a/Sources/EWizKit/Control.swift +++ b/Sources/EWizKit/Control.swift @@ -141,6 +141,10 @@ public struct ControlResponse: Codable, Sendable { /// so without one it can do nothing. An older daemon omits it and reads as true, which /// is what it would have claimed anyway. public var chargeControlSupported: Bool + /// The adapter is physically there, from the SMC (`AC-W`), nil where the key is missing + /// or the daemon predates it. Unlike IORegistry's `ExternalConnected` it survives the + /// helper cutting the adapter, which on some Macs reads exactly like an unplug. + public var adapterPresent: Bool? = nil public var message: String? /// Protocol version of the responding daemon. Older daemons omit it → decode to 0 → outdated. public var daemonProtocolVersion: Int @@ -214,6 +218,7 @@ public struct ControlResponse: Codable, Sendable { nativeLimitSteps = try c.decodeIfPresent([Int].self, forKey: .nativeLimitSteps) ?? [] nativeLimitApplied = try c.decodeIfPresent(Int.self, forKey: .nativeLimitApplied) chargeControlSupported = try c.decodeIfPresent(Bool.self, forKey: .chargeControlSupported) ?? true + adapterPresent = try c.decodeIfPresent(Bool.self, forKey: .adapterPresent) message = try c.decodeIfPresent(String.self, forKey: .message) daemonProtocolVersion = try c.decodeIfPresent(Int.self, forKey: .daemonProtocolVersion) ?? 0 daemonBuildVersion = try c.decodeIfPresent(Int.self, forKey: .daemonBuildVersion) ?? 0 @@ -398,7 +403,11 @@ public enum HelperBuild { /// reporting "held" until its next tick. /// v31: charging is read from current flowing in, not only macOS's `IsCharging`, which /// trailed a plug-in by 23 s and had the MagSafe light go amber, green, amber. - public static let version = 31 + /// v32: switching a limit on stops the charge within a second. macOS takes ~40 s to act + /// on its own limit; the adapter stands in for up to 90 s until it has. + /// v33: the cable reads as in through an adapter cut (ExternalChargeCapable), where + /// ExternalConnected alone said unplugged. + public static let version = 33 } public enum ControlError: Error, CustomStringConvertible { diff --git a/Sources/eWiz/ChargeLimitStore.swift b/Sources/eWiz/ChargeLimitStore.swift index 5aa9d3b..f31f6fb 100644 --- a/Sources/eWiz/ChargeLimitStore.swift +++ b/Sources/eWiz/ChargeLimitStore.swift @@ -88,6 +88,8 @@ final class ChargeLimitStore: ObservableObject { @Published private(set) var sensors: [SensorReading] = [] @Published private(set) var dischargeSupported = false @Published private(set) var discharging = false + /// The helper's SMC reading of the adapter. See `ControlResponse.adapterPresent`. + @Published private(set) var adapterPresent: Bool? @Published var disableChargingBeforeSleep = false @Published var preventIdleSleep = false /// "Always Active": keep the Mac awake with the lid closed (on AC power). @@ -197,6 +199,16 @@ final class ChargeLimitStore: ObservableObject { } } + /// Read the helper's status now and wait for it, for a decision that needs it fresh. + /// Skipped, like `refresh`, while a write or a drag is in progress. + func refreshNow() async { + guard pendingWrites == 0, !isEditing else { return } + refreshSequence += 1 + let sequence = refreshSequence + let result = await Task.detached { try? ControlClient.send(.getStatus) }.value + ingestFromRefresh(result, sequence: sequence) + } + /// Issue order of status reads. Each runs on its own detached task, and with the /// helper's lock held for a pmset call a slow early answer could land after a quick /// later one and put the older state back until the next poll. @@ -522,7 +534,11 @@ final class ChargeLimitStore: ObservableObject { // The daemon's flag is only as fresh as the last 30 s poll. With the cable // physically out it can't be a cut adapter, so a stale `true` mustn't hold the // icon on "plugged in" after a real unplug. - discharging: discharging && snap.isExternalConnected, + // + // The cable test asks the SMC too, through the helper: on some Macs cutting the + // adapter clears `ExternalConnected` as if it were pulled, and the panel then + // said "On battery" over a cable that was in, mid-drain to the limit. + discharging: discharging && (snap.isExternalConnected || adapterPresent == true), isPaused: isPaused, calibrating: calibrating, chargePower: chargePower)) @@ -664,6 +680,25 @@ final class ChargeLimitStore: ObservableObject { command(.setPowerToggle(toggle, on)) } + private var adapterCutFollow: Task? + + /// Re-read every few seconds while the helper has the adapter cut. + /// + /// Through a cut the battery store has nothing to go on: the cable already reads as + /// out, so pulling it for real changes nothing IOKit reports, and only the helper (from + /// the SMC) can say when the cut ends or the cable went. The cut lasts a minute or two + /// at most, so the extra socket calls are bounded. + private func followWhileAdapterCut() { + guard discharging else { adapterCutFollow?.cancel(); adapterCutFollow = nil; return } + guard adapterCutFollow == nil else { return } + adapterCutFollow = Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: 3_000_000_000) + guard !Task.isCancelled, let self else { return } + self.adapterCutFollow = nil + self.refresh() + } + } + private var resumeRefresh: Task? /// Re-read just after a timed pause runs out, so the panel and the icon leave "paused" @@ -761,6 +796,8 @@ final class ChargeLimitStore: ObservableObject { set(\.sensors, r.sensors) set(\.dischargeSupported, r.dischargeSupported) set(\.discharging, r.discharging) + set(\.adapterPresent, r.adapterPresent) + followWhileAdapterCut() set(\.disableChargingBeforeSleep, r.config.disableChargingBeforeSleep) set(\.preventIdleSleep, r.config.preventIdleSleep) set(\.keepAwake, r.config.keepAwake) diff --git a/Sources/eWiz/EWizApp.swift b/Sources/eWiz/EWizApp.swift index 284b832..6c48e0b 100644 --- a/Sources/eWiz/EWizApp.swift +++ b/Sources/eWiz/EWizApp.swift @@ -309,20 +309,17 @@ struct MenuBarLabel: View { // guard only caught one direction (and only once the 30 s poll had seen the cut). .onChange(of: snap.isExternalConnected) { was, isNow in guard was != isNow else { return } - if settings.hapticsEnabled { - isNow ? HapticFeedback.chargeConnected() : HapticFeedback.chargeDisconnected() + // On some Macs the helper cutting or restoring the adapter flips this exactly as + // a pull would, so ask the helper's SMC reading before saying anything. Present + // before and after means the cable never moved. No reading (an older helper, a + // Mac without the key) keeps the old behaviour. + let before = chargeLimit.adapterPresent + let percentage = snap.percentage + Task { @MainActor in + await chargeLimit.refreshNow() + if before == true, chargeLimit.adapterPresent == true { return } + cableFeedback(isNow, percentage: percentage) } - if settings.soundAllowed { - ChargeSound.play(isNow ? .connect : .disconnect, volume: settings.soundVolume, - theme: settings.soundTheme) - } - guard ChargeOverlayFeature.shipped, settings.chargeOverlayEnabled, - isNow || settings.chargeOverlayOnUnplug else { return } - overlay.show(style: settings.chargeOverlayStyle, - duration: settings.chargeOverlayDuration, - percentage: snap.percentage, - plugging: isNow, - allowMotion: settings.motionAllowed) } // A real plug or unplug changes what the helper is doing (hold, drain, pause), and // its state otherwise waits for the 30 s poll — the icon lagged up to ~45 s behind @@ -337,6 +334,24 @@ struct MenuBarLabel: View { .onChange(of: snap.isCharging) { _, _ in refreshChargeStatusSoon() } } + /// The plug / unplug cue: haptic, sound and overlay. + private func cableFeedback(_ isNow: Bool, percentage: Int) { + if settings.hapticsEnabled { + isNow ? HapticFeedback.chargeConnected() : HapticFeedback.chargeDisconnected() + } + if settings.soundAllowed { + ChargeSound.play(isNow ? .connect : .disconnect, volume: settings.soundVolume, + theme: settings.soundTheme) + } + guard ChargeOverlayFeature.shipped, settings.chargeOverlayEnabled, + isNow || settings.chargeOverlayOnUnplug else { return } + overlay.show(style: settings.chargeOverlayStyle, + duration: settings.chargeOverlayDuration, + percentage: percentage, + plugging: isNow, + allowMotion: settings.motionAllowed) + } + /// One burst of helper re-reads, restarted rather than stacked: a single plug flips the /// cable, the source and the charging flag a moment apart, and each used to start its /// own burst — a dozen status calls in ten seconds. 15 s is past the helper's own diff --git a/Sources/ewiz-helper/Daemon.swift b/Sources/ewiz-helper/Daemon.swift index d2b014c..4060d32 100644 --- a/Sources/ewiz-helper/Daemon.swift +++ b/Sources/ewiz-helper/Daemon.swift @@ -100,6 +100,12 @@ final class Daemon: @unchecked Sendable { /// Plugged in, not taking charge, because the native limit says so. What the app is /// told as "held", since there's no SMC flag on this Mac to report instead. private var nativeHolding = false + /// Until when the adapter stands in for a macOS limit that was just set. See + /// `nativeBridgeWanted`. + private var nativeBridgeUntil: Date? + /// How long macOS gets to act on its own limit before the stand-in steps back. Traced at + /// 42 s from the limit being set to current stopping; 90 covers a slow PowerUIAgent. + private let nativeBridgeWindow: TimeInterval = 90 /// On the cable but running off the battery, because the battery is above the step /// macOS is holding and macOS brings it down. `pmset` says "AC attached; not charging" /// throughout, so without this the app would show a draining battery as "held". @@ -501,7 +507,7 @@ final class Daemon: @unchecked Sendable { private func status(ok: Bool, message: String? = nil) -> ControlResponse { let snap = BatteryMonitor.read() let pmset = pmsetState() - return ControlResponse( + var response = ControlResponse( ok: ok, config: ConfigStore.load(), batteryPercent: snap.percentage, @@ -525,6 +531,8 @@ final class Daemon: @unchecked Sendable { chargeControlSupported: chargeControlSupported, message: message ) + response.adapterPresent = charge.isACPresent() + return response } private static func failureResponse() -> ControlResponse { @@ -1155,15 +1163,18 @@ final class Daemon: @unchecked Sendable { // Gate on onExternalPower, NOT isPluggedIn: cutting the adapter makes macOS report // "Battery Power", so isPluggedIn would flip false next tick and we'd restore the // adapter — oscillating instead of draining. onExternalPower stays true while the cable is in. + let bridge = nativeBridgeWanted(cfg, snap) let shouldDischarge = snap.onExternalPower - && (limitDischarge || scheduleDischarge || adapterHold) + && (limitDischarge || scheduleDischarge || adapterHold || bridge) let adapterOn = (try? charge.isAdapterEnabled()) ?? true var cut = !adapterOn if shouldDischarge { if adapterOn { if (try? charge.disableAdapter()) != nil { cut = true } - log(adapterHold && !limitDischarge && !scheduleDischarge + log(bridge && !limitDischarge && !scheduleDischarge + ? "macOS limit set; adapter off until macOS stops the charge itself" + : adapterHold && !limitDischarge && !scheduleDischarge ? "hold: on the battery at \(snap.percentage)%, adapter back at \((holdAnchor ?? cfg.chargeLimit) - adapterHoldBand)%" : "discharging to limit") } @@ -1177,6 +1188,28 @@ final class Daemon: @unchecked Sendable { } } + /// Whether the adapter should stand in for a macOS limit that hasn't bitten yet. + /// + /// macOS acts on its own limit in its own time: traced at 42 s from setting 80% at 89% + /// to current stopping. Through that gap the battery kept charging past the limit the + /// user had just switched on, and the panel truthfully said "Charging", which read as + /// the switch not working. Cutting the adapter stops the charge within a second, and + /// it is the same state macOS's limit arrives at above its mark (running down to it + /// with the cable in). Once macOS has had `nativeBridgeWindow` to take over, the + /// adapter comes back and its limit holds from there. + /// + /// Only above the mark, only while charging would otherwise run, and never for + /// calibration, which means to charge past it. Caller holds `lock`. + private func nativeBridgeWanted(_ cfg: EWizConfig, _ snap: BatterySnapshot) -> Bool { + guard let until = nativeBridgeUntil else { return false } + guard Date() < until, let mark = nativeApplied, !cfg.calibrateToFull, + snap.percentage >= mark else { + nativeBridgeUntil = nil + return false + } + return true + } + /// The level "don't charge" was thrown at, on a Mac with no charge-inhibit key. /// /// Anchored the first time it's seen on the charger, and kept across an unplug: the @@ -1246,6 +1279,7 @@ final class Daemon: @unchecked Sendable { if native.set(want) { nativeApplied = want NativeChargeLimitOwnership.save(want) + nativeBridgeUntil = now.addingTimeInterval(nativeBridgeWindow) log("macOS charge limit set to \(want)%") } else { err("macOS refused a charge limit of \(want)%") diff --git a/Tests/EWizKitTests/PowerFlowTests.swift b/Tests/EWizKitTests/PowerFlowTests.swift index 62bb3bf..61d4e1c 100644 --- a/Tests/EWizKitTests/PowerFlowTests.swift +++ b/Tests/EWizKitTests/PowerFlowTests.swift @@ -78,3 +78,22 @@ struct ChargingFromCurrentTests { #expect(BatteryMonitor.isCharging(flag: true, amperage: -500, cableIn: true, full: false)) } } + +@Suite("Cable presence through an adapter cut") +struct CablePresenceTests { + @Test("a cut that clears ExternalConnected is still a cable in") + func cutIsNotAnUnplug() { + #expect(BatteryMonitor.cablePresent(externalConnected: false, chargeCapable: true)) + } + + @Test("a real unplug clears both") + func unplug() { + #expect(!BatteryMonitor.cablePresent(externalConnected: false, chargeCapable: false)) + #expect(!BatteryMonitor.cablePresent(externalConnected: false, chargeCapable: nil)) + } + + @Test("connected is connected") + func connected() { + #expect(BatteryMonitor.cablePresent(externalConnected: true, chargeCapable: false)) + } +}