chargecheck 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
11
+
12
+ # Build and tool caches
13
+ .pytest_cache/
14
+ .ruff_cache/
15
+ .DS_Store
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] - 2026-12-02
8
+
9
+ First release.
10
+
11
+ ### Added
12
+
13
+ - Shows what the charger negotiated over USB-C (watts, volts, amps) next to what actually arrives at the Mac, with a bar for the share of the negotiated power.
14
+ - Flags a sagging voltage (below 85 % of the negotiated one), a battery draining while plugged in, and a charger that is connected but delivers nothing.
15
+ - Port in use, labelled left or right on the 14" and 16" MacBook Pro.
16
+ - System load, battery current and power, charge level and state.
17
+ - Battery health: maximum capacity, cycle count against the design cycles and Apple's own condition.
18
+ - `--watch` keeps sampling and lists every change until Ctrl-C, `--interval` sets the seconds between samples.
19
+ - Exit status 0 ok, 1 problem found, 2 on battery, for scripts.
20
+
21
+ [Unreleased]: https://github.com/bartTC/chargecheck/compare/v0.1.0...HEAD
22
+ [0.1.0]: https://github.com/bartTC/chargecheck/releases/tag/v0.1.0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Martin Mahner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.5
2
+ Name: chargecheck
3
+ Version: 0.1.0
4
+ Summary: Show what a USB-C charger negotiated with a Mac and what power actually arrives
5
+ Project-URL: Homepage, https://github.com/bartTC/chargecheck
6
+ Project-URL: Issues, https://github.com/bartTC/chargecheck/issues
7
+ Project-URL: Changelog, https://github.com/bartTC/chargecheck/blob/main/CHANGELOG.md
8
+ Author-email: Martin Mahner <martin@mahner.org>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: battery,charger,macbook,macos,power,usb-c,usb-pd
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Environment :: MacOS X
15
+ Classifier: Intended Audience :: End Users/Desktop
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Topic :: System :: Hardware
20
+ Classifier: Topic :: Utilities
21
+ Requires-Python: >=3.15
22
+ Requires-Dist: rich>=14
23
+ Description-Content-Type: text/markdown
24
+
25
+ # chargecheck
26
+
27
+ Shows what a USB-C charger negotiated with your Mac and how much power actually arrives.
28
+
29
+ The USB Power Delivery handshake runs over its own wire, so a worn port, a dirty contact or a broken cable can still negotiate 100 W while the power pins sag under load. macOS then says "charging" while only a few watts arrive and the battery drains. chargecheck puts the negotiated numbers next to the measured ones and says when they don't match.
30
+
31
+ ```
32
+ ╭─ ⚡ Charger ──────────────────────────────────────────────────╮
33
+ │ │
34
+ │ Port USB-C 3 (right) │
35
+ │ Negotiated 100 W 20.0 V × 5.00 A │
36
+ │ Arriving 83.2 W 18.82 V × 4.42 A (94% of the voltage) │
37
+ │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
38
+ │ System load 22.3 W │
39
+ │ Battery +5.07 A (+61.4 W) 44 % charging │
40
+ │ Health 86 % capacity 482 / 1000 cycles Good │
41
+ │ │
42
+ │ ✅ All good │
43
+ │ │
44
+ ╰───────────────────────────────────────────────────────────────╯
45
+ ```
46
+
47
+ ## Install
48
+
49
+ macOS only, Python ≥ 3.15 (uv fetches it for `uvx` if needed). It reads `ioreg` and `system_profiler`, no admin rights needed.
50
+
51
+ ```sh
52
+ uvx chargecheck # run without installing
53
+ uv tool install chargecheck
54
+ pipx install chargecheck
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ ```sh
60
+ chargecheck # check once
61
+ chargecheck --watch # keep sampling, list every change until Ctrl-C
62
+ chargecheck -w -i 2 # sample every 2 seconds
63
+ ```
64
+
65
+ | Option | Default | Effect |
66
+ |---|---|---|
67
+ | `-w`, `--watch` | off | Keep sampling and add a row whenever the reading changes. Repeats are hidden. |
68
+ | `-i`, `--interval SECONDS` | 5 | Seconds between samples in watch mode. |
69
+
70
+ The battery controller refreshes its numbers only every 20–30 s, so right after plugging in, or when switching ports, give it half a minute.
71
+
72
+ ### Exit status
73
+
74
+ | Code | Meaning |
75
+ |---|---|
76
+ | `0` | All good, or charging paused on purpose (optimised charging, charge limit). |
77
+ | `1` | A problem: voltage sagging, battery draining while plugged in, or no power arriving. |
78
+ | `2` | On battery, no charger connected. |
79
+
80
+ ## What it shows
81
+
82
+ - **Port:** the port with something plugged in. On the 14" and 16" MacBook Pro, USB-C 1 and 2 are on the left next to MagSafe, USB-C 3 on the right next to HDMI. macOS doesn't say so itself, chargecheck reads it off the port layout.
83
+ - **Negotiated:** what charger and Mac agreed on over USB-PD.
84
+ - **Arriving:** the voltage, current and power measured at the Mac's input, and the share of the negotiated voltage. The bar shows the arriving power against the negotiated watts. It is rarely full: the Mac only draws what it needs.
85
+ - **System load:** what the Mac uses right now.
86
+ - **Battery:** current and power into (+) or out of (−) the battery, charge level and state.
87
+ - **Health:** maximum capacity (yellow below 80 %, where Apple recommends service), cycle count against the cycles the battery was designed for, and Apple's own condition.
88
+
89
+ ## What counts as a problem
90
+
91
+ - **Sagging:** less than 85 % of the negotiated voltage arrives. Resistance in a contact or the cable is eating the power. A healthy 5 m cable still delivers about 94 %.
92
+ - **Draining:** the battery loses more than 100 mA while plugged in and isn't full. The charger can't cover the load.
93
+ - **No power:** a charger is connected but nothing arrives. Normal for a few seconds after plugging in.
94
+
95
+ The battery not charging while the charger delivers is not a problem: optimised charging and the charge limit do that on purpose. chargecheck shows it as paused, with macOS's reason code.
96
+
97
+ ## Development
98
+
99
+ ```sh
100
+ just run # check once from the repo
101
+ just watch # watch mode
102
+ just test # pytest
103
+ just lint # ruff with all rules (config in pyproject.toml)
104
+ just build # sdist and wheel into dist/
105
+ ```
106
+
107
+ Releases go out through GitHub Actions: `git tag v0.1.0 && git push --tags` runs ruff and the tests and publishes to PyPI with Trusted Publishing. The tag has to match the version in `pyproject.toml`.
108
+
109
+ ## License
110
+
111
+ MIT
@@ -0,0 +1,87 @@
1
+ # chargecheck
2
+
3
+ Shows what a USB-C charger negotiated with your Mac and how much power actually arrives.
4
+
5
+ The USB Power Delivery handshake runs over its own wire, so a worn port, a dirty contact or a broken cable can still negotiate 100 W while the power pins sag under load. macOS then says "charging" while only a few watts arrive and the battery drains. chargecheck puts the negotiated numbers next to the measured ones and says when they don't match.
6
+
7
+ ```
8
+ ╭─ ⚡ Charger ──────────────────────────────────────────────────╮
9
+ │ │
10
+ │ Port USB-C 3 (right) │
11
+ │ Negotiated 100 W 20.0 V × 5.00 A │
12
+ │ Arriving 83.2 W 18.82 V × 4.42 A (94% of the voltage) │
13
+ │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
14
+ │ System load 22.3 W │
15
+ │ Battery +5.07 A (+61.4 W) 44 % charging │
16
+ │ Health 86 % capacity 482 / 1000 cycles Good │
17
+ │ │
18
+ │ ✅ All good │
19
+ │ │
20
+ ╰───────────────────────────────────────────────────────────────╯
21
+ ```
22
+
23
+ ## Install
24
+
25
+ macOS only, Python ≥ 3.15 (uv fetches it for `uvx` if needed). It reads `ioreg` and `system_profiler`, no admin rights needed.
26
+
27
+ ```sh
28
+ uvx chargecheck # run without installing
29
+ uv tool install chargecheck
30
+ pipx install chargecheck
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ```sh
36
+ chargecheck # check once
37
+ chargecheck --watch # keep sampling, list every change until Ctrl-C
38
+ chargecheck -w -i 2 # sample every 2 seconds
39
+ ```
40
+
41
+ | Option | Default | Effect |
42
+ |---|---|---|
43
+ | `-w`, `--watch` | off | Keep sampling and add a row whenever the reading changes. Repeats are hidden. |
44
+ | `-i`, `--interval SECONDS` | 5 | Seconds between samples in watch mode. |
45
+
46
+ The battery controller refreshes its numbers only every 20–30 s, so right after plugging in, or when switching ports, give it half a minute.
47
+
48
+ ### Exit status
49
+
50
+ | Code | Meaning |
51
+ |---|---|
52
+ | `0` | All good, or charging paused on purpose (optimised charging, charge limit). |
53
+ | `1` | A problem: voltage sagging, battery draining while plugged in, or no power arriving. |
54
+ | `2` | On battery, no charger connected. |
55
+
56
+ ## What it shows
57
+
58
+ - **Port:** the port with something plugged in. On the 14" and 16" MacBook Pro, USB-C 1 and 2 are on the left next to MagSafe, USB-C 3 on the right next to HDMI. macOS doesn't say so itself, chargecheck reads it off the port layout.
59
+ - **Negotiated:** what charger and Mac agreed on over USB-PD.
60
+ - **Arriving:** the voltage, current and power measured at the Mac's input, and the share of the negotiated voltage. The bar shows the arriving power against the negotiated watts. It is rarely full: the Mac only draws what it needs.
61
+ - **System load:** what the Mac uses right now.
62
+ - **Battery:** current and power into (+) or out of (−) the battery, charge level and state.
63
+ - **Health:** maximum capacity (yellow below 80 %, where Apple recommends service), cycle count against the cycles the battery was designed for, and Apple's own condition.
64
+
65
+ ## What counts as a problem
66
+
67
+ - **Sagging:** less than 85 % of the negotiated voltage arrives. Resistance in a contact or the cable is eating the power. A healthy 5 m cable still delivers about 94 %.
68
+ - **Draining:** the battery loses more than 100 mA while plugged in and isn't full. The charger can't cover the load.
69
+ - **No power:** a charger is connected but nothing arrives. Normal for a few seconds after plugging in.
70
+
71
+ The battery not charging while the charger delivers is not a problem: optimised charging and the charge limit do that on purpose. chargecheck shows it as paused, with macOS's reason code.
72
+
73
+ ## Development
74
+
75
+ ```sh
76
+ just run # check once from the repo
77
+ just watch # watch mode
78
+ just test # pytest
79
+ just lint # ruff with all rules (config in pyproject.toml)
80
+ just build # sdist and wheel into dist/
81
+ ```
82
+
83
+ Releases go out through GitHub Actions: `git tag v0.1.0 && git push --tags` runs ruff and the tests and publishes to PyPI with Trusted Publishing. The tag has to match the version in `pyproject.toml`.
84
+
85
+ ## License
86
+
87
+ MIT
@@ -0,0 +1,77 @@
1
+ [project]
2
+ name = "chargecheck"
3
+ version = "0.1.0"
4
+ description = "Show what a USB-C charger negotiated with a Mac and what power actually arrives"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "Martin Mahner", email = "martin@mahner.org" }
10
+ ]
11
+ keywords = ["macos", "macbook", "usb-c", "usb-pd", "charger", "battery", "power"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Environment :: Console",
15
+ "Environment :: MacOS X",
16
+ "Intended Audience :: End Users/Desktop",
17
+ "Operating System :: MacOS",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.15",
20
+ "Topic :: System :: Hardware",
21
+ "Topic :: Utilities",
22
+ ]
23
+ requires-python = ">=3.15"
24
+ dependencies = [
25
+ "rich>=14",
26
+ ]
27
+
28
+ [project.scripts]
29
+ chargecheck = "chargecheck:main"
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/bartTC/chargecheck"
33
+ Issues = "https://github.com/bartTC/chargecheck/issues"
34
+ Changelog = "https://github.com/bartTC/chargecheck/blob/main/CHANGELOG.md"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "pytest>=8",
39
+ "ruff>=0.16",
40
+ ]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+
45
+ [build-system]
46
+ requires = ["hatchling>=1.27"]
47
+ build-backend = "hatchling.build"
48
+
49
+ [tool.hatch.build.targets.sdist]
50
+ include = ["src", "README.md", "CHANGELOG.md", "LICENSE"]
51
+
52
+ [tool.ruff]
53
+ target-version = "py315" # keep in sync with requires-python
54
+ lint.select = ["ALL"]
55
+ lint.ignore = [
56
+ # Valid exclusions.
57
+ "COM812", # Conflicts with ruff format
58
+ "E501", # Line too long (>88)
59
+ "D203", # incorrect-blank-line-before-class (conflicts with D211)
60
+ "D212", # Don't require summary on first line
61
+ "ERA001", # Found commented-out code
62
+ "FBT", # Flake Boolean Trap (don't use arg=True in functions)
63
+ "D", # docstrings are written where they help, not on every function
64
+ "CPY001", # the license is in LICENSE, no header in every file
65
+ "RUF001", "RUF002", "RUF003", # typographic characters (× · ⚡) in the interface are intended
66
+ "S603", "S607", # ioreg and system_profiler are fixed system tools, called without user input
67
+ "PLR2004", # the thresholds (mA, capacity %) read better inline next to their comments
68
+ "DTZ005", # times shown are wall clock times on this Mac, local time is intended
69
+ ]
70
+
71
+ [tool.ruff.lint.extend-per-file-ignores]
72
+ "tests/test_*.py" = [
73
+ "S101", # Use of `assert` detected
74
+ "D", # Tests don't need docstrings on every class/method
75
+ "ANN", # Inline helpers don't need full type annotations
76
+ ]
77
+ "tests/__init__.py" = ["D104"]
@@ -0,0 +1,351 @@
1
+ """Show what the charger negotiated over USB-C and what actually reaches the Mac.
2
+
3
+ The PD handshake runs over its own CC wire, so a worn port, dirty contact or
4
+ broken cable can still negotiate 100 W while the power pins sag under load:
5
+ macOS then says "charging" while only a few watts arrive and the battery
6
+ drains. The numbers come from the battery controller, which refreshes them
7
+ only every 20-30 s.
8
+
9
+ Exit status: 0 ok, 1 problem found, 2 on battery.
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import plistlib
15
+ import subprocess
16
+ import time
17
+ from collections import deque
18
+ from dataclasses import dataclass
19
+ from datetime import datetime
20
+
21
+ from rich import box
22
+ from rich.console import Console, Group
23
+ from rich.live import Live
24
+ from rich.panel import Panel
25
+ from rich.progress_bar import ProgressBar
26
+ from rich.table import Table
27
+ from rich.text import Text
28
+
29
+ OK, PROBLEM, ON_BATTERY = 0, 1, 2
30
+ STYLES = {OK: "green", PROBLEM: "bold red", ON_BATTERY: "yellow"}
31
+ ICONS = {OK: "✅", PROBLEM: "❌", ON_BATTERY: "🔋"}
32
+
33
+ # Below this share of the negotiated voltage, resistance in the contact or
34
+ # cable is eating the power. A healthy 5 m cable still delivers about 94 %.
35
+ SAG_LIMIT = 0.85
36
+
37
+
38
+ def ioreg(*args: str) -> list[dict]:
39
+ out = subprocess.run(["ioreg", "-a", *args], capture_output=True, check=True).stdout
40
+ return plistlib.loads(out) if out.strip() else []
41
+
42
+
43
+ def signed(value: int | None) -> int | None:
44
+ # ioreg hands negative values (a draining battery) over as unsigned 64-bit.
45
+ if value is not None and value >= 2**63:
46
+ return value - 2**64
47
+ return value
48
+
49
+
50
+ def active_ports() -> tuple[str, ...]:
51
+ """Ports with something plugged in, labelled with their side where known.
52
+
53
+ On the 14"/16" MacBook Pro (MagSafe plus three USB-C) USB-C 1 and 2 sit on
54
+ the left next to MagSafe, USB-C 3 on the right next to HDMI. macOS doesn't
55
+ say so itself; this is read off the port layout.
56
+ """
57
+ ports = ioreg("-r", "-d1", "-c", "AppleHPMInterface")
58
+ names = [p.get("PortDescription", "") for p in ports]
59
+ pro_layout = "Port-USB-C@3" in names and any(n.startswith("Port-MagSafe") for n in names)
60
+ labels = []
61
+ for port in ports:
62
+ if not port.get("ConnectionActive"):
63
+ continue
64
+ name = port.get("PortDescription", "?")
65
+ label = name.removeprefix("Port-").replace("@", " ")
66
+ if pro_layout:
67
+ label += " (right)" if name == "Port-USB-C@3" else " (left)"
68
+ labels.append(label)
69
+ return tuple(labels)
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Sample:
74
+ """One reading. Frozen so watch mode can skip repeats by comparing samples."""
75
+
76
+ connected: bool
77
+ watts: int | None
78
+ adapter_mv: int | None
79
+ adapter_ma: int | None
80
+ vin_mv: int
81
+ iin_ma: int
82
+ pin_mw: int
83
+ load_mw: int
84
+ battery_ma: int
85
+ battery_mv: int
86
+ percent: int
87
+ charging: bool
88
+ full: bool
89
+ not_charging_reason: int
90
+ ports: tuple[str, ...]
91
+
92
+ @classmethod
93
+ def read(cls) -> Sample:
94
+ battery = ioreg("-r", "-n", "AppleSmartBattery")[0]
95
+ adapter = battery.get("AdapterDetails", {})
96
+ telemetry = battery.get("PowerTelemetryData", {})
97
+ connected = bool(battery.get("ExternalConnected"))
98
+ return cls(
99
+ connected=connected,
100
+ # A disconnected adapter leaves its last details behind.
101
+ watts=adapter.get("Watts") if connected else None,
102
+ adapter_mv=adapter.get("AdapterVoltage") if connected else None,
103
+ adapter_ma=adapter.get("Current") if connected else None,
104
+ vin_mv=telemetry.get("SystemVoltageIn", 0),
105
+ iin_ma=telemetry.get("SystemCurrentIn", 0),
106
+ pin_mw=telemetry.get("SystemPowerIn", 0),
107
+ load_mw=signed(telemetry.get("SystemLoad", 0)),
108
+ battery_ma=signed(battery.get("InstantAmperage", 0)),
109
+ battery_mv=battery.get("Voltage", 0),
110
+ percent=battery.get("CurrentCapacity", 0),
111
+ charging=bool(battery.get("IsCharging")),
112
+ full=bool(battery.get("FullyCharged")),
113
+ not_charging_reason=battery.get("ChargerData", {}).get("NotChargingReason", 0),
114
+ ports=active_ports(),
115
+ )
116
+
117
+ @property
118
+ def voltage_share(self) -> float | None:
119
+ if not self.adapter_mv or not self.connected:
120
+ return None
121
+ return self.vin_mv / self.adapter_mv
122
+
123
+ @property
124
+ def battery_w(self) -> float:
125
+ return self.battery_ma * self.battery_mv / 1_000_000
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class Health:
130
+ """Battery wear. Kept out of Sample since it doesn't change while watching."""
131
+
132
+ max_capacity: int | None
133
+ cycles: int
134
+ design_cycles: int | None
135
+ condition: str
136
+
137
+ @classmethod
138
+ def read(cls) -> Health:
139
+ battery = ioreg("-r", "-n", "AppleSmartBattery")[0]
140
+ data = battery.get("BatteryData", {})
141
+ # system_profiler carries Apple's own verdict ("Good", "Service
142
+ # Recommended") and the rounded capacity System Settings shows.
143
+ profile = json.loads(
144
+ subprocess.run(
145
+ ["system_profiler", "-json", "SPPowerDataType"], capture_output=True, check=True
146
+ ).stdout
147
+ )
148
+ info = next(
149
+ (e["sppower_battery_health_info"] for e in profile.get("SPPowerDataType", [])
150
+ if "sppower_battery_health_info" in e),
151
+ {},
152
+ )
153
+ capacity = info.get("sppower_battery_health_maximum_capacity", "").removesuffix(" %")
154
+ if not capacity.isdigit() and data.get("DesignCapacity"):
155
+ # Same ratio System Settings rounds to, should system_profiler fall short.
156
+ capacity = str(round(100 * data["NominalChargeCapacity"] / data["DesignCapacity"]))
157
+ return cls(
158
+ max_capacity=int(capacity) if capacity.isdigit() else None,
159
+ cycles=battery.get("CycleCount", 0),
160
+ design_cycles=battery.get("DesignCycleCount9C"),
161
+ condition=info.get("sppower_battery_health", "unknown"),
162
+ )
163
+
164
+
165
+ @dataclass(frozen=True)
166
+ class Verdict:
167
+ code: int
168
+ short: str
169
+ message: str
170
+
171
+
172
+ def judge(s: Sample) -> Verdict:
173
+ if not s.connected:
174
+ return Verdict(ON_BATTERY, "battery", "On battery, no charger connected")
175
+ if not s.vin_mv:
176
+ return Verdict(
177
+ PROBLEM,
178
+ "no power",
179
+ "Charger connected but no power arriving. Right after plugging in "
180
+ "that's normal; check again in 30 s.",
181
+ )
182
+ if s.voltage_share is not None and s.voltage_share < SAG_LIMIT:
183
+ return Verdict(
184
+ PROBLEM,
185
+ "sagging",
186
+ f"Only {s.vin_mv / 1000:.1f} V of the {s.adapter_mv / 1000:.0f} V negotiated "
187
+ "arrive: bad contact, port or cable",
188
+ )
189
+ if s.battery_ma < -100 and not s.full:
190
+ return Verdict(
191
+ PROBLEM, "draining", "Battery draining while plugged in: the charger can't cover the load"
192
+ )
193
+ if s.battery_ma <= 50 and not s.full and s.not_charging_reason:
194
+ # Optimised charging and the charge limit land here too, so this is
195
+ # informational only.
196
+ return Verdict(
197
+ OK,
198
+ "paused",
199
+ f"Not charging at {s.percent} % (reason code {s.not_charging_reason}), "
200
+ "e.g. optimised charging or the charge limit",
201
+ )
202
+ return Verdict(OK, "ok", "All good")
203
+
204
+
205
+ def signed_text(value: float, unit: str, decimals: int, plugged_in: bool) -> Text:
206
+ style = "green" if value > 0 else "red" if value < 0 and plugged_in else ""
207
+ return Text(f"{value:+.{decimals}f} {unit}", style=style)
208
+
209
+
210
+ def voltage_style(s: Sample) -> str:
211
+ share = s.voltage_share
212
+ if share is None:
213
+ return ""
214
+ return "green" if share >= SAG_LIMIT else "bold red"
215
+
216
+
217
+ def health_text(h: Health) -> Text:
218
+ text = Text()
219
+ if h.max_capacity is not None:
220
+ # Apple recommends service once capacity drops below 80 %.
221
+ style = "green" if h.max_capacity >= 80 else "yellow"
222
+ text.append(f"{h.max_capacity} %", style=f"bold {style}")
223
+ text.append(" capacity ")
224
+ text.append(f"{h.cycles}")
225
+ text.append(f" / {h.design_cycles} cycles " if h.design_cycles else " cycles ", style="dim")
226
+ text.append(h.condition, style="green" if h.condition in ("Good", "Normal") else "yellow")
227
+ return text
228
+
229
+
230
+ def report(s: Sample, v: Verdict, h: Health) -> Panel:
231
+ grid = Table.grid(padding=(0, 2))
232
+ grid.add_column(style="dim", justify="right")
233
+ grid.add_column()
234
+ grid.add_row("Port", ", ".join(s.ports) or "-")
235
+ if s.connected:
236
+ grid.add_row(
237
+ "Negotiated",
238
+ Text.assemble(
239
+ (f"{s.watts} W", "bold"),
240
+ f" {s.adapter_mv / 1000:.1f} V × {s.adapter_ma / 1000:.2f} A",
241
+ ),
242
+ )
243
+ arriving = Text.assemble(
244
+ (f"{s.pin_mw / 1000:.1f} W", "bold"),
245
+ " ",
246
+ (f"{s.vin_mv / 1000:.2f} V", voltage_style(s)),
247
+ f" × {s.iin_ma / 1000:.2f} A",
248
+ )
249
+ if s.voltage_share is not None:
250
+ arriving.append(f" ({s.voltage_share:.0%} of the voltage)", style="dim")
251
+ grid.add_row("Arriving", arriving)
252
+ bar_style = "green" if v.code == OK else "red"
253
+ grid.add_row(
254
+ "",
255
+ ProgressBar(
256
+ total=s.watts or 1,
257
+ completed=s.pin_mw / 1000,
258
+ width=40,
259
+ complete_style=bar_style,
260
+ finished_style=bar_style,
261
+ ),
262
+ )
263
+ grid.add_row("System load", f"{s.load_mw / 1000:.1f} W")
264
+ state = "full" if s.full else "charging" if s.charging else "not charging"
265
+ battery = signed_text(s.battery_ma / 1000, "A", 2, s.connected)
266
+ battery.append(f" ({s.battery_w:+.1f} W) ")
267
+ battery.append(f"{s.percent} %", style="bold")
268
+ battery.append(f" {state}", style="dim")
269
+ grid.add_row("Battery", battery)
270
+ grid.add_row("Health", health_text(h))
271
+
272
+ verdict = Text(f"{ICONS[v.code]} {v.message}", style=STYLES[v.code])
273
+ return Panel(
274
+ Group(grid, Text(), verdict),
275
+ title="⚡ Charger",
276
+ title_align="left",
277
+ border_style=STYLES[v.code].removeprefix("bold "),
278
+ box=box.ROUNDED,
279
+ expand=False,
280
+ padding=(1, 2),
281
+ )
282
+
283
+
284
+ def watch(console: Console, interval: int) -> int:
285
+ rows: deque[tuple[datetime, Sample, Verdict]] = deque(maxlen=max(console.height - 10, 5))
286
+ last_check = datetime.now()
287
+
288
+ def render() -> Table:
289
+ table = Table(
290
+ box=box.SIMPLE_HEAD,
291
+ title="⚡ Charger",
292
+ title_justify="left",
293
+ caption=(
294
+ f"Checked {last_check:%H:%M:%S} · every {interval} s · repeats hidden, "
295
+ "macOS refreshes every 20-30 s · Ctrl-C to stop"
296
+ ),
297
+ caption_justify="left",
298
+ )
299
+ for name in ("Time", "Port", "Agreed", "Volts", "Amps", "In", "Load", "Battery", "%", "Status"):
300
+ justify = "left" if name in ("Time", "Port", "Status") else "right"
301
+ table.add_column(name, justify=justify)
302
+ for at, s, v in rows:
303
+ table.add_row(
304
+ f"{at:%H:%M:%S}",
305
+ ", ".join(s.ports) or "-",
306
+ f"{s.watts} W" if s.connected else "-",
307
+ Text(f"{s.vin_mv / 1000:.2f} V", style=voltage_style(s)),
308
+ f"{s.iin_ma / 1000:.2f} A",
309
+ f"{s.pin_mw / 1000:.1f} W",
310
+ f"{s.load_mw / 1000:.0f} W",
311
+ signed_text(s.battery_ma / 1000, "A", 2, s.connected),
312
+ str(s.percent),
313
+ Text(f"{ICONS[v.code]} {v.short}", style=STYLES[v.code]),
314
+ )
315
+ return table
316
+
317
+ with Live(render(), console=console, auto_refresh=False) as live:
318
+ try:
319
+ while True:
320
+ sample = Sample.read()
321
+ last_check = datetime.now()
322
+ if not rows or rows[-1][1] != sample:
323
+ rows.append((last_check, sample, judge(sample)))
324
+ live.update(render(), refresh=True)
325
+ time.sleep(interval)
326
+ except KeyboardInterrupt:
327
+ pass
328
+ return OK
329
+
330
+
331
+ def main() -> int:
332
+ parser = argparse.ArgumentParser(
333
+ description="Show what the charger negotiated over USB-C and what really arrives.",
334
+ epilog="Exit status: 0 ok, 1 problem found, 2 on battery.",
335
+ )
336
+ parser.add_argument(
337
+ "-w", "--watch", action="store_true", help="keep sampling and list every change until Ctrl-C"
338
+ )
339
+ parser.add_argument(
340
+ "-i", "--interval", type=int, default=5, metavar="SECONDS", help="seconds between samples (default 5)"
341
+ )
342
+ args = parser.parse_args()
343
+ console = Console()
344
+ if args.watch:
345
+ return watch(console, args.interval)
346
+ sample = Sample.read()
347
+ verdict = judge(sample)
348
+ console.print()
349
+ console.print(report(sample, verdict, Health.read()))
350
+ return verdict.code
351
+
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from . import main
4
+
5
+ sys.exit(main())