Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 5 additions & 4 deletions Sources/App/Model.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
}
Expand All @@ -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
Expand Down
87 changes: 79 additions & 8 deletions Sources/Daemon/Daemon.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import IOKit.ps
import IOKit.pwr_mgt

func log(_ msg: String) {
Expand Down Expand Up @@ -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
Expand All @@ -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<Daemon>.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() {
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -215,7 +287,6 @@ final class Daemon {
chmod(Paths.status, 0o644)
}
lastStatus = s
lastStatusWrite = Date()
}

// MARK: Sleep / wake
Expand Down
2 changes: 1 addition & 1 deletion Sources/Daemon/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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") }
Expand Down
24 changes: 20 additions & 4 deletions Sources/Shared/Battery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<CFMutableDictionary>?
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<CFMutableDictionary>?
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 }
Expand Down
10 changes: 9 additions & 1 deletion Sources/Shared/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
8 changes: 8 additions & 0 deletions Tests/Policy/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading