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
5 changes: 5 additions & 0 deletions .changeset/charging-from-current.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ewiz": patch
---

**Plugging in shows "Charging" at once, and the MagSafe light stops flickering.** macOS's charging flag can lag a plug-in by over 20 seconds while current is already flowing into the battery. eWiz waited on that flag, so the panel said "Plugged in, not charging", the icon had no bolt, and the MagSafe light went amber, then green, then amber again. eWiz now treats current flowing into the battery as charging. Also adds `scripts/plug-trace.py`, which logs the battery, macOS, the helper and the menu bar side by side across a plug or unplug.
24 changes: 24 additions & 0 deletions Sources/EWizKit/BatteryMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,22 @@ public enum BatteryMonitor {
snap.isExternalConnected = snap.isPluggedIn
}

/// Current into the battery that counts as charging whatever the flag says. Well above
/// the trickle a full or held battery shows on the adapter, well below a real charge.
public static let chargingCurrentFloor = 300

/// Whether the battery is charging: macOS's flag, or current actually flowing in.
///
/// `IsCharging` can trail the current by a long way. Traced on a plug-in: +1063 mA into
/// the battery one second after the cable, and the flag still "No" 23 seconds later. Every
/// surface waited on the flag, so the panel said "Plugged in, not charging", the icon had
/// no bolt, and the helper set the MagSafe light green over a battery taking 4 A (macOS
/// had lit it amber, so it went amber, green, amber). Current is the fact; the flag is a
/// report of it. Never the other way: a flag saying yes is kept.
public static func isCharging(flag: Bool, amperage: Int, cableIn: Bool, full: Bool) -> Bool {
flag || (cableIn && !full && amperage >= chargingCurrentFloor)
}

// MARK: - AppleSmartBattery (hardware detail)

private static func readSmartBattery(into snap: inout BatterySnapshot) {
Expand All @@ -108,6 +124,14 @@ public enum BatteryMonitor {
snap.isExternalConnected = ext
}

// Signed mA, positive into the battery. CFNumber keeps the sign; the ioreg text
// prints negatives as huge unsigned values, the number itself doesn't.
if let amps = (props["Amperage"] as? NSNumber)?.intValue {
snap.isCharging = Self.isCharging(flag: snap.isCharging, amperage: amps,
cableIn: snap.isExternalConnected,
full: snap.isFullyCharged)
}

if let cycles = props["CycleCount"] as? Int {
snap.cycleCount = cycles
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/EWizKit/Control.swift
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,9 @@ public enum HelperBuild {
/// v30: charging starting or stopping wakes the loop too. The source doesn't switch
/// when current starts after a resume or a plug-in, so the helper went on
/// reporting "held" until its next tick.
public static let version = 30
/// 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
}

public enum ControlError: Error, CustomStringConvertible {
Expand Down
24 changes: 24 additions & 0 deletions Tests/EWizKitTests/PowerFlowTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,27 @@ struct PowerFlowTests {
#expect(f.systemWatts == 18)
}
}

@Suite("Charging from current, not only the flag")
struct ChargingFromCurrentTests {
@Test("current flowing in counts before macOS's flag turns over")
func currentBeatsALaggingFlag() {
#expect(BatteryMonitor.isCharging(flag: false, amperage: 1063, cableIn: true, full: false))
}

@Test("a trickle on the adapter is not charging")
func trickleIsNot() {
#expect(!BatteryMonitor.isCharging(flag: false, amperage: 120, cableIn: true, full: false))
}

@Test("no cable, or a full battery, is never charging from current alone")
func needsCableAndRoom() {
#expect(!BatteryMonitor.isCharging(flag: false, amperage: 2000, cableIn: false, full: false))
#expect(!BatteryMonitor.isCharging(flag: false, amperage: 2000, cableIn: true, full: true))
}

@Test("the flag saying yes is kept")
func flagWins() {
#expect(BatteryMonitor.isCharging(flag: true, amperage: -500, cableIn: true, full: false))
}
}
123 changes: 123 additions & 0 deletions scripts/plug-trace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Trace a plug / unplug through every layer, to see which one lags.

Every ~250 ms it reads:
hw the battery itself (IORegistry AppleSmartBattery): cable, charging, %, current
macos the power source macOS reports (pmset -g batt)
helper what ewiz-helper's status says (control socket)
app what the eWiz menu-bar item says (its accessibility label)
and prints a line only when something changed, with the time since the last cable
change. On each change it also grabs the menu-bar item, so the icon's colour is on
record. Ctrl-C to stop. Output: stdout and plug-trace-<time>/trace.log.

python3 scripts/plug-trace.py
"""
import json, os, re, socket, subprocess, sys, time

OUT = os.path.join(os.getcwd(), time.strftime("plug-trace-%H%M%S"))
os.makedirs(OUT, exist_ok=True)
LOG = open(os.path.join(OUT, "trace.log"), "w")


def sh(*cmd):
try:
return subprocess.run(cmd, capture_output=True, text=True, timeout=2).stdout
except subprocess.TimeoutExpired:
return ""


def hw():
out = sh("ioreg", "-rn", "AppleSmartBattery")
def val(key):
m = re.search(rf'^\s*"{key}" = (\S+)', out, re.M)
return m.group(1) if m else "?"
amps = val("Amperage")
try:
amps = int(amps)
amps = amps - (1 << 64) if amps > (1 << 63) else amps
except ValueError:
pass
return {"cable": val("ExternalConnected") == "Yes", "charging": val("IsCharging") == "Yes",
"pct": val("CurrentCapacity"), "mA": amps}


def macos():
out = sh("pmset", "-g", "batt")
src = "AC" if "AC Power" in out else "batt" if "Battery Power" in out else "?"
m = re.search(r"\d+%; ([^;]+);", out)
return {"source": src, "state": m.group(1) if m else "?"}


def helper():
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(1.5)
s.connect("/var/run/ewiz.sock")
s.sendall(b'{"getStatus":{}}\n')
buf = b""
while not buf.endswith(b"\n"):
chunk = s.recv(65536)
if not chunk:
break
buf += chunk
s.close()
d = json.loads(buf)
return {"enabled": d.get("chargingEnabled"), "reason": d.get("pauseReason"),
"cut": d.get("discharging"), "native": d.get("nativeLimitApplied")}
except Exception as e: # a busy or missing helper is itself worth seeing
return {"error": type(e).__name__}


AX = '''tell application "System Events" to tell process "eWiz"
set i to menu bar item 1 of menu bar 2
set {x, y} to position of i
set {w, h} to size of i
return (description of i) & "|" & x & "," & y & "," & w & "," & h
end tell'''


def app():
out = sh("osascript", "-e", AX).strip()
label, _, rect = out.partition("|")
return {"label": label.removeprefix("eWiz, ")}, rect


def emit(line):
print(line, flush=True)
LOG.write(line + "\n"); LOG.flush()


emit(f"tracing → {OUT} (unplug / plug in; Ctrl-C to stop)")
start = time.monotonic()
last_cable_at = None
prev = {}
shot = 0
try:
while True:
t = time.monotonic()
a, rect = app()
now = {"hw": hw(), "macos": macos(), "helper": helper(), "app": a}
if now["hw"]["cable"] != prev.get("hw", {}).get("cable"):
last_cable_at = t
# Current wanders by tens of mA every second; only its sign is a state.
def key(k, d):
return {kk: (vv > 0 if kk == "mA" and isinstance(vv, int) else vv)
for kk, vv in d.items()} if k == "hw" else d
changed = [k for k in now if key(k, now[k]) != key(k, prev.get(k, {}))]
if changed:
since = f"+{t - last_cable_at:5.2f}s" if last_cable_at else " - "
stamp = time.strftime("%H:%M:%S") + f".{int((time.time() % 1) * 1000):03d}"
parts = []
for k in ("hw", "macos", "helper", "app"):
body = " ".join(f"{kk}={vv}" for kk, vv in now[k].items())
parts.append(("*" if k in changed else " ") + f"{k}[{body}]")
emit(f"{stamp} {since} " + " ".join(parts))
if rect.count(",") == 3:
shot += 1
x, y, w, h = rect.split(",")
subprocess.run(["screencapture", "-x", "-R", f"{x},{y},{w},{h}",
os.path.join(OUT, f"icon-{shot:03d}-{since.strip()}.png")])
prev = now
time.sleep(max(0, 0.25 - (time.monotonic() - t)))
except KeyboardInterrupt:
emit("stopped")
Loading