feat(hud): add battery runtime estimate to DD overlay ( hud ) (#2573)

This commit is contained in:
LunaDL authored and GitHub committed 2026-11-13 21:41:44 -05:00
1 parent 30d103280b
commit f502b8b3e6
43 files changed
+380 -146

No files matched your search

@@ -9,7 +9,7 @@ internal object DroidDeckHudConfig {
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showBatteryTime" to "0", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
@@ -37,11 +37,11 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
fun from(token: String?): DroidDeckHudSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "1% low", "0.1% low", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val MINIMAL_CHIPS = setOf("FPS", "Battery time", "FPS graph", "1% low", "0.1% low", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "Battery time", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val STANDARD_CHIPS = setOf(
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
"Battery", "GPU model", "Engine", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
"Battery", "Battery time", "GPU model", "Engine", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
)
val MEGA_ONLY = setOf(
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
@@ -87,6 +87,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showVram = true
private var showRAM = true
private var showBattery = true
private var showBatteryTime = true
private var showPower = true
private var showBatteryTemp = false
private var showGraph = false
@@ -308,6 +309,7 @@ class DroidDeckHudView(context: Context) : View(context) {
showVram = cfg.get("showVram", "1") == "1"
showRAM = cfg.get("showRAM", "1") == "1"
showBattery = cfg.get("showBattery", "1") == "1"
showBatteryTime = cfg.get("showBatteryTime", "1") == "1"
showPower = cfg.get("showPower", "1") == "1"
showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1"
showGraph = cfg.get("showFPSGraph", "0") == "1"
@@ -758,6 +760,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
if (any) rows.add(HudRow(Span("BAT", colBat, rowPx), v))
}
if (showBatteryTime) rows.add(HudRow(Span("TIME", colBat, rowPx), listOf(Span(s.battery.runtimeText ?: "—", colValue, rowPx))))
if (showFPS) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
@@ -843,6 +846,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showPower && s.battery.watts > 0f) { if (any) parts += Span(" · ", colDim, subPx); parts += numUnit(fmt1(s.battery.watts), "W", valPx, unitPx); any = true }
if (any) tiles.add(Tile("BAT", colBat, parts, null, true))
}
if (showBatteryTime) tiles.add(Tile("BAT TIME", colBat, listOf(Span(s.battery.runtimeText ?: "—", colValue, valPx)), "", true))
if (tiles.isEmpty()) { contentW = 0f; contentH = 0f; return }
val keyH = lineH(keyPx); val valH = lineH(valPx); val subH = lineH(subPx)
@@ -890,40 +894,39 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun buildPill(s: HudMetrics.Snapshot) {
val bigPx = sp(30f); val bigUnitPx = bigPx * 0.36f; val stkPx = sp(11.5f)
val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f)
val left = ArrayList<Span>()
val generating = differs(fpsNow)
val fpsPx = if (generating) bigPx * 0.55f else bigPx
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
if (showFPS) {
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
} else if (showBatteryTime) left += Span(s.battery.runtimeText ?: "TIME —", colBat, bigPx * 0.8f)
val stack = ArrayList<List<Span>>()
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
run {
val l = ArrayList<Span>()
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
if (showGPU && s.gpuPercent != null) l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx)
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
if (l.isNotEmpty()) stack.add(l)
}
if (showRAM) stack.add(listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx)))
if (showBattery || showPower || showBatteryTemp) {
val l = ArrayList<Span>()
fun part(spans: List<Span>) {
l += if (l.isEmpty()) Span("BAT ", colBat, stkPx) else Span(" · ", colDim, stkPx)
l += spans
}
fun part(spans: List<Span>) { l += if (l.isEmpty()) Span("BAT ", colBat, stkPx) else Span(" · ", colDim, stkPx); l += spans }
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, stkPx)))
if (showBatteryTemp && s.battery.tempC != null)
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, stkPx, stkPx * 0.62f))
if (showBatteryTemp && s.battery.tempC != null) part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, stkPx, stkPx * 0.62f))
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, stkPx)))
if (l.isNotEmpty()) stack.add(l)
}
if (showBatteryTime) stack.add(listOf(Span("BAT TIME ${s.battery.runtimeText ?: "—"}", colBat, stkPx)))
run {
val l = ArrayList<Span>()
l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
if (displayServer.isNotBlank()) { l += Span(" · ", colDim, stkPx); l += Span(displayServer, colDisp, stkPx) }
if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
stack.add(l)
if (showFPS) l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
if (showFPS && displayServer.isNotBlank()) { l += Span(" · ", colDim, stkPx); l += Span(displayServer, colDisp, stkPx) }
else if (displayServer.isNotBlank()) l += Span(displayServer, colDisp, stkPx)
if (showVram && s.vramText() != null) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
if (l.isNotEmpty()) stack.add(l)
}
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
@@ -931,13 +934,11 @@ class DroidDeckHudView(context: Context) : View(context) {
for (l in stack) statsW = max(statsW, runWidth(l))
val nameOnTop = gpuName != null && runWidth(gpuName) > statsW
if (gpuName != null && !nameOnTop) stack.add(0, gpuName)
val apiStr = apiLabel()
val hasApi = apiStr != "FPS"
val hasApi = showFPS && apiStr != "FPS"
val apiH = if (hasApi) lineH(stkPx) else 0f
val apiGap = if (hasApi) stkLineGap else 0f
val leftW = runWidth(left); val leftH = lineH(bigPx)
val leftW = runWidth(left); val leftH = if (left.isEmpty()) 0f else lineH(bigPx)
val apiW = if (hasApi) measure(apiStr, stkPx) else 0f
val leftBlockW = max(leftW, apiW)
val leftColH = apiH + apiGap + leftH
@@ -949,23 +950,13 @@ class DroidDeckHudView(context: Context) : View(context) {
val topLineH = if (nameOnTop) stkH + stkLineGap else 0f
contentW = pad + leftBlockW + midGap + stackW + pad
contentH = pad + topLineH + innerH + pad
var ly = pad + topLineH + (innerH - leftColH) / 2f
if (hasApi) {
placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx)))
ly += apiH + apiGap
}
placeRun(pad, ly - ascent(bigPx), left)
if (hasApi) { placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx))); ly += apiH + apiGap }
if (left.isNotEmpty()) placeRun(pad, ly - ascent(bigPx), left)
var sy = pad + topLineH + (innerH - stackTotalH) / 2f
for (l in stack) {
placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l)
sy += stkH + stkLineGap
}
for (l in stack) { placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l); sy += stkH + stkLineGap }
addSubtleClock(pad, leftAligned = true)
if (nameOnTop && gpuName != null) {
val end = placeRun(pad, pad - ascent(stkPx), gpuName)
contentW = max(contentW, end + pad)
}
if (nameOnTop && gpuName != null) { val end = placeRun(pad, pad - ascent(stkPx), gpuName); contentW = max(contentW, end + pad) }
}
private fun buildMinimal(s: HudMetrics.Snapshot) {
@@ -973,55 +964,39 @@ class DroidDeckHudView(context: Context) : View(context) {
val stroke = outlineWidth()
val left = contentLeft()
val inner = panelInset() + stroke
val runtime = if (showBatteryTime) s.battery.runtimeText ?: "TIME —" else null
val minGenerating = differs(fpsNow)
val big = listOf(
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
val big = when {
showFPS -> listOf(Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx), Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
runtime != null -> listOf(Span(runtime, colBat, sp(24f)))
else -> emptyList()
}
val sub = ArrayList<Span>()
fun low(label: String, value: Float) {
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
sub += Span("$label ", colDim, subPx)
sub += Span(lowText(value) ?: "—", colFps, subPx)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
.filter { it.isNotBlank() }.joinToString(" · ")
if (showFPS && showLow1) low("1%", lows.low1Fps)
if (showFPS && showLow01) low("0.1%", lows.low01Fps)
if (showFPS && showLow001) low("0.01%", lows.low001Fps)
if (showBatteryTime) {
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
sub += Span("BAT TIME ", colBat, subPx)
sub += Span(s.battery.runtimeText ?: "—", colBat, subPx)
}
val footerLabel = listOf(if (showFPS && showEngine) engineLabel else "", if (showFPS) displayServer else "").filter { it.isNotBlank() }.joinToString(" · ")
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
val (headerBottom, headerRight) = addPanelHeader(left, inner)
val x = headerRight
val colW = maxOf(runWidth(big), runWidth(sub), x - left,
max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f)
val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx)
placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true)
var last = bigBase
if (sub.isNotEmpty()) {
last += sp(10f) + capHeight(subPx)
placeRun(left - inkLeft(sub[0].text, subPx), last, sub)
}
if (showGraph) {
val top = last + sp(9f)
graphRect = RectF(left, top, left + colW, top + sp(24f))
last = top + sp(24f)
}
if (footerLabel.isNotBlank()) {
val base = last + sp(8f) + capHeight(footPx)
glyphs.add(Glyph(left - inkLeft(footerLabel, footPx), base, footerLabel, blend(colDim), footPx))
last = base
}
if (hdr.isNotEmpty()) {
val base = last + sp(6f) + capHeight(footPx)
placeRun(left - inkLeft(hdr[0].text, footPx), base, hdr)
last = base
}
val colW = maxOf(runWidth(big), runWidth(sub), headerRight - left, max(measure(footerLabel, footPx), runWidth(hdr)), if (showFPS && showGraph) sp(120f) else 0f)
var last = headerBottom + sp(8f)
if (big.isNotEmpty()) { last += capHeight(big[0].sizePx); placeRun(left - inkLeft(big[0].text, big[0].sizePx), last, big, glow = showFPS) }
if (sub.isNotEmpty()) { last += sp(10f) + capHeight(subPx); placeRun(left - inkLeft(sub[0].text, subPx), last, sub) }
if (showFPS && showGraph) { val top = last + sp(9f); graphRect = RectF(left, top, left + colW, top + sp(24f)); last = top + sp(24f) }
if (footerLabel.isNotBlank()) { val base = last + sp(8f) + capHeight(footPx); glyphs.add(Glyph(left - inkLeft(footerLabel, footPx), base, footerLabel, blend(colDim), footPx)); last = base }
if (hdr.isNotEmpty()) { val base = last + sp(6f) + capHeight(footPx); placeRun(left - inkLeft(hdr[0].text, footPx), base, hdr); last = base }
measurePaint.textSize = footPx
val panel = RectF(panelLeft(), panelInset(), left + colW + sp(34f), last + measurePaint.fontMetrics.descent + sp(9f) + stroke)
finishPanel(panel, halfRound = true)
finishPanel(RectF(panelLeft(), panelInset(), left + colW + sp(34f), last + measurePaint.fontMetrics.descent + sp(9f) + stroke), halfRound = true)
}
private fun buildStrip(s: HudMetrics.Snapshot) {
@@ -1045,14 +1020,16 @@ class DroidDeckHudView(context: Context) : View(context) {
right -= groupGap
}
val generating = differs(fpsNow)
val fps = ArrayList<Span>()
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
fps += Span("fps", colDim, unitPx)
x = placeRun(x, baseline, fps) + groupGap
if (showFPS) {
val generating = differs(fpsNow)
val fps = ArrayList<Span>()
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
fps += Span("fps", colDim, unitPx)
x = placeRun(x, baseline, fps) + groupGap
}
if (showGraph) {
if (showFPS && showGraph) {
val gw = sp(72f); val gh = h * 0.55f
if (x + gw <= right) {
graphRect = RectF(x, mid - gh / 2f, x + gw, mid + gh / 2f)
@@ -1068,9 +1045,9 @@ class DroidDeckHudView(context: Context) : View(context) {
l += Span("$label ", colDim, rowPx)
l += Span(lowText(value) ?: "—", colFps, rowPx)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
if (showFPS && showLow1) low("1%", lows.low1Fps)
if (showFPS && showLow01) low("0.1%", lows.low01Fps)
if (showFPS && showLow001) low("0.01%", lows.low001Fps)
if (l.isNotEmpty()) groups += l
}
if (showGPU || showGpuTemp) {
@@ -1099,6 +1076,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, rowPx)))
if (l.isNotEmpty()) groups += l
}
if (showBatteryTime) groups += listOf(Span("BAT TIME ${s.battery.runtimeText ?: "—"}", colBat, rowPx))
if (displayServer.isNotBlank()) groups += listOf(Span(displayServer, colDisp, rowPx))
if (hdrState != DroidDeckHudHdr.NONE) groups += hdrLine(rowPx)
if (showGpuModel && gpuNameText().isNotBlank()) groups += gpuModelSpans(rowPx, colDim, compact = true)
@@ -1228,6 +1206,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
if (any) right.add(HudRow(Span("BAT", colBat, rowPx), v))
}
if (showBatteryTime) right.add(HudRow(Span("TIME", colBat, rowPx), listOf(Span(s.battery.runtimeText ?: "—", colValue, rowPx))))
if (showFPS) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
@@ -14,6 +14,8 @@
package com.droiddeck.launcher.hud;
import com.droiddeck.launcher.session.BatteryRuntimeEstimator;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
@@ -560,10 +562,9 @@ public class HudMetrics {
return sawSignal;
}
private Double smoothedBatteryRuntimeHours = null;
private static final double MAX_RUNTIME_HOURS = 72.0;
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
private final BatteryRuntimeEstimator batteryRuntimeEstimator = new BatteryRuntimeEstimator();
private Boolean lastBatteryDischarging = null;
private Boolean lastBatteryCharging = null;
public Battery collectBattery() {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
@@ -581,11 +582,22 @@ public class HudMetrics {
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
boolean discharging = st == BatteryManager.BATTERY_STATUS_DISCHARGING
|| st == BatteryManager.BATTERY_STATUS_NOT_CHARGING;
if (lastBatteryDischarging != null && lastBatteryDischarging.booleanValue() != discharging) {
batteryRuntimeEstimator.reset();
}
lastBatteryDischarging = discharging;
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
Boolean sysCharging = readChargingFromPowerSupply();
if (sysCharging != null) charging = sysCharging;
}
long currentMicroAmps = Math.abs(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
if (lastBatteryCharging != null
&& lastBatteryCharging.booleanValue() != charging) {
batteryRuntimeEstimator.reset();
}
lastBatteryCharging = charging;
long currentMicroAmps = BatteryRuntimeEstimator.toMicroamps(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
long chargeCounter = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
int voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
@@ -606,36 +618,16 @@ public class HudMetrics {
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
}
Double runtimeHours = !charging
? batteryRuntimeEstimator.estimateHours(chargeCounter, Math.abs((double) currentMicroAmps))
: null;
String runtimeText;
if (charging) {
smoothedBatteryRuntimeHours = null;
runtimeText = "LEFT CHG";
} else if (currentMicroAmps <= 0L || chargeCounter <= 0L) {
runtimeText = null;
} else {
double rawHours = (double) chargeCounter / (double) currentMicroAmps;
if (!Double.isFinite(rawHours) || rawHours <= 0.0 || rawHours > MAX_RUNTIME_HOURS) {
runtimeText = null;
} else {
double smoothed = smoothedBatteryRuntimeHours == null ? rawHours
: (smoothedBatteryRuntimeHours * RUNTIME_SMOOTHING_OLD_WEIGHT)
+ (rawHours * RUNTIME_SMOOTHING_NEW_WEIGHT);
smoothedBatteryRuntimeHours = smoothed;
runtimeText = "LEFT " + formatRuntimeHours(smoothed);
}
}
if (st == BatteryManager.BATTERY_STATUS_FULL || (percent != null && percent >= 100)) runtimeText = "Full";
else if (charging) runtimeText = "Charging";
else runtimeText = BatteryRuntimeEstimator.formatDuration(runtimeHours);
return new Battery(watts, charging, percent, tempC, runtimeText);
}
private static String formatRuntimeHours(double hours) {
int totalMinutes = Math.max(1, (int) Math.round(hours * 60.0));
int wholeHours = totalMinutes / 60;
int minutes = totalMinutes % 60;
if (wholeHours > 0 && minutes > 0) return wholeHours + "h " + minutes + "m";
if (wholeHours > 0) return wholeHours + "h";
return minutes + "m";
}
private static float currentRawToAmps(long raw) {
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
long a = Math.abs(raw);
@@ -843,7 +835,7 @@ public class HudMetrics {
Battery android = collectBattery();
MangoReadings.Battery bat = m.battery();
Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(),
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText);
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, bat.getRuntimeText());
long[] net = readNetRateBps();
int[] perCoreClk = getPerCoreClockMhz();
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), fastestCoreMhz(perCoreClk), m.gpuClockMhz(),
@@ -2,13 +2,18 @@ package com.droiddeck.launcher.hud
import android.os.Environment
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.BatteryRuntimeEstimator
import java.io.File
import kotlin.math.abs
import kotlin.math.roundToInt
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
class Battery(val percent: Int?, val watts: Float, val charging: Boolean)
class Battery(val percent: Int?, val watts: Float, val charging: Boolean, val runtimeText: String?)
private val batteryRuntimeEstimator = BatteryRuntimeEstimator()
private var lastBatteryDischarging: Boolean? = null
private val cpuTimes = HashMap<String, LongArray>()
private val cpuPercents = HashMap<String, Int>()
@@ -106,32 +111,113 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }?.take(2)
if (dirs.isNullOrEmpty()) return null
var chargeNow = 0f
var chargeFull = 0f
var watts = 0f
var charging = false
var weightedChargeNow = 0.0
var weightedChargeFull = 0.0
var allHaveWeightedCharge = true
val perBatteryPercents = ArrayList<Int>()
var runtimeChargeUah = 0.0
var runtimeChargeComplete = true
var aggregateCurrentUa = 0.0
var currentComplete = true
var watts = 0.0
var anyDischarging = false
var anyChargingStatus = false
var allFull = true
var suppliedRuntimeSeconds: Long? = null
for (dir in dirs) {
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
if (status == "Charging" || status == "Unknown" || status == "Full") charging = true
val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now")
val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full")
if (now.exists()) {
chargeNow += (readFloat(now) ?: 0f) / 1_000_000f
chargeFull += (readFloat(full) ?: 0f) / 1_000_000f
} else {
chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f
chargeFull = dirs.size.toFloat()
val isDischarging = status == "Discharging" || status == "Not charging"
if (isDischarging) anyDischarging = true
if (status == "Charging" || status == "Unknown") anyChargingStatus = true
if (status != "Full") allFull = false
val chargeNowFile = File(dir, "charge_now")
val chargeFullFile = File(dir, "charge_full")
val energyNowFile = File(dir, "energy_now")
val energyFullFile = File(dir, "energy_full")
val voltageFile = File(dir, "voltage_now")
val chargeNow = if (chargeNowFile.isFile) readFloat(chargeNowFile)?.toDouble() else null
val chargeFull = if (chargeFullFile.isFile) readFloat(chargeFullFile)?.toDouble() else null
val energyNow = if (energyNowFile.isFile) readFloat(energyNowFile)?.toDouble() else null
val energyFull = if (energyFullFile.isFile) readFloat(energyFullFile)?.toDouble() else null
val voltageUv = if (voltageFile.isFile) readFloat(voltageFile)?.toDouble() else null
val nowForPercent: Double? = when {
chargeNow != null && chargeNow >= 0.0 -> chargeNow
energyNow != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)
else -> null
}
if (!charging) {
val power = File(dir, "power_now")
watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f
else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f
val fullForPercent: Double? = when {
chargeFull != null && chargeFull > 0.0 -> chargeFull
energyFull != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyFull, voltageUv)
else -> null
}
if (nowForPercent != null && fullForPercent != null && fullForPercent > 0.0) {
weightedChargeNow += nowForPercent
weightedChargeFull += fullForPercent
perBatteryPercents += (nowForPercent * 100.0 / fullForPercent).roundToInt().coerceIn(0, 100)
} else {
allHaveWeightedCharge = false
readFloat(File(dir, "capacity"))?.roundToInt()?.coerceIn(0, 100)?.let { perBatteryPercents += it }
}
when {
chargeNow != null && chargeNow >= 0.0 -> runtimeChargeUah += chargeNow
energyNow != null && voltageUv != null ->
BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)?.let { runtimeChargeUah += it }
?: run { runtimeChargeComplete = false }
else -> runtimeChargeComplete = false
}
if (dirs.size == 1) {
suppliedRuntimeSeconds = readLong(File(dir, "time_to_empty_avg"))?.takeIf { it > 0L }
?: readLong(File(dir, "time_to_empty_now"))?.takeIf { it > 0L }
?: suppliedRuntimeSeconds
}
val currentFile = File(dir, "current_now")
val powerFile = File(dir, "power_now")
val currentNow = if (currentFile.isFile) readFloat(currentFile)?.toDouble() else null
val currentForEta = when {
currentNow != null -> abs(currentNow)
powerFile.isFile && voltageUv != null -> readFloat(powerFile)?.toDouble()?.let {
BatteryRuntimeEstimator.currentMicroampsFromPower(it, voltageUv)
}
else -> null
}
if (currentForEta == null) currentComplete = false else aggregateCurrentUa += currentForEta
if (isDischarging) {
val power = if (powerFile.isFile) readFloat(powerFile)?.toDouble() else null
if (power != null) watts += abs(power) / 1_000_000.0
else if (currentNow != null && voltageUv != null) watts += abs(currentNow * voltageUv) / 1_000_000_000_000.0
}
}
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
return Battery(percent, if (charging) 0f else watts, charging)
val percent = when {
allHaveWeightedCharge && weightedChargeFull > 0.0 -> (weightedChargeNow * 100.0 / weightedChargeFull).roundToInt().coerceIn(0, 100)
perBatteryPercents.isNotEmpty() -> perBatteryPercents.average().roundToInt().coerceIn(0, 100)
else -> null
}
if (lastBatteryDischarging != null && lastBatteryDischarging != anyDischarging) {
batteryRuntimeEstimator.reset()
}
lastBatteryDischarging = anyDischarging
val estimatedHours = if (anyDischarging && runtimeChargeComplete && currentComplete)
batteryRuntimeEstimator.estimateHours(runtimeChargeUah, aggregateCurrentUa) else null
val runtimeHours = suppliedRuntimeSeconds?.let { it / 3600.0 } ?: estimatedHours
val charging = !anyDischarging && anyChargingStatus
val runtimeText = when {
anyDischarging -> BatteryRuntimeEstimator.formatDuration(runtimeHours)
charging -> "Charging"
allFull -> "Full"
else -> null
}
return Battery(percent, if (anyDischarging) watts.toFloat() else 0f, charging, runtimeText)
}
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
@@ -11,6 +11,8 @@ import kotlin.math.abs
class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val runtimeEstimator = BatteryRuntimeEstimator()
private var lastDischarging: Boolean? = null
override fun start() {
File(dir, "BAT0").deleteRecursively()
@@ -49,11 +51,17 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
val currentAvgUa = toMicroamps(bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE)?.takeIf { it != Long.MIN_VALUE && it != 0L } ?: 0L)
.takeIf { it != 0L } ?: currentNowUa
val discharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING
if (lastDischarging != null && lastDischarging != discharging) runtimeEstimator.reset()
lastDischarging = discharging
val currentForRuntimeUa = currentNowUa.takeIf { it != 0L } ?: currentAvgUa
val chargeFullUah = if (chargeNowUah > 0 && pct > 0) chargeNowUah * 100 / pct else 0L
val energyNowUwh = chargeNowUah * voltageUv / 1_000_000L
val energyFullUwh = chargeFullUah * voltageUv / 1_000_000L
val powerNowUw = abs(currentNowUa) * voltageUv / 1_000_000L
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
val runtimeHours = if (discharging)
runtimeEstimator.estimateHours(chargeNowUah.toDouble(), currentForRuntimeUa.toDouble())
else null
val timeToEmptyS = BatteryRuntimeEstimator.secondsFromHours(runtimeHours)
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
val statusText = when (status) {
@@ -126,9 +134,7 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
companion object {
private const val TAG = "SessionService"
private const val MILLIAMP_CEILING = 10_000L
internal fun toMicroamps(raw: Long): Long = if (abs(raw) < MILLIAMP_CEILING) raw * 1000L else raw
internal fun toMicroamps(raw: Long): Long = BatteryRuntimeEstimator.toMicroamps(raw)
private const val PERIOD_MS = 5_000L
private val VPOWER_FILES = listOf(
"ac_status", "battery_percent", "battery_status",
@@ -0,0 +1,74 @@
package com.droiddeck.launcher.session
import java.util.ArrayDeque
import kotlin.math.abs
import kotlin.math.roundToLong
class BatteryRuntimeEstimator {
private val currentSamples = ArrayDeque<Double>()
@Synchronized
fun reset() {
currentSamples.clear()
}
@Synchronized
fun estimateHours(chargeNowUah: Double, currentSampleUa: Double): Double? {
if (currentSampleUa.isFinite() && currentSampleUa != 0.0) {
currentSamples.addLast(abs(currentSampleUa))
while (currentSamples.size > MAX_SAMPLES) currentSamples.removeFirst()
}
if (!chargeNowUah.isFinite() || chargeNowUah <= 0.0 || currentSamples.isEmpty()) return null
var sum = 0.0
for (sample in currentSamples) sum += sample
val averageCurrentUa = sum / currentSamples.size
if (!averageCurrentUa.isFinite() || averageCurrentUa <= 0.0) return null
val hours = chargeNowUah / averageCurrentUa
return hours.takeIf { it.isFinite() && it > 0.0 }
}
companion object {
private const val MAX_SAMPLES = 25
private const val MILLIAMP_CEILING = 10_000L
@JvmStatic
fun toMicroamps(raw: Long): Long {
if (raw == Long.MIN_VALUE) return 0L
return if (abs(raw) < MILLIAMP_CEILING) raw * 1_000L else raw
}
@JvmStatic
fun chargeMicroampHoursFromEnergy(energyUwh: Double, voltageUv: Double): Double? {
if (!energyUwh.isFinite() || energyUwh <= 0.0 || !voltageUv.isFinite() || voltageUv <= 0.0) return null
return (energyUwh * 1_000_000.0 / voltageUv).takeIf { it.isFinite() && it > 0.0 }
}
@JvmStatic
fun currentMicroampsFromPower(powerUw: Double, voltageUv: Double): Double? {
if (!powerUw.isFinite() || voltageUv <= 0.0 || !voltageUv.isFinite()) return null
return (abs(powerUw) * 1_000_000.0 / voltageUv).takeIf { it.isFinite() && it > 0.0 }
}
@JvmStatic
fun secondsFromHours(hours: Double?): Long {
if (hours == null || !hours.isFinite() || hours <= 0.0) return 0L
val seconds = hours * 3_600.0
return if (seconds.isFinite() && seconds < Long.MAX_VALUE.toDouble()) seconds.toLong() else 0L
}
@JvmStatic
fun formatDuration(hours: Double?): String? {
if (hours == null || !hours.isFinite() || hours <= 0.0) return null
val totalMinutes = (hours * 60.0).roundToLong().coerceAtLeast(1L)
val wholeHours = totalMinutes / 60L
val minutes = totalMinutes % 60L
val hourUnit = if (wholeHours == 1L) "hr" else "hrs"
val minuteUnit = if (minutes == 1L) "min" else "mins"
return when {
wholeHours > 0L && minutes > 0L -> "$wholeHours $hourUnit $minutes $minuteUnit"
wholeHours > 0L -> "$wholeHours $hourUnit"
else -> "$minutes $minuteUnit"
}
}
}
}
@@ -64,6 +64,16 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
if (metric.chip !in chips || metric.chip in HIDDEN[size].orEmpty()) continue
ToggleRow(host, "hud-${metric.key}", stringResource(metric.label), null, on(metric.key),
chipModifier = track("hud-${metric.key}")) { a.onHudSetting(metric.key, flag(it)) }
if (metric.key == "showBattery" && size != DroidDeckHudSize.MINIMAL) {
ToggleRow(host, "hud-showBatteryTime", stringResource(R.string.hud_metric_battery_time), null, on("showBatteryTime"),
chipModifier = track("hud-showBatteryTime")) { a.onHudSetting("showBatteryTime", flag(it)) }
}
}
if (size == DroidDeckHudSize.MINIMAL && "Battery time" in chips &&
"Battery time" !in HIDDEN[size].orEmpty()) {
ToggleRow(host, "hud-showBatteryTime", stringResource(R.string.hud_metric_battery_time), null, on("showBatteryTime"),
chipModifier = track("hud-showBatteryTime")) { a.onHudSetting("showBatteryTime", flag(it)) }
}
}
@@ -176,8 +186,6 @@ private val METRICS = listOf(
)
private val HIDDEN = mapOf(
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
DroidDeckHudSize.MINIMAL to setOf("FPS"),
DroidDeckHudSize.PILL to setOf("FPS graph"),
DroidDeckHudSize.TILES to setOf("FPS graph", "0.1% low", "0.01% low"),
DroidDeckHudSize.STRIP to setOf("FPS"),
)