#!/usr/bin/env python3 """Батарея, настройки питания и температура macOS.""" from __future__ import annotations import argparse import json import re import subprocess from pathlib import Path def run(command: list[str]) -> str: result = subprocess.run(command, capture_output=True, text=True, check=False) return result.stdout def ioreg_values() -> dict[str, str]: output = run(["ioreg", "-r", "-c", "AppleSmartBattery", "-w0"]) values = {} for line in output.splitlines(): match = re.search(r'"([^"]+)"\s*=\s*(.+?)\s*$', line) if match: values[match.group(1)] = match.group(2).rstrip(",").strip() return values def pmset_sections() -> dict[str, dict[str, str]]: output = run(["pmset", "-g", "custom"]) sections: dict[str, dict[str, str]] = {} current = "Общее" sections[current] = {} for line in output.splitlines(): if line.endswith(":") and not line.startswith(" "): current = line[:-1] sections[current] = {} continue fields = line.split() if len(fields) >= 2: sections[current][fields[0]] = " ".join(fields[1:]) return sections def thermal() -> dict[str, str]: output = run(["pmset", "-g", "therm"]) values = {} for line in output.splitlines(): match = re.match(r"\s*([A-Za-z0-9_]+)\s*=\s*(.+)", line) if match: values[match.group(1)] = match.group(2).strip() return values def main() -> int: parser = argparse.ArgumentParser(description="Отчёт по питанию и батарее") parser.add_argument("--json", type=Path) args = parser.parse_args() battery_text = run(["pmset", "-g", "batt"]).strip() values = ioreg_values() sections = pmset_sections() heat = thermal() def number(key: str) -> int: try: return int(values.get(key, "0")) except ValueError: return 0 design = number("DesignCapacity") maximum = number("MaxCapacity") health = round(maximum / design * 100, 1) if design else None raw_temperature = number("Temperature") celsius = round(raw_temperature / 10 - 273.15, 1) if raw_temperature > 1000 else None report = { "battery_text": battery_text, "ioreg": { "cycle_count": number("CycleCount"), "design_capacity": design, "max_capacity": maximum, "health_percent": health, "temperature_c": celsius, "external_connected": values.get("ExternalConnected", ""), "charging": values.get("IsCharging", ""), "fully_charged": values.get("FullyCharged", ""), }, "pmset": sections, "thermal": heat, } if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print("Батарея:") print(f" {battery_text or 'данные недоступны'}") print(f" циклов: {report['ioreg']['cycle_count']}") if health is not None: print(f" здоровье: {health}% ({maximum} из {design} мАч)") if celsius is not None: print(f" температура: {celsius} C") print(f" внешнее питание: {report['ioreg']['external_connected'] or 'неизвестно'}") print(f" зарядка: {report['ioreg']['charging'] or 'неизвестно'}") print("\nНастройки pmset:") for section, values in sections.items(): print(f" {section}:") for key in ("sleep", "displaysleep", "hibernatemode", "standby", "powernap", "womp", "lidwake"): if key in values: print(f" {key}: {values[key]}") print("\nТепловые лимиты:") if heat: for key, value in heat.items(): print(f" {key}: {value}") else: print(" данные недоступны") return 0 if __name__ == "__main__": raise SystemExit(main())