Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ else `device.*`.
| battery | `hw.battery.charge` | `1` | | Battery level, 0 to 1 (0.87 = 87 %) |
| battery | `device.battery.voltage` | `V` | | Battery voltage |
| battery | `device.battery.temperature` | `Cel` | | Battery temperature, °C |
| battery | `device.battery.current` | `A` | | Battery current. Positive is into the battery on most phones; some phones use the other sign |
| battery | `device.battery.current` | `A` | | Battery current. The sign is kept as the phone gives it: positive is into the battery on most phones, but some phones (for example OnePlus) use the other sign. The unit of the raw value is chosen by `collectors.battery.current_unit`: see [Battery current unit](#battery-current-unit) |
| battery | `device.battery.charge_counter` | `A.h` | | Remaining charge |
| battery | `device.battery.cycle_count` | `{cycle}` | | Charge cycles (Android 14+, when the phone reports it) |
| battery | `device.battery.status` | `1` | `battery.status`: `charging`, `discharging`, `not_charging`, `full`, `unknown` | 1 for the current status, 0 for the others |
Expand Down Expand Up @@ -112,7 +112,7 @@ default. Example (all keys):
"attributes": { "location": "lobby" }
},
"collectors": {
"battery": { "enabled": true, "interval": 60 },
"battery": { "enabled": true, "interval": 60, "current_unit": "auto" },
"power": { "enabled": true, "interval": 60 },
"boot": { "enabled": true, "interval": 300 },
"network": { "enabled": true, "interval": 60 },
Expand All @@ -138,17 +138,41 @@ default. Example (all keys):
| `resource.attributes` | none | More resource attributes (text values) |
| `collectors.NAME.enabled` | `true` | NAME is `battery`, `power`, `boot`, `network`, `device` or `thermal` |
| `collectors.NAME.interval` | `60` | Seconds, 10–86400 |
| `collectors.battery.current_unit` | `auto` | Unit of the raw battery current: `auto`, `uA` or `mA`; see [Battery current unit](#battery-current-unit) |
| `buffer.max_bytes` | `20971520` (20 MiB) | Disk queue size cap. When it is full, the oldest file is dropped first |
| `buffer.max_age` | `604800` (7 days) | Seconds. Older queue files are dropped |
| `wake_policy` | `when_charging` | `never`, `when_charging` or `always`; see below |

A wrong value (a bad type, a number out of range, an unknown `wake_policy`)
A wrong value (a bad type, a number out of range, an unknown `wake_policy`
or `current_unit`)
rejects the whole import, and the config in use stays as it was. An unknown
key is ignored with a warning.

The app screen shows the config in use, each value with where it came from
(`default` or `local file`).

### Battery current unit

Android says the raw battery current (`BATTERY_PROPERTY_CURRENT_NOW`) is in
microamperes (µA). Some phones give milliamperes (mA) instead, for example a
OnePlus Nord CE 2 Lite. Read as µA, that value is 1000 times too small.

`collectors.battery.current_unit` sets the unit:

- `uA` or `mA`: the raw value is always read in this unit.
- `auto` (default), in this order:
1. A raw value of 50000 or more (in size) is µA, because 50000 mA (50 A)
is not a real phone current, even with 240 W fast charging. After one such value, the app reads µA
until it restarts.
2. On phones made by OnePlus, OPPO or realme (`Build.MANUFACTURER`), mA.
These makers share one battery service that gives mA. If such a phone
gives µA, a current below 50 mA reads 1000 times too large until the
first value of 50000 or more; set `uA` then.
3. On all other phones, µA, as Android says.

If the value is wrong on your phone (about 1000 times too small or too
large), set `uA` or `mA`. The sign is never changed.

### Import the config

**By file.** In the app: **Import config file**, then pick the JSON file. Or
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/dev/code6x/otelagent/AgentService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class AgentService : Service() {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
store = ConfigStore(this)
collectors = Collectors.create(this)
collectors = Collectors.create(this) { loaded.config.batteryCurrentUnit }
val queueRoot = File(filesDir, "queue")
metricQueue = FileQueue(File(queueRoot, "metrics"), 0, 0)
logQueue = FileQueue(File(queueRoot, "logs"), 0, 0)
Expand Down
39 changes: 33 additions & 6 deletions app/src/main/java/dev/code6x/otelagent/collect/BatteryCollector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import dev.code6x.otelagent.config.CurrentUnit

/** Raw values as Android gives them; null when the phone does not report one. */
data class BatterySnapshot(
Expand All @@ -15,15 +16,23 @@ data class BatterySnapshot(
val status: Int,
val plugged: Int,
val health: Int,
val currentMicroA: Long?,
/** BATTERY_PROPERTY_CURRENT_NOW as the phone gives it: µA on most phones, mA on some. */
val currentRaw: Long?,
val chargeCounterMicroAh: Long?,
val cycleCount: Int?,
)

class BatteryCollector(private val context: Context) : Collector {
class BatteryCollector(private val context: Context, private val currentUnit: () -> CurrentUnit) : Collector {
override val name = "battery"

override fun collect(): List<Reading> = map(read(context) ?: return emptyList())
/** True after a raw current too large to be mA: then this phone gives µA (see [unit]). */
private var seenMicroA = false

override fun collect(): List<Reading> {
val s = read(context) ?: return emptyList()
if (s.currentRaw != null && Math.abs(s.currentRaw) >= MICRO_A_MIN) seenMicroA = true
return map(s, unit(currentUnit(), s.currentRaw, Build.MANUFACTURER, seenMicroA))
}

companion object {
val STATUSES = listOf("charging", "discharging", "not_charging", "full", "unknown")
Expand Down Expand Up @@ -60,12 +69,30 @@ class BatteryCollector(private val context: Context) : Collector {
else -> "unknown"
}

fun map(s: BatterySnapshot): List<Reading> {
/** A raw value this large (50 A if it were mA, more than even 240 W fast charging) can only be µA. */
const val MICRO_A_MIN = 50_000L

/** Makers whose phones are known to give mA (OnePlus, OPPO and realme share one battery service). */
val MILLI_A_MAKERS = setOf("oneplus", "oppo", "realme")

/**
* The unit of the raw current. A set unit wins. `auto`: µA when the value is too large
* to be mA (now or earlier in this process, [seenMicroA]); else mA for the makers in
* [MILLI_A_MAKERS]; else µA, as Android says.
*/
fun unit(set: CurrentUnit, raw: Long?, manufacturer: String, seenMicroA: Boolean): CurrentUnit {
if (set != CurrentUnit.AUTO) return set
if (seenMicroA || (raw != null && Math.abs(raw) >= MICRO_A_MIN)) return CurrentUnit.MICRO_A
return if (manufacturer.trim().lowercase() in MILLI_A_MAKERS) CurrentUnit.MILLI_A else CurrentUnit.MICRO_A
}

/** [unit] is the unit of the raw current (not AUTO; AUTO is read as µA). */
fun map(s: BatterySnapshot, unit: CurrentUnit = CurrentUnit.MICRO_A): List<Reading> {
val out = mutableListOf<Reading>()
if (s.level >= 0 && s.scale > 0) out += Reading(Metrics.BATTERY_CHARGE, s.level.toDouble() / s.scale)
s.voltageMv?.takeIf { it > 0 }?.let { out += Reading(Metrics.BATTERY_VOLTAGE, it / 1000.0) }
s.temperatureTenthsC?.let { out += Reading(Metrics.BATTERY_TEMPERATURE, it / 10.0) }
s.currentMicroA?.let { out += Reading(Metrics.BATTERY_CURRENT, it / 1_000_000.0) }
s.currentRaw?.let { out += Reading(Metrics.BATTERY_CURRENT, it / if (unit == CurrentUnit.MILLI_A) 1_000.0 else 1_000_000.0) }
s.chargeCounterMicroAh?.takeIf { it > 0 }?.let { out += Reading(Metrics.BATTERY_CHARGE_COUNTER, it / 1_000_000.0) }
s.cycleCount?.takeIf { it >= 0 }?.let { out += Reading(Metrics.BATTERY_CYCLES, it.toDouble()) }
out += states(Metrics.BATTERY_STATUS, "battery.status", STATUSES, setOf(status(s.status)))
Expand Down Expand Up @@ -98,7 +125,7 @@ class BatteryCollector(private val context: Context) : Collector {
status = i.getIntExtra(BatteryManager.EXTRA_STATUS, 1),
plugged = i.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0),
health = i.getIntExtra(BatteryManager.EXTRA_HEALTH, 1),
currentMicroA = current,
currentRaw = current,
chargeCounterMicroAh = counter,
cycleCount = cycles,
)
Expand Down
6 changes: 4 additions & 2 deletions app/src/main/java/dev/code6x/otelagent/collect/Collector.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dev.code6x.otelagent.collect

import android.content.Context
import dev.code6x.otelagent.config.CurrentUnit

/** A group of readings that can be turned on or off, with its own interval. */
interface Collector {
Expand All @@ -9,10 +10,11 @@ interface Collector {
}

object Collectors {
fun create(context: Context): List<Collector> {
/** [currentUnit] gives the `collectors > battery > current_unit` value in use at each reading. */
fun create(context: Context, currentUnit: () -> CurrentUnit): List<Collector> {
val c = context.applicationContext
return listOf(
BatteryCollector(c),
BatteryCollector(c, currentUnit),
PowerCollector(c),
BootCollector(c),
NetworkCollector(c),
Expand Down
13 changes: 13 additions & 0 deletions app/src/main/java/dev/code6x/otelagent/config/AgentConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ enum class WakePolicy(val key: String) {
}
}

/** Unit of the raw BATTERY_PROPERTY_CURRENT_NOW value. Android says µA; some phones give mA. */
enum class CurrentUnit(val key: String) {
AUTO("auto"),
MICRO_A("uA"),
MILLI_A("mA"),
;

companion object {
fun parse(key: String): CurrentUnit? = entries.firstOrNull { it.key == key }
}
}

data class ExporterConfig(
/** Full URL of the OTLP/HTTP metrics endpoint. Empty: data stays in the queue. */
val endpoint: String,
Expand All @@ -40,6 +52,7 @@ data class AgentConfig(
val collectors: Map<String, CollectorConfig>,
val buffer: BufferConfig,
val wakePolicy: WakePolicy,
val batteryCurrentUnit: CurrentUnit = CurrentUnit.AUTO,
) {
fun collector(name: String): CollectorConfig =
collectors[name] ?: CollectorConfig(enabled = false, intervalSeconds = DEFAULT_INTERVAL)
Expand Down
9 changes: 7 additions & 2 deletions app/src/main/java/dev/code6x/otelagent/config/ConfigLoader.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ object ConfigLoader {
"attributes": {}
},
"collectors": {
"battery": {"enabled": true, "interval": 60},
"battery": {"enabled": true, "interval": 60, "current_unit": "auto"},
"power": {"enabled": true, "interval": 60},
"boot": {"enabled": true, "interval": 60},
"network": {"enabled": true, "interval": 60},
Expand Down Expand Up @@ -109,7 +109,9 @@ object ConfigLoader {

private fun known(p: List<String>): Boolean {
if (FREE_MAPS.any { p.size == it.size + 1 && p.subList(0, it.size) == it }) return true
if (p.size == 3 && p[0] == "collectors") return p[1] in AgentConfig.COLLECTORS && p[2] in setOf("enabled", "interval")
if (p.size == 3 && p[0] == "collectors") {
return (p[1] in AgentConfig.COLLECTORS && p[2] in setOf("enabled", "interval")) || p in defaultsLayer.keys
}
return p in defaultsLayer.keys
}

Expand Down Expand Up @@ -152,6 +154,8 @@ object ConfigLoader {
val wakeKey = str("wake_policy")
val wake = WakePolicy.parse(wakeKey)
?: throw ConfigException("wake_policy: must be one of ${WakePolicy.entries.joinToString { it.key }}")
val unit = CurrentUnit.parse(str("collectors", "battery", "current_unit"))
?: throw ConfigException("collectors > battery > current_unit: must be one of ${CurrentUnit.entries.joinToString { it.key }}")
val collectors = AgentConfig.COLLECTORS.associateWith { c ->
CollectorConfig(
enabled = bool("collectors", c, "enabled"),
Expand All @@ -174,6 +178,7 @@ object ConfigLoader {
maxAgeSeconds = long("buffer", "max_age", min = 60, max = 90L * 86400),
),
wakePolicy = wake,
batteryCurrentUnit = unit,
)
}

Expand Down
30 changes: 29 additions & 1 deletion app/src/test/java/dev/code6x/otelagent/CollectorMappingTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import dev.code6x.otelagent.collect.PowerSnapshot
import dev.code6x.otelagent.collect.Reading
import dev.code6x.otelagent.collect.ThermalCollector
import dev.code6x.otelagent.collect.ThermalSnapshot
import dev.code6x.otelagent.config.CurrentUnit
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
Expand All @@ -31,7 +32,7 @@ class CollectorMappingTest {
val r = BatteryCollector.map(
BatterySnapshot(
level = 87, scale = 100, voltageMv = 4123, temperatureTenthsC = 312, status = 2, plugged = 1,
health = 2, currentMicroA = -250_000, chargeCounterMicroAh = 3_100_000, cycleCount = 42,
health = 2, currentRaw = -250_000, chargeCounterMicroAh = 3_100_000, cycleCount = 42,
),
)
assertEquals(0.87, r.value("hw.battery.charge")!!, 1e-9)
Expand All @@ -48,6 +49,33 @@ class CollectorMappingTest {
assertEquals(5, r.count { it.def.name == "device.battery.plug" })
}

private fun snap(raw: Long) = BatterySnapshot(50, 100, null, null, 2, 1, 2, raw, null, null)

@Test fun batteryCurrentInMilliAmps() {
// A phone that gives mA, charging at 1.5 A with a negative sign: the sign is kept.
assertEquals(-1.508, BatteryCollector.map(snap(-1508), CurrentUnit.MILLI_A).value("device.battery.current")!!, 1e-9)
assertEquals(-0.001508, BatteryCollector.map(snap(-1508), CurrentUnit.MICRO_A).value("device.battery.current")!!, 1e-12)
}

@Test fun batteryCurrentUnitChoice() {
fun unit(set: CurrentUnit, raw: Long?, maker: String, seen: Boolean = false) =
BatteryCollector.unit(set, raw, maker, seen)
// A set unit always wins.
assertEquals(CurrentUnit.MICRO_A, unit(CurrentUnit.MICRO_A, -1508, "OnePlus"))
assertEquals(CurrentUnit.MILLI_A, unit(CurrentUnit.MILLI_A, -250_000, "Google"))
// auto: known mA makers, any case.
assertEquals(CurrentUnit.MILLI_A, unit(CurrentUnit.AUTO, -1508, "OnePlus"))
assertEquals(CurrentUnit.MILLI_A, unit(CurrentUnit.AUTO, 300, "OPPO"))
assertEquals(CurrentUnit.MILLI_A, unit(CurrentUnit.AUTO, null, "realme"))
// auto: other makers (the emulator says "unknown") stay µA, as Android says.
assertEquals(CurrentUnit.MICRO_A, unit(CurrentUnit.AUTO, 900_000, "Google"))
assertEquals(CurrentUnit.MICRO_A, unit(CurrentUnit.AUTO, 1500, "unknown"))
// auto: a value too large to be mA is µA, also on a known maker, now and later.
assertEquals(CurrentUnit.MICRO_A, unit(CurrentUnit.AUTO, -50_000, "OnePlus"))
assertEquals(CurrentUnit.MILLI_A, unit(CurrentUnit.AUTO, -15_000, "OnePlus"))
assertEquals(CurrentUnit.MICRO_A, unit(CurrentUnit.AUTO, 500, "OnePlus", seen = true))
}

@Test fun batteryWithoutOptionalValues() {
val r = BatteryCollector.map(
BatterySnapshot(50, 100, null, null, 3, 0, 1, null, null, null),
Expand Down
14 changes: 14 additions & 0 deletions app/src/test/java/dev/code6x/otelagent/ConfigLoaderTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dev.code6x.otelagent

import dev.code6x.otelagent.config.ConfigException
import dev.code6x.otelagent.config.ConfigLoader
import dev.code6x.otelagent.config.CurrentUnit
import dev.code6x.otelagent.config.Source
import dev.code6x.otelagent.config.WakePolicy
import org.junit.Assert.assertEquals
Expand Down Expand Up @@ -36,6 +37,19 @@ class ConfigLoaderTest {
assertEquals(20L * 1024 * 1024, c.buffer.maxBytes)
assertEquals(7L * 86400, c.buffer.maxAgeSeconds)
assertTrue(c.attributes.isEmpty())
assertEquals(CurrentUnit.AUTO, c.batteryCurrentUnit)
}

@Test fun batteryCurrentUnitValues() {
fun unit(v: String) = local("""{"collectors": {"battery": {"current_unit": "$v"}}}""").config.batteryCurrentUnit
assertEquals(CurrentUnit.AUTO, unit("auto"))
assertEquals(CurrentUnit.MICRO_A, unit("uA"))
assertEquals(CurrentUnit.MILLI_A, unit("mA"))
assertTrue(local("""{"collectors": {"battery": {"current_unit": "mA"}}}""").warnings.isEmpty())
assertRejected("""{"collectors": {"battery": {"current_unit": "MA"}}}""", "current_unit")
assertRejected("""{"collectors": {"battery": {"current_unit": 1000}}}""", "current_unit")
// Only the battery collector has this key.
assertEquals(1, local("""{"collectors": {"power": {"current_unit": "mA"}}}""").warnings.size)
}

@Test fun localFileOverridesDefaultsAndKeepsSources() {
Expand Down
Loading