diff --git a/README.md b/README.md index 72f132c..0c071c5 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,8 @@ dynamo off # let macOS manage charging again Dynamo has two parts: -- **`dynamo daemon`**, a small root service run by launchd. Every 5 seconds it reads the +- **`dynamo daemon`**, a small root service run by launchd. Every 5 seconds on power + (30 on battery, and at once when you plug in or change a setting) it reads the battery and sets the Mac's SMC charging controls: `CHTE` (charging on/off), `CHIE` (adapter on/off, for discharging) and `ACLC` (MagSafe LED). On older firmware it falls back to `CH0B`/`CH0C` and `CH0I`. When the service stops, it always turns charging back on. diff --git a/Sources/App/Model.swift b/Sources/App/Model.swift index d358661..cd959ac 100644 --- a/Sources/App/Model.swift +++ b/Sources/App/Model.swift @@ -73,11 +73,11 @@ final class Model: ObservableObject { /// Live numbers every 3 s while the panel is open. While it's closed only the menu /// bar icon needs them and battery changes arrive as notifications, so a slow poll - /// for the daemon's status is enough; it stays well inside DaemonStatus.isFresh's - /// 60 s even with the daemon's 20 s heartbeat. The tolerance lets macOS batch wakeups. + /// for the daemon's status (task finished, adapter paused) is enough. The tolerance + /// lets macOS batch wakeups. private func startTimer() { timer?.invalidate() - let interval: TimeInterval = panelVisible ? 3 : 20 + let interval: TimeInterval = panelVisible ? 3 : 60 timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in Task { @MainActor in self?.refresh() } } @@ -98,7 +98,8 @@ final class Model: ObservableObject { func refresh() { guard !frozen else { return } - battery = BatteryInfo.read() + // The closed panel's menu bar icon needs only the essentials (opening it refreshes). + battery = BatteryInfo.read(essentialsOnly: !panelVisible) status = DaemonStatus.load() if panelVisible { energyApps = energy.sample() } installed = Config.exists diff --git a/Sources/Daemon/Daemon.swift b/Sources/Daemon/Daemon.swift index e740d58..c214c35 100644 --- a/Sources/Daemon/Daemon.swift +++ b/Sources/Daemon/Daemon.swift @@ -1,4 +1,5 @@ import Foundation +import IOKit.ps import IOKit.pwr_mgt func log(_ msg: String) { @@ -40,6 +41,11 @@ final class Daemon { private var asleepSince: Date? private var timer: Timer? private var signalSources: [DispatchSourceSignal] = [] + /// Modification time and size of the config last parsed, to skip unchanged reads. + private var configStamp: (mtime: timespec, size: off_t)? + private var configWatch: DispatchSourceFileSystemObject? + private var pendingConfigCheck: DispatchWorkItem? + private var pluggedIn: Bool? init() { state.wasInhibited = ChargeControl.chargingInhibited ?? false @@ -62,21 +68,80 @@ final class Daemon { } registerForSleep() - timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in self?.tick() } - timer?.tolerance = 1 // lets macOS coalesce the wakeup with others + watchPower() + schedule(pluggedIn: true) tick() RunLoop.main.run() exit(0) } + /// Every 5 s on power, where charging must stop right at the limit. On battery + /// nothing charges, so every 30 s is plenty; plugging in or unplugging and setting + /// changes trigger a check at once (watchPower, watchConfig). + private func schedule(pluggedIn: Bool) { + let interval: TimeInterval = pluggedIn ? 5 : 30 + guard timer?.timeInterval != interval else { return } + timer?.invalidate() + timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in self?.tick() } + timer?.tolerance = interval / 5 // lets macOS coalesce the wakeup with others + } + + /// Checks right away when the adapter is connected or disconnected. macOS posts + /// power source changes about once a minute on battery as well, so only a change + /// in ExternalConnected leads to a full check. + private func watchPower() { + let ctx = Unmanaged.passUnretained(self).toOpaque() + guard let src = IOPSNotificationCreateRunLoopSource({ ctx in + guard let ctx else { return } + let daemon = Unmanaged.fromOpaque(ctx).takeUnretainedValue() + let now = BatteryInfo.read(essentialsOnly: true)?.pluggedIn + if now != nil && now != daemon.pluggedIn { daemon.tick() } + }, ctx)?.takeRetainedValue() else { + log("warning: no power source notifications; plugging in is noticed at the next check") + return + } + CFRunLoopAddSource(CFRunLoopGetMain(), src, .defaultMode) + } + + /// Applies a change from the app or CLI right away, not at the next check (up to + /// 30 s on battery). Config is saved in place, so the file itself can be watched; + /// if it's ever replaced, the next check watches the new one. + private func watchConfig() { + let fd = open(Paths.config, O_EVTONLY) + guard fd >= 0 else { return } + let src = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: [.write, .extend, .delete, .rename], + queue: .main) + src.setEventHandler { [weak self, weak src] in + guard let self, let src else { return } + if !src.data.isDisjoint(with: [.delete, .rename]) { + src.cancel() + self.configWatch = nil + } + // A save is a truncate then a write: let it finish, and check once. + self.pendingConfigCheck?.cancel() + let check = DispatchWorkItem { [weak self] in self?.tick() } + self.pendingConfigCheck = check + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: check) + } + src.setCancelHandler { close(fd) } + src.resume() + configWatch = src + } + /// The config, tolerating a half-written file: if the file exists but doesn't - /// parse, the app is mid-save, so keep using the last good copy. + /// parse, the app is mid-save, so keep using the last good copy. Parsed again + /// only when the file has changed. private func loadConfig() -> Config? { - if let c = Config.load() { - lastGoodConfig = c + var st = stat() + guard stat(Paths.config, &st) == 0 else { return nil } + if let c = lastGoodConfig, let s = configStamp, s.size == st.st_size, + s.mtime.tv_sec == st.st_mtimespec.tv_sec, s.mtime.tv_nsec == st.st_mtimespec.tv_nsec { return c } - return Config.exists ? lastGoodConfig : nil + guard let c = Config.load() else { return lastGoodConfig } + lastGoodConfig = c + configStamp = (st.st_mtimespec, st.st_size) + return c } func tick() { @@ -86,11 +151,14 @@ final class Daemon { guard Date().timeIntervalSince(since) > 60 else { return } asleepSince = nil } - guard let bat = BatteryInfo.read() else { + if configWatch == nil { watchConfig() } + guard let bat = BatteryInfo.read(essentialsOnly: true) else { writeStatus(mode: nil, reason: "Battery unreadable", error: "Could not read AppleSmartBattery", inhibited: ChargeControl.chargingInhibited, adapterDisabled: ChargeControl.adapterDisabled) return } + pluggedIn = bat.pluggedIn + schedule(pluggedIn: bat.pluggedIn) if History.record(bat, into: &history) { History.save(history) } guard var cfg = loadConfig()?.sanitized else { @@ -206,6 +274,10 @@ final class Daemon { || $0.calibration != s.calibration || $0.eventAt != s.eventAt } ?? true guard changed || Date().timeIntervalSince(lastStatusWrite) > 20 else { return } + lastStatusWrite = Date() + // Nothing new: touching the file is enough to show we're alive (readers count + // its date, see DaemonStatus.load), and costs a fraction of rewriting it. + if !changed && utimes(Paths.status, nil) == 0 { return } let enc = JSONEncoder() enc.dateEncodingStrategy = .iso8601 @@ -215,7 +287,6 @@ final class Daemon { chmod(Paths.status, 0o644) } lastStatus = s - lastStatusWrite = Date() } // MARK: Sleep / wake diff --git a/Sources/Daemon/main.swift b/Sources/Daemon/main.swift index a4f921b..8bc9f6d 100644 --- a/Sources/Daemon/main.swift +++ b/Sources/Daemon/main.swift @@ -138,7 +138,7 @@ case "lowpower": print(mode.apply() ? "Low Power Mode: \(mode.title)" : "pmset failed") } else { updateConfig { $0.lowPowerRequest = mode } - print("Requested Low Power Mode: \(mode.title) (applied within 5 s)") + print("Requested Low Power Mode: \(mode.title) (applied in a moment)") } case "restore": guard geteuid() == 0 else { fail("restore needs root: sudo dynamo restore") } diff --git a/Sources/Shared/Battery.swift b/Sources/Shared/Battery.swift index 79495eb..7cb475c 100644 --- a/Sources/Shared/Battery.swift +++ b/Sources/Shared/Battery.swift @@ -58,14 +58,30 @@ struct BatteryInfo { return hi - lo } - static func read() -> BatteryInfo? { + /// What the daemon's policy and history and the menu bar icon need. Copying just + /// these is about 6x cheaper than the whole entry (0.25 vs 1.6 ms on a cold wakeup), + /// which matters for code that runs all day. + static let essentialKeys = ["CurrentCapacity", "ExternalConnected", "IsCharging", "FullyCharged", + "Temperature", "Voltage", "InstantAmperage", "AvgTimeToEmpty", "AvgTimeToFull"] + + /// With `essentialsOnly`, fields outside `essentialKeys` are left zero or nil. + static func read(essentialsOnly: Bool = false) -> BatteryInfo? { let svc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery")) guard svc != 0 else { return nil } defer { IOObjectRelease(svc) } - var props: Unmanaged? - guard IORegistryEntryCreateCFProperties(svc, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS, - let d = props?.takeRetainedValue() as? [String: Any] else { return nil } + var d: [String: Any] = [:] + if essentialsOnly { + for k in essentialKeys { + d[k] = IORegistryEntryCreateCFProperty(svc, k as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() + } + guard !d.isEmpty else { return nil } + } else { + var props: Unmanaged? + guard IORegistryEntryCreateCFProperties(svc, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS, + let all = props?.takeRetainedValue() as? [String: Any] else { return nil } + d = all + } func num(_ dict: [String: Any]?, _ k: String) -> Int? { (dict?[k] as? NSNumber)?.intValue } func int(_ k: String) -> Int { num(d, k) ?? 0 } diff --git a/Sources/Shared/Config.swift b/Sources/Shared/Config.swift index 26c99ee..1dd4bf2 100644 --- a/Sources/Shared/Config.swift +++ b/Sources/Shared/Config.swift @@ -113,11 +113,19 @@ struct DaemonStatus: Codable { var event: String? var eventAt: Date? + /// When nothing has changed the daemon only touches the file (far cheaper than + /// rewriting it), so the file's modification date counts as `updatedAt` too. static func load() -> DaemonStatus? { guard let data = FileManager.default.contents(atPath: Paths.status) else { return nil } let dec = JSONDecoder() dec.dateDecodingStrategy = .iso8601 - return try? dec.decode(DaemonStatus.self, from: data) + guard var s = try? dec.decode(DaemonStatus.self, from: data) else { return nil } + var st = stat() + if stat(Paths.status, &st) == 0 { + let touched = Date(timeIntervalSince1970: TimeInterval(st.st_mtimespec.tv_sec)) + s.updatedAt = max(s.updatedAt, touched) + } + return s } var isFresh: Bool { Date().timeIntervalSince(updatedAt) < 60 } diff --git a/Tests/Policy/main.swift b/Tests/Policy/main.swift index f1ac822..aeefb72 100644 --- a/Tests/Policy/main.swift +++ b/Tests/Policy/main.swift @@ -118,5 +118,13 @@ check(History.record(bat(50), into: &hist, now: h0), "history records first samp check(!History.record(bat(50), into: &hist, now: h0 + 60), "history skips samples within 5 min") check(History.record(bat(50), into: &hist, now: h0 + 49 * 3600) && hist.count == 1, "history trims >48h") +// The essentials-only read must see the same battery as the full one (skipped without a battery, as on CI). +if let full = BatteryInfo.read(), let light = BatteryInfo.read(essentialsOnly: true) { + check(light.percent == full.percent && light.pluggedIn == full.pluggedIn && light.isCharging == full.isCharging + && light.fullyCharged == full.fullyCharged && abs(light.temperatureC - full.temperatureC) < 1 + && abs(light.voltage - full.voltage) < 0.2 && light.percent > 0 && light.voltage > 0, + "essentials-only battery read matches the full read") +} + print(failures == 0 ? "\nall passed" : "\n\(failures) failed") exit(failures == 0 ? 0 : 1)