Files
battery-monitor/TOOL-GUIDE.md
denq a4bc66a745 Implement unified uConsole Smart Power Regulator with AC detection
Major overhaul of power management system to address voltage-induced 4G
module hangs through intelligent, event-driven power regulation.

Key Features:
- Unified power regulation based on AC power + 4G modem state
- Event-driven AC detection via udev (power_supply subsystem)
- Three optimized power modes for different scenarios
- Automatic voltage monitoring with multi-method alerts

Power Modes:
- AC Connected: 2.4GHz (ondemand) - full performance
- Battery + 4G: 1.8GHz (powersave) - voltage monitoring enabled
- Battery Only: 2.0GHz (ondemand) - balanced performance

Technical Improvements:
- AC power state detection via udev events (not polling)
- Edge case handling (service starts with AC connected)
- Unified logging to /var/log/uconsole-power-regulator.log
- Upgrade path from old 4G Power Manager
- State tracking to avoid redundant regulator triggers

Components:
- uconsole-power-regulator.sh: Main power orchestrator
- uconsole-power-daemon.sh: Background state monitoring (5s interval)
- voltage-monitor.sh: Voltage checker (Battery + 4G only)
- voltage-alert-notify.sh: Multi-method alerts (desktop/audio/log/LED)
- voltage-monitor-control.sh: Monitor lifecycle controller
- 99-uconsole-power-regulator.rules: udev event triggers
- install-uconsole-power-regulator.sh: Installation + upgrade script

Documentation:
- Updated README.md with new system overview
- Created README_CN.md (Chinese translation)
- Updated TOOL-GUIDE.md with new architecture details
- Updated CLAUDE.md with unified system documentation

Breaking Changes:
- Replaces 4G Power Manager with unified regulator
- New service name: uconsole-power-regulator.service
- New log file: /var/log/uconsole-power-regulator.log
- Use upgrade script to migrate from old system

Installation:
- Fresh: sudo ./install-uconsole-power-regulator.sh install
- Upgrade: sudo ./install-uconsole-power-regulator.sh upgrade
- Uninstall: sudo ./install-uconsole-power-regulator.sh uninstall
2025-11-06 17:00:13 +08:00

16 KiB
Raw Permalink Blame History

Battery Monitor Tool: Complete User Guide

Comprehensive documentation for the uConsole Battery Monitor and 4G Power Manager

This tool was created to solve the uConsole CM5's 4G module hang issue and evolved into a complete battery analysis toolkit. For the story behind this tool, see STORY.md.

Table of Contents


Quick Start

Installation

# Clone the repository
git clone https://hiwifi.denq.us:8418/denq/battery-monitor.git
cd battery-monitor

# Install dependencies
npm install

# Run the development server
npm run dev

Visit http://localhost:3000 in your browser.

First Use

  1. Start Monitoring: Click the "Start Monitoring" button
  2. Observe Real-Time Data: Watch voltage, current, power, and percentage update every 2 seconds
  3. Start Recording (optional): Click "Start Recording" to save data to the database
  4. Export Data: Download session data as CSV for further analysis

Battery Monitor Features

Two Operating Modes

1. Live Mode (Default)

  • All charts visible with real-time updates
  • Best for active monitoring and analysis
  • Higher power consumption due to chart rendering

2. Background Mode (Battery Saving)

  • Charts hidden, only stats displayed
  • Same data collection granularity
  • Saves ~20-40% power through reduced rendering
  • Perfect for long recording sessions

Toggle between modes using the "Live Mode" / "Background Mode" button.

Monitoring vs. Recording

The tool separates monitoring (display only) from recording (database writes):

Monitoring Mode:

  • Click "Start Monitoring"
  • Data displayed in real-time
  • Last 100 points shown in charts
  • Up to 1000 points buffered in memory
  • No database writes

Recording Mode:

  • Click "Start Recording" while monitoring
  • Choose recording start point:
    • "Record from now": New data only
    • "Record from monitoring start": Saves all buffered data since monitoring began
  • Creates a session in database
  • All subsequent readings saved
  • Session metadata updated on stop

Real-Time Metrics

The status card displays:

  • Charge: Current battery percentage (0-100%)
  • Voltage: Real-time voltage in volts (V)
  • Current: Charge/discharge current in amps (A)
    • Positive = charging
    • Negative = discharging
  • Power: Instantaneous power in watts (W)
    • Positive = charging
    • Negative = discharging
  • Status: Charging, Discharging, Full, or Unknown
  • Capacity: Current/Full capacity in watt-hours (Wh)
  • System Up: Total system uptime

Understanding the Charts

1. Battery Percentage

Battery Percentage Chart

Purpose: Shows battery charge level over time

Reading the chart:

  • Y-axis: Percentage (0-100%)
  • X-axis: Time
  • Slope indicates discharge/charge rate
  • Steeper slope = faster discharge

Use cases:

  • Monitor discharge rate under different loads
  • Verify charging behavior
  • Estimate remaining runtime

2. Power Consumption

Purpose: Displays real-time power draw or input

Reading the chart:

  • Negative values: System consuming power (discharging)
  • Positive values: Charging (rare in typical usage)
  • Spikes indicate high-power activities

Use cases:

  • Identify power-hungry processes
  • Observe 4G module transmission bursts
  • Optimize power consumption

Voltage & Current Chart

Purpose: Dual-axis chart showing voltage and current simultaneously

Reading the chart:

  • Left Y-axis: Voltage (V) - orange line
  • Right Y-axis: Current (A) - green line
  • X-axis: Time
  • Legend shows current values on hover

Key observations:

  • Voltage should stay above 3.45V for stable 4G operation
  • High current draw causes voltage sag
  • Voltage recovery when current drops

Use cases:

  • Diagnose voltage drop issues
  • Correlate current spikes with voltage sag
  • Monitor battery internal resistance (voltage sag magnitude)

4. Battery Energy Output vs. Voltage NEW

Energy Output vs Voltage

Purpose: The most critical chart for battery selection - shows discharge curve with voltage threshold

Reading the chart:

  • X-axis: Energy output in milliwatt-hours (mWh)
  • Y-axis: Battery voltage (V)
  • Red dashed line: 3.45V threshold (4G module minimum)
  • Purple line: Actual voltage decay during discharge

Key insight:

  • Everything to the RIGHT of where voltage crosses 3.45V is unusable for 4G
  • This chart answers: "How much usable capacity does this battery have for 4G operation?"

Example (FEB-4000 batteries):

  • Total capacity: 24,790 mWh
  • Voltage crosses 3.45V at: 13,387 mWh
  • Usable capacity: 13,387 mWh (54%)
  • Unusable capacity: 11,403 mWh (46%)

Use cases:

  • Rate batteries for 4G compatibility
  • Compare different battery models
  • Determine when to recharge for reliable 4G
  • Understand real vs. advertised capacity

Battery Testing Guide

How to Test Your Batteries

  1. Fully Charge Batteries: Charge to 100% before testing
  2. Start Monitoring: Click "Start Monitoring"
  3. Start Recording: Choose "Record from monitoring start"
  4. Name Your Session: Edit session name (e.g., "Samsung-30Q-Test")
  5. Enable 4G Module: Turn on 4G for realistic load
  6. Let It Discharge: Run until voltage drops to ~3.3V (or system shuts down)
  7. Stop Recording: Click "Stop Recording"
  8. Analyze Results: View session data and export CSV

What to Look For

Good Batteries for 4G:

Voltage stays above 3.45V for >50% of capacity Gradual voltage decay under load Low voltage sag during current spikes High usable capacity above 3.45V threshold

Poor Batteries for 4G:

Voltage drops below 3.45V early (<30% capacity used) Steep voltage drops under load Large voltage sag (>0.2V) during current spikes Low usable capacity above 3.45V

For consistent results:

  • Same load (4G module enabled)
  • Full discharge cycle (100% → protection cutoff)
  • Room temperature (20-25°C)
  • No charging during test
  • Minimal other activity (close apps, disable wifi if testing 4G-only)

Interpreting Results

Usable Capacity Calculation:

Usable Capacity (mWh) = Initial Capacity - Capacity at 3.45V crossing
Usable Percentage = (Usable Capacity / Total Capacity) × 100%

Battery Rating:

  • Excellent: >60% usable capacity above 3.45V
  • Good: 50-60% usable capacity
  • Acceptable: 40-50% usable capacity
  • Poor: <40% usable capacity (consider replacement)

uConsole Smart Power Regulator

What It Does

Intelligently manages CPU performance and monitors battery voltage based on power source and 4G module status to prevent system hangs caused by voltage drops below 3.45V.

How It Works

The unified system combines three monitoring mechanisms:

  1. Event-Driven Detection (udev events):

    • AC power connect/disconnect events
    • 4G modem USB device changes
    • Network interface (wwan0) state changes
    • Modem serial port changes
  2. Background Daemon (5-second polling):

    • Monitors 4G modem state continuously
    • Monitors AC power status
    • Triggers regulator only when state changes
    • Handles edge cases (e.g., service starts with AC connected)
  3. Voltage Monitoring (when Battery + 4G active):

    • Checks voltage every 5 seconds
    • Alerts when voltage < 3.45V
    • Multiple alert methods: desktop notification, audio, log, LED blink
    • Rate-limited to every 30 seconds

Power Modes

Condition CPU Governor Max Frequency Voltage Monitoring
AC Connected ondemand 2.4GHz Off
Battery + 4G powersave 1.8GHz On (< 3.45V alerts)
Battery Only ondemand 2.0GHz Off

Installation

Fresh Install:

cd scripts
sudo ./install-uconsole-power-regulator.sh install

Upgrade from old 4G Power Manager:

cd scripts
sudo ./install-uconsole-power-regulator.sh upgrade

Uninstall:

cd scripts
sudo ./install-uconsole-power-regulator.sh uninstall

What it installs:

  • uconsole-power-regulator.sh - Main power regulation orchestrator
  • uconsole-power-daemon.sh - Background state monitoring daemon
  • voltage-monitor.sh - Voltage monitoring script (runs when Battery + 4G)
  • voltage-alert-notify.sh - Multi-method alert system
  • voltage-monitor-control.sh - Start/stop voltage monitor
  • /etc/udev/rules.d/99-uconsole-power-regulator.rules - udev event triggers
  • /etc/systemd/system/uconsole-power-regulator.service - Systemd service
  • /var/log/uconsole-power-regulator.log - Unified log file

Verification

Check if service is running:

sudo systemctl status uconsole-power-regulator

View recent logs:

sudo tail -f /var/log/uconsole-power-regulator.log

Check voltage monitor status:

sudo /usr/local/bin/voltage-monitor-control.sh status

Tuning

Edit /home/pi/battery-monitor/scripts/uconsole-power-regulator.sh to customize power modes:

# Configuration options
AC_GOVERNOR="ondemand"           # Governor when AC connected
BATTERY_GOVERNOR="ondemand"      # Governor on battery without 4G
POWERSAVE_GOVERNOR="powersave"   # Governor on battery with 4G

MAX_FREQ_AC="2400000"            # 2.4GHz - AC power, full performance
MAX_FREQ_BATTERY="2000000"       # 2.0GHz - battery only, balanced
MAX_FREQ_POWERSAVE="1800000"     # 1.8GHz - battery + 4G (try 1500000 for more savings)

# Performance configuration
MAX_FREQ_PERFORMANCE="2400000"   # Full CM5 speed
PERFORMANCE_GOVERNOR="ondemand"  # Or "schedutil"

After editing, restart the service:

sudo systemctl restart 4g-power-monitor

API Reference

Endpoints

GET /api/battery

Get current battery status

Response:

{
  "timestamp": "2025-11-06T12:00:00.000Z",
  "percentage": 75,
  "voltage": 3.85,
  "current": -1.5,
  "power": -5.775,
  "status": "Discharging",
  "health": "Good",
  "acConnected": false,
  "capacityFull": 24.8,
  "capacityNow": 18.6,
  "capacityDesign": 25.0,
  "systemUptime": 12345
}

GET /api/battery?save=true&sessionId=123

Get current battery status and save to database

Query parameters:

  • save: Set to true to save reading
  • sessionId: Optional session ID to associate reading with

GET /api/battery/history?start=<ISO>&end=<ISO>

Query historical readings by time range

Query parameters:

  • start: ISO 8601 timestamp (start of range)
  • end: ISO 8601 timestamp (end of range)

Response: Array of battery readings

GET /api/battery/sessions

List all recording sessions

Response:

[
  {
    "id": 1,
    "name": "FEB-4000 Test",
    "start_time": "2025-11-06T11:29:25.000Z",
    "end_time": "2025-11-06T14:17:51.000Z",
    "reading_count": 4318,
    "energy_wh": 17.874,
    "duration_seconds": 10106
  }
]

GET /api/battery/sessions/:id

Get all readings for a specific session

Response: Array of battery readings for the session

POST /api/battery/sessions

Create a new recording session

Request body:

{
  "start_time": "2025-11-06T11:29:25.000Z",
  "end_time": "2025-11-06T11:29:25.000Z",
  "name": "My Test Session"
}

Response:

{
  "id": 123
}

PATCH /api/battery/sessions/:id

Update session name or end time

Request body:

{
  "name": "Updated Session Name",
  "end_time": "2025-11-06T14:17:51.000Z",
  "reading_count": 4318
}

DELETE /api/battery/sessions/:id

Delete a session and all associated readings

POST /api/battery/save

Save buffered readings (used for retroactive recording)

Request body:

{
  "readings": [...],
  "sessionId": 123
}

Troubleshooting

Battery Monitor

Issue: "Unable to read battery data" error

Solution:

  • Ensure you're running on uConsole or compatible hardware
  • Check sysfs path exists: ls /sys/class/power_supply/axp20x-battery/
  • Verify permissions (may need to run dev server with sudo)

Issue: Charts not updating

Solution:

  • Refresh the page
  • Check browser console for errors
  • Ensure monitoring is active (green "Monitoring" badge visible)

Issue: Database errors when recording

Solution:

  • Check disk space: df -h
  • Verify battery-data.db permissions
  • Check SQLite is working: npm run dev should create DB automatically

4G Power Manager

Issue: 4G module still hangs

Solution:

  1. Check if service is running: sudo systemctl status 4g-power-monitor
  2. View logs: sudo tail -f /var/log/4g-power-manager.log
  3. Verify frequency is being changed: cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_max_freq
  4. Try lower frequency: Edit script, set MAX_FREQ_POWERSAVE="1500000"
  5. Check battery voltage in real-time during 4G use (should stay >3.45V)

Issue: Service won't start

Solution:

# Check service status
sudo systemctl status 4g-power-monitor

# View service logs
sudo journalctl -u 4g-power-monitor -n 50

# Reinstall
cd scripts
sudo ./install-4g-power-manager.sh uninstall
sudo ./install-4g-power-manager.sh

Issue: udev rules not triggering

Solution:

# Reload udev rules
sudo udevadm control --reload-rules
sudo udevadm trigger

# Check if rules are loaded
sudo udevadm control --reload

Advanced Usage

Custom Time Range Export

  1. Navigate to "Export Custom Time Range" card
  2. Set start date/time
  3. Set end date/time
  4. Click "Load Data" to preview
  5. Click "Export CSV" to download

Session Management

Rename a session:

  • Click the edit icon (pencil) next to session name
  • Type new name
  • Press Enter or click checkmark

Delete a session:

  • Click the trash icon
  • Confirm deletion
  • Session and ALL associated readings are permanently deleted

Download session data:

  • Click the download icon
  • CSV file downloads with session name

CSV Data Format

Exported CSV contains:

timestamp,percentage,voltage,current,power,status,health,ac_connected,capacity_full,capacity_now,capacity_design
2025-11-06T12:00:00.000Z,75,3.85,-1.5,-5.775,Discharging,Good,false,24.8,18.6,25.0

Database Schema

monitoring_sessions table:

  • id - Auto-increment primary key
  • name - Session name (editable)
  • start_time - ISO 8601 timestamp
  • end_time - ISO 8601 timestamp
  • reading_count - Number of readings
  • created_at - Database insertion time

battery_readings table:

  • id - Auto-increment primary key
  • session_id - Foreign key to sessions (nullable)
  • timestamp - Reading timestamp
  • percentage, voltage, current, power - Battery metrics
  • status, health, ac_connected - State info
  • capacity_full, capacity_now, capacity_design - Energy capacity
  • created_at - Database insertion time

Development

Run in production mode:

npm run build
npm start

Run tests:

npm test

Lint code:

npm run lint

Contributing

Contributions welcome! Areas for improvement:

  • Additional chart types
  • Battery comparison tools
  • Export formats (JSON, XML)
  • Mobile-responsive design improvements
  • Internationalization (i18n)

Submit issues or PRs:


License

GPL v3 - Same as uConsole hardware designs


Credits

Created by: denq Powered by: Next.js 16, React 19, Recharts, SQLite Built with: Claude Code (AI-assisted development) Hardware: ClockworkPi uConsole CM5

Community contributors:

  • Battery test data submissions
  • 4G power manager feedback
  • Bug reports and feature requests

Further Reading


Last updated: November 2025 Tool version: 1.0 Compatible with: uConsole CM5, Raspberry Pi CM4/CM5 with AXP20x battery management