Introduction
DroidMetrics is a comprehensive HTTP API that exposes real-time Android device metrics via ADB (Android Debug Bridge). Monitor CPU frequency, memory usage, battery health, thermal sensors, and much more—all without root access or installing any Android application.
📱 Device Information
Model, manufacturer, Android version, SDK, hardware details
⚡ CPU Metrics
Core count, frequencies, governors, idle states, architecture
💾 Memory & Storage
RAM usage, swap, storage capacity, mount breakdown
🔋 Battery & Power
Charge level, health, temperature, voltage, current draw
🌡️ Thermal Monitoring
CPU, battery, skin temperatures, per-core readings
🌐 Network & Display
WiFi info, carrier, network type, screen size, density
Quick Start
Prerequisites
- Python 3.9 or higher
- ADB installed and available in PATH
- Android device with USB debugging enabled
- Device connected via USB or WiFi ADB
adb devices.
You should see your device listed with "device" status.
Clone the Repository
git clone https://github.com/josephsharon07/DroidMetrics.git
cd DroidMetrics/Python
Install Dependencies
pip install -r requirements.txt
This installs FastAPI, uvicorn, and other required packages.
Start the API Server
uvicorn main:app --host 0.0.0.0 --port 8001 --reload
Access the Documentation
Open your browser and navigate to:
- Swagger UI: http://localhost:8001/docs
- ReDoc: http://localhost:8001/redoc
- API Root: http://localhost:8001/
curl http://localhost:8001/battery
API Endpoints
🏥 Health & Diagnostics
Check API health and ADB connection status. Returns the current timestamp and connection state.
{
"status": "healthy",
"adb_connected": true,
"timestamp": "2026-02-07T10:30:45.123456"
}
API root endpoint listing all available endpoints with metadata.
📱 Device & OS Information
Retrieve comprehensive device information including model, manufacturer, hardware platform, and board details.
{
"model": "SM-F127G",
"manufacturer": "samsung",
"android_version": "13",
"sdk": 33,
"hardware": "exynos850",
"board": "universal3830"
}
Get operating system details including Android version, SDK level, security patch date, build ID, and kernel version.
{
"android_version": "13",
"sdk": 33,
"security_patch": "2024-12-01",
"build_id": "TP1A.220624.014",
"kernel_version": "5.10.0-android13-123456"
}
⚡ CPU Monitoring
Get CPU architecture information including core count, ABI (Application Binary Interface), and supported architectures.
{
"cores": 8,
"abi": "arm64-v8a",
"abi_list": ["arm64-v8a", "armeabi-v7a"],
"arch": "ARMv8"
}
Real-time CPU frequency monitoring for each core with comprehensive statistics. Returns current frequencies, min/max values, and averages in both kHz and MHz.
{
"per_core": {
"cpu0": 1800000,
"cpu1": 1800000,
"cpu2": 1300000,
"cpu3": 1300000,
"cpu4": 800000,
"cpu5": 800000,
"cpu6": 546000,
"cpu7": 546000
},
"min_khz": 546000,
"max_khz": 1800000,
"min_mhz": 546.0,
"max_mhz": 1800.0,
"avg_mhz": 1173.25,
"core_count": 8
}
Get CPU governor information per core. Governors control CPU frequency scaling behavior (e.g., performance, powersave, schedutil).
{
"per_core": {
"cpu0": "schedutil",
"cpu1": "schedutil",
"cpu2": "schedutil"
},
"available_governors": ["schedutil", "performance", "powersave"]
}
Get CPU idle state statistics showing how much time each core spends in different power-saving states.
💾 Memory & Storage
Retrieve RAM and swap memory statistics including total, available, used memory with usage percentages.
{
"total_mb": 3704.71,
"available_mb": 1236.54,
"used_mb": 2468.17,
"usage_percent": 66.6,
"swap_total_mb": 4096.0,
"swap_free_mb": 2729.53
}
Get internal storage information for the /data partition showing total, used, and free space in GB.
{
"filesystem": "/dev/block/dm-44",
"total_gb": 51.35,
"used_gb": 15.63,
"free_gb": 35.52,
"usage_percent": 30.5
}
Get detailed mount breakdown for all filesystems with size and usage information.
🔋 Battery & Power
Comprehensive battery information including charge level, health status, temperature, voltage, and charging state.
{
"level": 39,
"health": "Good",
"status": "Charging",
"voltage_mv": 3960,
"temperature_c": 34.6,
"technology": "Li-ion",
"is_charging": true
}
Power consumption metrics including current draw in milliamps, charge counter, and charging status.
{
"current_ma": 1022,
"charge_counter": 1865000,
"max_charging_current": 0,
"charging_status": "discharging"
}
🌡️ Thermal Monitoring
System thermal sensor readings including CPU, battery, and skin temperatures with min/max calculations.
{
"temperatures": {
"AP": 39.5,
"BAT": 34.6,
"SKIN": 35.4
},
"max_temp_c": 39.5,
"min_temp_c": 34.6
}
Per-core CPU temperatures if available from the thermal service.
🌐 Network & Display
Network configuration including hostname, WiFi IP/MAC addresses, carrier information, and data state.
Display metrics including screen resolution and pixel density (DPI).
⏱️ System
Device uptime information showing how long the device has been running since last boot.
Comprehensive system snapshot - Returns all metrics in a single request. Ideal for dashboards or monitoring applications that need complete device state.
Usage Examples
cURL Examples
curl http://localhost:8001/health
curl http://localhost:8001/battery | jq
curl http://localhost:8001/cpu/frequency | jq
curl http://localhost:8001/system | jq > device_snapshot.json
Python Client Example
import requests
import json
# Base URL
BASE_URL = "http://localhost:8001"
# Get battery information
response = requests.get(f"{BASE_URL}/battery")
battery_data = response.json()
print(f"Battery Level: {battery_data['level']}%")
print(f"Temperature: {battery_data['temperature_c']}°C")
print(f"Status: {battery_data['status']}")
print(f"Charging: {battery_data['is_charging']}")
# Get CPU frequency
cpu_freq = requests.get(f"{BASE_URL}/cpu/frequency").json()
print(f"\nCPU Average Frequency: {cpu_freq['avg_mhz']} MHz")
print(f"CPU Max Frequency: {cpu_freq['max_mhz']} MHz")
# Get complete system info
system = requests.get(f"{BASE_URL}/system").json()
print(f"\nDevice: {system['device']['manufacturer']} {system['device']['model']}")
print(f"Android Version: {system['os']['android_version']}")
print(f"Memory Usage: {system['memory']['usage_percent']}%")
print(f"Storage Usage: {system['storage']['usage_percent']}%")
JavaScript/Fetch Example
// Fetch battery data
fetch('http://localhost:8001/battery')
.then(response => response.json())
.then(data => {
console.log(`Battery: ${data.level}%`);
console.log(`Temperature: ${data.temperature_c}°C`);
console.log(`Charging: ${data.is_charging}`);
})
.catch(error => console.error('Error:', error));
// Async/await version
async function getDeviceMetrics() {
try {
const [cpu, memory, battery] = await Promise.all([
fetch('http://localhost:8001/cpu/frequency').then(r => r.json()),
fetch('http://localhost:8001/memory').then(r => r.json()),
fetch('http://localhost:8001/battery').then(r => r.json())
]);
console.log('CPU Avg:', cpu.avg_mhz, 'MHz');
console.log('Memory Usage:', memory.usage_percent, '%');
console.log('Battery Level:', battery.level, '%');
} catch (error) {
console.error('Failed to fetch metrics:', error);
}
}
getDeviceMetrics();
Monitoring Script
#!/bin/bash
# Simple monitoring script
API_URL="http://localhost:8001"
while true; do
clear
echo "=== Android Device Monitor ==="
echo ""
# Battery
battery=$(curl -s $API_URL/battery)
level=$(echo $battery | jq -r '.level')
temp=$(echo $battery | jq -r '.temperature_c')
echo "🔋 Battery: ${level}% @ ${temp}°C"
# Memory
memory=$(curl -s $API_URL/memory)
mem_usage=$(echo $memory | jq -r '.usage_percent')
echo "💾 Memory: ${mem_usage}%"
# CPU
cpu=$(curl -s $API_URL/cpu/frequency)
cpu_avg=$(echo $cpu | jq -r '.avg_mhz')
echo "⚡ CPU Avg: ${cpu_avg} MHz"
# Thermal
thermal=$(curl -s $API_URL/thermal)
max_temp=$(echo $thermal | jq -r '.max_temp_c')
echo "🌡️ Max Temp: ${max_temp}°C"
sleep 2
done
API Reference
Response Models
All endpoints return JSON with typed Pydantic models. Here are the key data structures:
| Model | Endpoint | Description |
|---|---|---|
DeviceInfo |
/device | Device hardware and manufacturer information |
OSInfo |
/os | Operating system and kernel details |
CPUInfo |
/cpu | CPU architecture and core count |
CPUFrequency |
/cpu/frequency | Real-time CPU frequency data |
CPUGovernorInfo |
/cpu/governors | CPU frequency scaling governors |
CPUIdleInfo |
/cpu/idle | CPU idle state statistics |
MemoryInfo |
/memory | RAM and swap usage statistics |
StorageInfo |
/storage | Internal storage capacity and usage |
BatteryInfo |
/battery | Battery health and charging status |
PowerInfo |
/power | Power consumption metrics |
ThermalInfo |
/thermal | System thermal sensor readings |
NetworkInfo |
/network | Network configuration and status |
DisplayInfo |
/display | Screen resolution and density |
SystemInfo |
/system | Complete system snapshot (all metrics) |
Error Handling
The API uses standard HTTP status codes:
200 OK- Request successful500 Internal Server Error- ADB command failed or parsing error503 Service Unavailable- ADB not connected or device offline
{
"detail": "ADB command failed: device offline",
"error": "ADB Error"
}
Caching
The API implements intelligent caching to reduce ADB overhead. Static data (device info, OS version) is cached for 5 minutes, while dynamic data (battery, CPU frequency) is fetched in real-time or cached for 30 seconds. You can see cache TTL values in the implementation.
CORS Support
CORS is enabled for all origins, making it easy to integrate with web-based dashboards and monitoring tools.
OpenAPI Schema
Full OpenAPI 3.0 schema is available at:
/openapi.json- Machine-readable OpenAPI schema/docs- Interactive Swagger UI/redoc- Alternative ReDoc documentation
C++ Implementation
A high-performance C++ version is also available using cpp-httplib. Build instructions:
cd Cpp/build
cmake ..
make
./adb_insight
Rate Limiting
No built-in rate limiting is implemented. For production use, consider adding rate limiting middleware or deploying behind a reverse proxy with rate limiting capabilities.
Advanced Usage
Building a Dashboard
DroidMetrics is perfect for building real-time monitoring dashboards. Here's a simple HTML dashboard example:
<!DOCTYPE html>
<html>
<head>
<title>Device Dashboard</title>
<style>
.metric { margin: 20px; padding: 20px; border: 1px solid #ddd; }
.metric h3 { margin: 0; }
.value { font-size: 2em; color: #4F46E5; }
</style>
</head>
<body>
<h1>Android Device Dashboard</h1>
<div id="dashboard"></div>
<script>
async function updateDashboard() {
const data = await fetch('http://localhost:8001/system').then(r => r.json());
document.getElementById('dashboard').innerHTML = `
<div class="metric">
<h3>Battery</h3>
<div class="value">${data.battery.level}%</div>
<div>${data.battery.temperature_c}°C</div>
</div>
<div class="metric">
<h3>Memory</h3>
<div class="value">${data.memory.usage_percent}%</div>
<div>${data.memory.used_mb.toFixed(0)} / ${data.memory.total_mb.toFixed(0)} MB</div>
</div>
<div class="metric">
<h3>CPU</h3>
<div class="value">${data.cpu_frequency.avg_mhz} MHz</div>
<div>${data.cpu.cores} cores</div>
</div>
`;
}
updateDashboard();
setInterval(updateDashboard, 2000); // Update every 2 seconds
</script>
</body>
</html>
Integration with Monitoring Tools
DroidMetrics can be integrated with popular monitoring stacks:
- Prometheus: Create an exporter that polls DroidMetrics endpoints
- Grafana: Use the JSON API datasource to visualize metrics
- InfluxDB: Write a bridge script to store metrics time-series data
- Home Assistant: Create custom sensors using REST platform
Running in Production
- Use a production ASGI server like Gunicorn with Uvicorn workers
- Set up reverse proxy (nginx/Apache) for SSL and rate limiting
- Configure firewall rules to restrict access
- Consider authentication middleware for sensitive deployments
- Monitor ADB connection stability and implement auto-reconnection