### Install Power Monitor with uv Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Recommended installation method using the uv package manager. ```bash uv tool install powermonitor ``` -------------------------------- ### Install Power Monitor with pipx Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Alternative installation method using pipx. ```bash pipx install powermonitor ``` -------------------------------- ### Install and Run PowerMonitor Source: https://context7.com/narumiruna/power-monitor/llms.txt Install and run the tool using package managers like `uvx`, `uv tool`, or `pipx`. Launch the TUI with custom intervals and chart limits, or enable debug logging. ```bash # One-shot run (no install needed) uvx powermonitor # Permanent install with uv uv tool install powermonitor # Permanent install with pipx pipx install powermonitor # Launch TUI with custom interval and chart window powermonitor --interval 2.0 --chart-limit 120 --stats-limit 200 # Enable debug logging powermonitor --debug ``` -------------------------------- ### Power Monitor TUI Configuration Example Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Example TOML configuration file for Power Monitor. CLI arguments override these settings. ```toml # powermonitor configuration file [tui] interval = 1.0 # Data collection interval in seconds stats_limit = 100 # Number of readings for statistics chart_limit = 60 # Number of readings to display in chart [database] path = "~/.powermonitor/powermonitor.db" # Database file location [cli] default_history_limit = 20 # Default limit for history command default_export_limit = 1000 # Default limit for export command [logging] level = "INFO" # Logging level: DEBUG, INFO, WARNING, ERROR ``` -------------------------------- ### Install Project Dependencies Source: https://context7.com/narumiruna/power-monitor/llms.txt Installs project dependencies in editable mode using uv. ```bash uv sync ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Installs project dependencies using the 'uv' package manager. This command synchronizes the project's dependencies based on the lock file. ```bash # Install dependencies uv sync ``` -------------------------------- ### Power Monitor Custom Database and Interval Configuration Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Example TOML snippet to set a custom database path and collection interval. ```toml [database] path = "~/Documents/power-data.db" [tui] interval = 2.0 ``` -------------------------------- ### PowerMonitor Configuration File Example Source: https://context7.com/narumiruna/power-monitor/llms.txt An optional TOML configuration file at `~/.powermonitor/config.toml` allows customization of TUI settings, database path, CLI defaults, and logging level. Missing fields fall back to defaults. ```toml # ~/.powermonitor/config.toml [tui] interval = 1.0 # Collection interval in seconds (default: 1.0) stats_limit = 100 # Readings included in statistics panel (default: 100) chart_limit = 60 # Readings shown in chart panel (default: 60) [database] path = "~/.powermonitor/powermonitor.db" # Tilde expanded automatically [cli] default_history_limit = 20 # Default row count for `history` command default_export_limit = 1000 # Default row count for `export` command [logging] level = "INFO" # DEBUG | INFO | WARNING | ERROR (case-insensitive) ``` -------------------------------- ### Get and Query Power Monitor Data Source: https://context7.com/narumiruna/power-monitor/llms.txt Demonstrates how to retrieve statistics and insert/query historical readings from the Power Monitor database. Supports default and custom database paths. ```python stats = get_statistics(limit=100) print(stats["avg_watts"]) ``` ```python row_id = insert_reading(reading, db_path="~/custom.db") recent = query_history(limit=10, db_path="~/custom.db") stats = get_statistics(limit=50, db_path="~/custom.db") ``` -------------------------------- ### Analyze Last 60 Days of Power Usage Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Use this command to analyze power usage data for the last 60 days. Ensure you have the powermonitor CLI installed. ```bash powermonitor health --days 60 ``` -------------------------------- ### Get Default Power Collector Source: https://context7.com/narumiruna/power-monitor/llms.txt Use `default_collector()` to obtain the appropriate collector for the current macOS environment. Enable `verbose=True` for detailed logging of collector selection and sensor values. ```python from powermonitor.collector import default_collector # Normal use collector = default_collector() reading = collector.collect() print(f"{reading.watts_actual:.1f}W {reading.battery_percent}%") # Verbose mode: logs which collector was selected and SMC sensor values verbose_collector = default_collector(verbose=True) reading = verbose_collector.collect() # Logs: "Using IOKitCollector (SMC sensors)" # Logs: " PDTR (Power Input): 45.2W" # Logs: " PPBR (Battery Power): -12.4W" # etc. # Raises RuntimeError on non-macOS import sys if sys.platform != "darwin": # RuntimeError: powermonitor only supports macOS pass ``` -------------------------------- ### Module-Level Database Functions Source: https://context7.com/narumiruna/power-monitor/llms.txt Convenient module-level functions for interacting with the default database instance. Allows stateless calls for inserting readings, querying history, and getting statistics without explicitly managing Database objects. ```python from powermonitor.database import insert_reading, query_history, get_statistics, get_database from powermonitor.models import PowerReading from datetime import datetime, UTC reading = PowerReading( timestamp=datetime.now(tz=UTC), watts_actual=38.5, watts_negotiated=67, voltage=20.0, amperage=1.925, current_capacity=3200, max_capacity=4709, battery_percent=68, is_charging=True, external_connected=True, charger_name=None, charger_manufacturer=None, ) # Insert using default ~/.powermonitor/powermonitor.db row_id = insert_reading(reading) # Query using default db recent = query_history(limit=5) ``` -------------------------------- ### Load Configuration and Use in CLI Commands Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Demonstrates how to load configuration settings, with CLI arguments overriding file or default values. This pattern is useful for integrating configuration into CLI commands. ```python from .config_loader import load_config def some_command(limit: int | None = None): # Load config (file or defaults) config = load_config() # CLI arg overrides config if limit is None: limit = config.default_history_limit # Use config for database path db = Database(config.database_path) ``` -------------------------------- ### Load Configuration with Fallbacks Source: https://context7.com/narumiruna/power-monitor/llms.txt The `load_config()` function reads `~/.powermonitor/config.toml`, merges it with defaults, and handles malformed files or individual bad fields gracefully by logging warnings and using defaults where necessary. `get_config_path()` returns the expected file location. ```python from powermonitor.config_loader import load_config, get_config_path # Returns PowerMonitorConfig; no exception even if file is absent/malformed config = load_config() print(config.collection_interval) print(config.database_path) # Where the file lives print(get_config_path()) # /Users/you/.powermonitor/config.toml # Bad individual field → warning logged, default used; rest of file applied # config.toml: # [tui] # interval = "not-a-number" ← falls back to 1.0 # stats_limit = 50 ← applied successfully ``` -------------------------------- ### Run Power Monitor TUI Source: https://context7.com/narumiruna/power-monitor/llms.txt Launches the Power Monitor Text User Interface (TUI) from the source code using uv. ```bash uv run powermonitor ``` -------------------------------- ### Launch Power Monitor TUI Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Launches the auto-updating TUI with default settings. Customize interval, stats limit, and chart limit using flags. ```bash # Launch auto-updating TUI with default settings powermonitor # Customize TUI settings powermonitor --interval 1.0 --stats-limit 100 --chart-limit 60 # Enable debug logging powermonitor --debug ``` -------------------------------- ### Run Linting and Formatting with `ruff` Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Applies linting and code formatting checks using `ruff`. This command enforces code quality and style guidelines. ```bash uv run ruff check src/ uv run ruff format src/ ``` -------------------------------- ### Configure Power Monitor Logging Source: https://context7.com/narumiruna/power-monitor/llms.txt Sets up loguru logging for the Power Monitor application. Supports different log levels, file logging, and synchronous/asynchronous modes. ```python from powermonitor.logger import setup_logger # Default: INFO level, file logging enabled, async enqueue setup_logger() ``` ```python # Debug mode setup_logger(level="DEBUG") ``` ```python # Suppress file logging (e.g., CI environments) setup_logger(level="INFO", log_to_file=False) ``` ```python # Synchronous logging for tests (no background thread) setup_logger(level="DEBUG", log_to_file=True, enqueue=False) ``` ```python # File rotation: 10 MB max size, 7-day retention, zip compression # Log format: "2025-01-06 15:22:00 | INFO | module:function:42 - message" # Console format: "INFO: message" (WARNING and above only) ``` -------------------------------- ### Create AdapterDetail Charger Metadata Model Source: https://context7.com/narumiruna/power-monitor/llms.txt Instantiate an AdapterDetail object to hold charger metadata. Access properties like watts, name, and manufacturer. Note that voltage and current are in millivolts and milliamperes respectively. ```python from powermonitor.models import AdapterDetail adapter = AdapterDetail( watts=67, name="USB-C Power Adapter", description="67W USB-C Power Adapter", manufacturer="Apple Inc.", voltage=20000, # mV current=3350, # mA ) print(adapter.watts) # 67 print(adapter.voltage / 1000) # 20.0 V ``` -------------------------------- ### Test Data Collection in Development Mode Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Run a quick test of the data collection mechanism in development mode. This command collects and prints the default collector's output. ```bash uv run python -c "from powermonitor.collector import default_collector; print(default_collector().collect())" ``` -------------------------------- ### View Power Monitor Database Statistics Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Displays database information including total readings, date range, size, and path. ```bash powermonitor stats ``` -------------------------------- ### Format Code Source: https://context7.com/narumiruna/power-monitor/llms.txt Formats the source code according to project standards using Ruff. ```bash uv run ruff format src/ ``` -------------------------------- ### Create and Use PowerReading Data Model Source: https://context7.com/narumiruna/power-monitor/llms.txt Instantiate a PowerReading object to store power measurement data. Use the static `calculate_watts` method for convenience. Determine charging status based on reading attributes. ```python from datetime import datetime, UTC from powermonitor.models import PowerReading reading = PowerReading( timestamp=datetime.now(tz=UTC), watts_actual=-12.4, # negative = discharging watts_negotiated=67, # PD-negotiated max watts from charger voltage=20.0, # V amperage=-0.62, # A (negative = discharging) current_capacity=3800, # mAh max_capacity=4709, # mAh battery_percent=80, is_charging=False, external_connected=True, charger_name="USB-C Power Adapter", charger_manufacturer="Apple Inc.", ) # Static helper: compute watts from V and A watts = PowerReading.calculate_watts(20.0, 2.26) print(watts) # 45.2 # Status logic example if reading.is_charging: label = "⚡ Charging" elif reading.external_connected: label = "🔌 AC Power (Not Charging)" else: label = "🔋 On Battery" ``` -------------------------------- ### Map ioreg Keys to PowerReading Fields Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Illustrates the mapping between keys found in the `AppleSmartBattery` IORegistry entry and the corresponding fields in the `PowerReading` data structure. Includes units and data types. ```text CurrentCapacity → current_capacity (mAh) MaxCapacity → max_capacity (mAh) IsCharging → is_charging (bool) ExternalConnected → external_connected (bool) Voltage → voltage (mV → V conversion) Amperage → amperage (mA → A conversion, negative = discharging) AppleRawAdapterDetails → charger info array [0].Watts → watts_negotiated [0].Name → charger_name [0].Manufacturer → charger_manufacturer [0].Voltage → charger voltage (mV) [0].Current → charger current (mA) ``` -------------------------------- ### Manage Power Monitor Database Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Provides commands to interact with the powermonitor database. View statistics, display recent readings, clean up old data, or analyze battery health. ```bash # View database statistics powermonitor stats ``` ```bash # View recent readings powermonitor history --limit 50 ``` ```bash # Clean up old data powermonitor cleanup --days 30 powermonitor cleanup --all # Requires confirmation ``` ```bash # Analyze battery health powermonitor health --days 60 ``` -------------------------------- ### Run Full Test Suite with Coverage Source: https://context7.com/narumiruna/power-monitor/llms.txt Executes all tests in the project and generates a coverage report using pytest. ```bash uv run pytest ``` -------------------------------- ### Run Tests with uv Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Executes the project's test suite using 'pytest' via the 'uv run' command. Ensure tests are available before running. ```bash # Run tests (when available) uv run pytest ``` -------------------------------- ### Launch Power Monitor TUI Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Launches the auto-updating Text User Interface for power monitoring. Customize display settings like data collection interval, statistics limit, chart limit, and debug mode. ```bash powermonitor ``` ```bash # Customize TUI settings powermonitor --interval 1.0 --stats-limit 100 --chart-limit 60 --debug ``` ```bash # Or using uv: uv run powermonitor ``` -------------------------------- ### Run Type Checking with `ty` Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Executes type checking for the project using the `ty` command. Ensure all type hints are correctly implemented. ```bash uv run ty check . ``` -------------------------------- ### Run Code Quality Checks Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Execute type checking and linting using 'uv run' with 'ty' and 'ruff'. This ensures code adheres to quality standards. ```bash # Type checking uv run ty check . # Linting uv run ruff check src/ # Auto-formatting uv run ruff format src/ # Run all checks uv run ty check . && uv run ruff check src/ && uv run ruff format src/ ``` -------------------------------- ### Lint and Format Code with Ruff Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Applies linting and formatting checks to the project's source code using 'ruff'. This ensures code quality and consistency. ```bash # Linting and formatting uv run ruff check src/ uv run ruff format src/ ``` -------------------------------- ### Configure Custom Database Path Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Specify a custom location for the SQLite database by modifying the configuration file. This allows for flexible data storage management. ```toml [database] path = "/path/to/custom.db" ``` -------------------------------- ### Perform Type Checking with uv Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Runs static type checking on the project's Python code using 'ty' via the 'uv run' command. This helps identify type-related errors. ```bash # Type checking uv run ty check . ``` -------------------------------- ### One-shot Data Collection Source: https://context7.com/narumiruna/power-monitor/llms.txt Performs a single data collection using the default collector and prints key metrics. Useful for testing collector selection. ```bash uv run python -c " from powermonitor.collector import default_collector c = default_collector(verbose=True) r = c.collect() print(f'{r.watts_actual:+.1f}W {r.battery_percent}% {r.voltage:.2f}V') " ``` -------------------------------- ### Run Tests and Manual Execution Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Commands to execute automated tests using pytest and to manually run the PowerMonitor application. ```bash # Run tests (when available) uv run pytest # Manual testing uv run powermonitor ``` -------------------------------- ### Run Development Mode with Verbose Collector Info Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Execute Python code in development mode using 'uv run'. This command enables verbose output from the collector, useful for debugging data collection. ```bash uv run python -c "from powermonitor.collector import default_collector; collector = default_collector(verbose=True); print(collector.collect())" ``` -------------------------------- ### Collect Battery Data with IORegCollector Source: https://context7.com/narumiruna/power-monitor/llms.txt Use IORegCollector as a fallback to gather battery information by parsing `ioreg` output. Handles potential command failures, parsing errors, and missing fields. ```python from powermonitor.collector.ioreg import IORegCollector from powermonitor.models import CommandFailedError, ParseError, MissingFieldError collector = IORegCollector() try: reading = collector.collect() print(f"Voltage: {reading.voltage:.2f}V") print(f"Amperage: {reading.amperage:.3f}A") print(f"Battery: {reading.battery_percent}% ({reading.current_capacity}/{reading.max_capacity} mAh)") print(f"Charger: {reading.charger_name} by {reading.charger_manufacturer}") print(f"Negotiated: {reading.watts_negotiated}W") except CommandFailedError as e: print(f"ioreg failed: {e}") except ParseError as e: print(f"Parse error: {e}") except MissingFieldError as e: print(f"Missing field: {e.field_name}") ``` -------------------------------- ### Run Power Monitor TUI Application Source: https://context7.com/narumiruna/power-monitor/llms.txt Instantiates and runs the Power Monitor Textual TUI application with a custom configuration. The app manages data collection and display. ```python from powermonitor.tui.app import PowerMonitorApp from powermonitor.config import PowerMonitorConfig config = PowerMonitorConfig( collection_interval=2.0, stats_history_limit=50, chart_history_limit=30, ) # Run the full TUI (blocking) PowerMonitorApp(config=config).run() ``` ```python # The app exposes these action methods (bound to keys): # action_refresh() → R key: force collect + update # action_clear_history() → C key: clear DB + refresh # action_quit() → Q/ESC: cancel loop, close DB, exit ``` -------------------------------- ### Manage Power Readings with SQLite Database Source: https://context7.com/narumiruna/power-monitor/llms.txt Utilize the Database class to persist power readings in an SQLite file. Supports insertion, querying history, calculating statistics, analyzing battery health trends, and data cleanup. Use as a context manager for automatic connection handling. ```python from pathlib import Path from powermonitor.database import Database from powermonitor.models import PowerReading from datetime import datetime, UTC db_path = Path("~/my-power.db").expanduser() # Idiomatic: use as context manager (auto-closes connection) with Database(db_path) as db: # Insert a reading reading = PowerReading( timestamp=datetime.now(tz=UTC), watts_actual=45.2, watts_negotiated=67, voltage=20.0, amperage=2.26, current_capacity=3800, max_capacity=4709, battery_percent=80, is_charging=True, external_connected=True, charger_name="USB-C Power Adapter", charger_manufacturer="Apple Inc.", ) row_id = db.insert_reading(reading) print(f"Inserted row {row_id}") # Query recent history (newest first) readings = db.query_history(limit=10) for r in readings: print(f"{r.timestamp:%H:%M:%S} {r.watts_actual:+.1f}W {r.battery_percent}%") # Statistics over last N readings stats = db.get_statistics(limit=100) # Returns: {"avg_watts", "min_watts", "max_watts", "avg_battery", # "earliest", "latest", "count"} print(f"Avg: {stats['avg_watts']:.1f}W Max: {stats['max_watts']:.1f}W") print(f"Count: {stats['count']} Range: {stats['earliest']} → {stats['latest']}") # Battery health trend (daily averages) trend = db.get_battery_health_trend(days=30) # Returns: list of (date_str, avg_max_capacity, reading_count) for date, avg_cap, count in trend: print(f"{date}: {avg_cap:.0f} mAh ({count} readings)") # Cleanup: remove readings older than 30 days deleted = db.cleanup_old_data(days=30) print(f"Deleted {deleted} old readings") # Clear all data total_deleted = db.clear_history() print(f"Cleared {total_deleted} readings") ``` -------------------------------- ### SQLite Database Schema for Power Readings Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Defines the SQL schema for the `power_readings` table, including columns for timestamp, power metrics, electrical details, battery state, and charger information. An index on timestamp is included for efficient querying. ```sql CREATE TABLE IF NOT EXISTS power_readings ( id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp TEXT NOT NULL, watts_actual REAL NOT NULL, watts_negotiated INTEGER NOT NULL, voltage REAL NOT NULL, amperage REAL NOT NULL, current_capacity INTEGER NOT NULL, max_capacity INTEGER NOT NULL, battery_percent INTEGER NOT NULL, is_charging INTEGER NOT NULL, external_connected INTEGER NOT NULL, charger_name TEXT, charger_manufacturer TEXT ); CREATE INDEX idx_timestamp ON power_readings(timestamp DESC); ``` -------------------------------- ### Lint Code Source: https://context7.com/narumiruna/power-monitor/llms.txt Checks the source code for style and potential errors using Ruff. ```bash uv run ruff check src/ ``` -------------------------------- ### View Power Monitor Reading History Source: https://context7.com/narumiruna/power-monitor/llms.txt Retrieves and displays historical power readings from the Power Monitor database. Allows specifying the number of readings to display. ```bash # Last 20 readings (default from config) powermonitor history ``` ```bash # Custom count powermonitor history --limit 50 powermonitor history -n 5 ``` -------------------------------- ### PowerMonitorConfig Dataclass Usage Source: https://context7.com/narumiruna/power-monitor/llms.txt The `PowerMonitorConfig` dataclass holds runtime settings. It normalizes log levels, expands paths, validates ranges, and warns for small collection intervals. Custom values can be provided during instantiation. ```python from pathlib import Path from powermonitor.config import PowerMonitorConfig # Use all defaults cfg = PowerMonitorConfig() print(cfg.collection_interval) # 1.0 print(cfg.database_path) # PosixPath('/Users/you/.powermonitor/powermonitor.db') # Custom values cfg = PowerMonitorConfig( collection_interval=0.5, stats_history_limit=200, chart_history_limit=90, database_path="~/Documents/power.db", # str is auto-converted to Path log_level="debug", # normalised → "DEBUG" ) # Validation errors raised immediately try: PowerMonitorConfig(collection_interval=-1) except ValueError as e: print(e) # collection_interval must be positive, got -1 try: PowerMonitorConfig(log_level="VERBOSE") except ValueError as e: print(e) # log_level must be one of DEBUG, ERROR, INFO, WARNING, got VERBOSE. ``` -------------------------------- ### Asyncio Background Data Collection Loop Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Implements a background loop for data collection using asyncio. It schedules periodic collection and updates, running blocking operations in an executor to prevent UI freezes. ```python async def _collection_loop(self) -> None: while True: await asyncio.sleep(self.config.collection_interval) # Default: 1.0s await self._collect_and_update() async def _collect_and_update(self) -> None: # Run blocking collector in executor (avoid blocking UI) loop = asyncio.get_event_loop() reading = await loop.run_in_executor(None, self.collector.collect) # Save to database await loop.run_in_executor(None, self.database.insert_reading, reading) # Update all widgets reactively self.call_from_thread(self._update_all_widgets, reading) ``` -------------------------------- ### Run Power Monitor Collector in Debug Mode Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Executes the power monitor data collector with verbose output enabled for debugging purposes. This is useful for inspecting the collector's internal state. ```bash # Run with verbose collector info (debug mode) uv run python -c "from powermonitor.collector import default_collector; default_collector(verbose=True).collect()" ``` -------------------------------- ### Export Power Monitor Data Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Export power readings to CSV or JSON format. Supports specifying a limit and manually setting the format. ```bash # Export to CSV (auto-detected from extension) powermonitor export data.csv # Export to JSON powermonitor export data.json # Export last 1000 readings powermonitor export data.csv --limit 1000 # Manually specify format powermonitor export backup.txt --format csv ``` -------------------------------- ### View Power Monitor History Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Displays recent power readings in a formatted table. The default limit is 20 readings, which can be adjusted with the --limit flag. ```bash # Show last 20 readings (default) powermonitor history # Show last 50 readings powermonitor history --limit 50 ``` -------------------------------- ### Use IOKitCollector for Direct SMC Access Source: https://context7.com/narumiruna/power-monitor/llms.txt Instantiate `IOKitCollector` for direct access to SMC sensors via ctypes. Set `verbose=True` to log all raw SMC values. The `collect()` method returns a `PowerReading` object. ```python from powermonitor.collector.iokit import IOKitCollector collector = IOKitCollector(verbose=True) reading = collector.collect() # With verbose=True, debug log shows all raw SMC values: # PPBR (Battery Power), PDTR (Power Input), PSTR (System Power), # PHPC (Heatpipe), PDBR (Display), TB0T (Battery Temp), CHCC (Charging) print(reading.watts_actual) # PDTR value if available # SMC sensors dictionary (informational) from powermonitor.collector.iokit.collector import SMC_SENSORS for key, description in SMC_SENSORS.items(): print(f"{key}: {description}") # PPBR: Battery power rate (W) - positive when discharging # PDTR: Power delivery/input rate (W) # PSTR: System total power consumption (W) # PHPC: Heatpipe/cooling power (W) # PDBR: Display brightness power (W) # TB0T: Battery temperature (°C) # CHCC: Charging status (0 = not charging) ``` -------------------------------- ### Analyze Power Monitor Battery Health Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Tracks battery degradation over time. Analyzes the last 30 days by default. ```bash # Analyze last 30 days (default) powermonitor health ``` -------------------------------- ### Update StatsPanel with statistics dictionary Source: https://context7.com/narumiruna/power-monitor/llms.txt Update the statistics panel with a dictionary containing aggregated power usage data. This is typically obtained from a database query. ```python stats_panel = StatsPanel(id="stats") stats_panel.update_stats({ "count": 100, "avg_watts": 42.3, "max_watts": 55.1, "min_watts": 12.4, "avg_battery": 74.5, "earliest": "2026-01-06T14:22:00", "latest": "2026-01-06T15:22:00", }) ``` -------------------------------- ### Export Power Monitor Data Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Exports collected power monitoring data to CSV or JSON format. Specify the output file name and an optional limit for the number of records to export. ```bash # Export data to CSV or JSON powermonitor export data.csv --limit 1000 powermonitor export data.json ``` -------------------------------- ### Power Readings Database Schema Source: https://context7.com/narumiruna/power-monitor/llms.txt SQL schema for the power_readings table. Stores detailed power metrics and timestamps. Note the default database path and configuration options. ```sql CREATE TABLE power_readings ( id INTEGER PRIMARY KEY, timestamp TEXT, -- ISO-8601 UTC datetime watts_actual REAL, -- positive=charging, negative=discharging watts_negotiated INTEGER, -- PD-negotiated max from charger (W) voltage REAL, -- V amperage REAL, -- A (negative=discharging) current_capacity INTEGER, -- mAh max_capacity INTEGER, -- mAh battery_percent INTEGER, -- 0-100 is_charging INTEGER, -- boolean external_connected INTEGER, -- boolean charger_name TEXT, -- nullable charger_manufacturer TEXT -- nullable ); CREATE INDEX idx_timestamp ON power_readings(timestamp DESC); ``` -------------------------------- ### Bump Version Source: https://context7.com/narumiruna/power-monitor/llms.txt Increments the project version number (e.g., patch version) and updates relevant files using bump-my-version. ```bash uv run bump-my-version bump patch # 0.0.9 → 0.0.10 ``` -------------------------------- ### Power Readings Database Schema Source: https://github.com/narumiruna/power-monitor/blob/main/README.md The SQL schema for the 'power_readings' table, used to store detailed power consumption data. Includes timestamp, power metrics, battery status, and charger information. ```sql CREATE TABLE power_readings ( id INTEGER PRIMARY KEY, timestamp TEXT, watts_actual REAL, watts_negotiated INTEGER, voltage REAL, amperage REAL, current_capacity INTEGER, max_capacity INTEGER, battery_percent INTEGER, is_charging INTEGER, external_connected INTEGER, charger_name TEXT, charger_manufacturer TEXT ); ``` -------------------------------- ### Update LiveDataPanel with PowerReading Source: https://context7.com/narumiruna/power-monitor/llms.txt Use this to update the live data panel with a fresh PowerReading object. Ensure the PowerReading object is correctly instantiated with all relevant metrics. ```python panel = LiveDataPanel(id="live-data") reading = PowerReading( timestamp=datetime.now(tz=UTC), watts_actual=45.2, watts_negotiated=67, voltage=20.0, amperage=2.26, current_capacity=3800, max_capacity=4709, battery_percent=80, is_charging=True, external_connected=True, charger_name="USB-C Power Adapter", charger_manufacturer="Apple Inc.", ) panel.update_reading(reading) ``` -------------------------------- ### Export Power Monitor Data Source: https://context7.com/narumiruna/power-monitor/llms.txt Exports Power Monitor readings to CSV or JSON format. Supports specifying the output file, limiting the number of exported rows, and forcing the output format. ```bash # Auto-detect format from extension powermonitor export readings.csv powermonitor export readings.json ``` ```bash # Limit rows exported powermonitor export readings.csv --limit 500 powermonitor export readings.json -n 100 ``` ```bash # Force format regardless of extension powermonitor export backup.txt --format csv powermonitor export backup.txt --format json ``` -------------------------------- ### Analyze Power Monitor Battery Health Source: https://context7.com/narumiruna/power-monitor/llms.txt Performs a battery health analysis based on historical data. Allows specifying the analysis period in days. ```bash # Analyse last 30 days (default) powermonitor health ``` ```bash # Analyse last 60 days powermonitor health --days 60 powermonitor health -d 90 ``` -------------------------------- ### Clean Up Power Monitor Data Source: https://github.com/narumiruna/power-monitor/blob/main/README.md Removes old readings to manage database size. Can delete readings older than a specified number of days or all readings. ```bash # Delete readings older than 30 days powermonitor cleanup --days 30 # Delete all readings (requires confirmation) powermonitor cleanup --all ``` -------------------------------- ### Analyze Battery Degradation Trend Source: https://context7.com/narumiruna/power-monitor/llms.txt Use `get_battery_health_trend` to analyze battery degradation by grouping `max_capacity` readings by day. Provides average capacity and reading count per day over a specified period. Includes error handling for invalid day counts. ```python from powermonitor.database import Database with Database() as db: trend = db.get_battery_health_trend(days=60) if len(trend) >= 2: first_cap = trend[0][1] last_cap = trend[-1][1] change_mah = last_cap - first_cap change_percent = (change_mah / first_cap) * 100 print(f"Start: {trend[0][0]} {first_cap:.0f} mAh") print(f"End: {trend[-1][0]} {last_cap:.0f} mAh") print(f"Change: {change_mah:+.0f} mAh ({change_percent:+.2f}%)") if change_percent < -2: print("Status: ⚠️ Degrading (significant)") elif change_percent < -0.5: print("Status: ⚠️ Degrading (normal wear)") else: print("Status: ✓ Stable") # Raises ValueError for non-positive days try: db.get_battery_health_trend(days=0) except ValueError as e: print(e) # days must be a positive integer ``` -------------------------------- ### PowerReading Data Model Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Represents a single power reading, including timestamp, power metrics, electrical details, battery state, and charging status. Used for data collection and storage. ```python @dataclass class PowerReading: timestamp: datetime # UTC timestamp # Power metrics watts_actual: float # Actual power (W): + = charging, - = discharging watts_negotiated: int # PD negotiated max power (W) # Electrical details voltage: float # Voltage (V) amperage: float # Current (A) # Battery state current_capacity: int # Current capacity (mAh) max_capacity: int # Max capacity (mAh) battery_percent: int # Battery percentage (0-100) # Status is_charging: bool external_connected: bool charger_name: str | None charger_manufacturer: str | None ``` -------------------------------- ### Handle Power Collector Errors Source: https://context7.com/narumiruna/power-monitor/llms.txt Catch specific exceptions like `MissingFieldError`, `CommandFailedError`, `ParseError`, `IOKitError`, or the general `PowerCollectorError` when collecting power data. Access error details like the missing field name. ```python from powermonitor.models import ( PowerCollectorError, CommandFailedError, # ioreg subprocess failed / timed out / not found ParseError, # plist parsing failed MissingFieldError, # required plist key absent IOKitError, # SMC/IOKit API error ) from powermonitor.collector import default_collector collector = default_collector() try: reading = collector.collect() except MissingFieldError as e: print(e.field_name) # e.g. "Voltage" except CommandFailedError as e: print(f"ioreg failed: {e}") except PowerCollectorError as e: print(f"Collection error: {e}") ``` -------------------------------- ### Update ChartWidget with PowerReading history Source: https://context7.com/narumiruna/power-monitor/llms.txt Update the chart widget with a list of PowerReading objects, ordered from newest to oldest. This is used to plot historical power data. ```python from powermonitor.database import Database with Database() as db: history = db.query_history(limit=60) chart = ChartWidget(id="chart") chart.update_chart(history) ``` -------------------------------- ### PowerCollector Protocol Definition Source: https://github.com/narumiruna/power-monitor/blob/main/CLAUDE.md Defines the interface for power data collection strategies. Implementations must provide a `collect` method that returns a `PowerReading` object. ```python class PowerCollector(Protocol): def collect(self) -> PowerReading: ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.