commit
Device Reporter app
diff --git a/api-helper/.github/workflows/build.yml b/api-helper/.github/workflows/build.yml
new file mode 100644
index 0000000..01c104b
--- /dev/null
+++ b/api-helper/.github/workflows/build.yml
@@ -0,0 +1,36 @@
+name: Build APK
+
+on:
+ push:
+ branches: [ "**" ]
+ pull_request:
+ workflow_dispatch:
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Set up JDK 17
+ uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: "17"
+
+ - name: Set up Android SDK
+ uses: android-actions/setup-android@v3
+
+ - name: Make gradlew executable
+ run: chmod +x ./gradlew
+
+ - name: Build debug APK
+ run: ./gradlew assembleDebug --stacktrace
+
+ - name: Upload APK artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: device-reporter-debug-apk
+ path: app/build/outputs/apk/debug/app-debug.apk
+ if-no-files-found: error
diff --git a/api-helper/.gitignore b/api-helper/.gitignore
new file mode 100644
index 0000000..91df74f
--- /dev/null
+++ b/api-helper/.gitignore
@@ -0,0 +1,10 @@
+*.iml
+.gradle/
+/local.properties
+.idea/
+.DS_Store
+/build
+/app/build
+/captures
+.externalNativeBuild
+.cxx
diff --git a/api-helper/README.md b/api-helper/README.md
new file mode 100644
index 0000000..09ad61b
--- /dev/null
+++ b/api-helper/README.md
@@ -0,0 +1,110 @@
+# Device Reporter
+
+A tiny always-on Android app that reports your Pixel's state to your own API.
+It replaces the paid "battery worker" apps — self-hosted, one device, no cost.
+
+It calls your endpoint as an HTTP GET:
+
+```
+GET https://doughmination.uk/v2/devices?device=pixel&level=25&charging=1&lpm=0&wifi=Home
+Header: X-Battery-Key: <your key>
+```
+
+The API updates only the fields it receives and leaves the rest untouched, so the
+app sends a full snapshot on every event.
+
+## What it reports and when
+
+| Trigger | Fields sent |
+|---|---|
+| Wi-Fi connect / disconnect | full snapshot (`wifi` = SSID, or `0` when disconnected) |
+| Charger connect / disconnect | full snapshot (`charging`) |
+| Power-save (low power mode) toggle | full snapshot (`lpm`) |
+| Chosen Bluetooth device connect / disconnect | full snapshot (`airpods`) |
+| Every 5 minutes | full snapshot + `location` (battery `level`, etc.) |
+
+A full snapshot is: `device`, `level`, `charging`, `lpm`, `wifi`, `watch`, `airpods`.
+The 5-minute timer (and the in-app **test report**) additionally send `location`.
+
+Every parameter value is URL-encoded before being placed in the query string.
+
+### Field mapping
+
+- **device** — the device name you set in the app.
+- **level** — battery percentage `0–100`.
+- **charging** — `1` plugged in, `0` on battery.
+- **lpm** — `1`/`0` from Android's Battery Saver.
+- **wifi** — SSID when connected; `0` when disconnected. (Withheld by the OS? the app
+ omits `wifi` rather than sending a wrong value — see permissions below.)
+- **watch** — manual toggle in settings. An Apple Watch cannot pair to a Pixel, so
+ there is nothing to auto-detect; flip it yourself if you want `watch=1`.
+- **airpods** — `1`/`0` based on the Bluetooth device you pick in settings. Open
+ **Select AirPods device**, choose your AirPods (or any earbuds) from the paired list,
+ and the app remembers it and reports `airpods=1` when it connects, `0` when it drops.
+- **location** — sent only on the 5-minute timer. The app takes the last-known GPS fix and
+ reverse-geocodes it to human-readable text `City, Region, Country` (not coordinates), e.g.
+ `location=London, England, United Kingdom`. Built from Android's `Geocoder` fields
+ `locality, adminArea, countryName`; any missing part is skipped. Omitted entirely if
+ location permission is off, location services are off, or geocoding returns nothing.
+
+## Settings screen
+
+- **Base URL** — defaults to `https://doughmination.uk/v2`.
+- **X-Battery-Key** — your secret; stored only on the device, never baked into the APK.
+- **Device name** — e.g. `pixel`.
+- **Watch connected** — manual switch.
+- **Enable AirPods (Bluetooth) reporting** + **Select AirPods device**.
+- **Save**, **Start / Stop service**, **Send test report now** (shows the exact request URL and result).
+
+## Permissions
+
+- **Location (fine)** — Android requires it to read the Wi-Fi SSID and the device location.
+ Location services must be **on**, otherwise Android hides the SSID and no `location` is sent.
+- **Background location ("Allow all the time")** — needed so the 5-minute timer can read
+ location while the app is in the background. When you tap **Start**, Android opens the
+ all-the-time location screen; choose it, or the `location` field only fills while the app is open.
+- **Notifications** — the foreground service shows a quiet ongoing notification (Android needs this).
+- **Bluetooth (connect)** — to list paired devices and detect the AirPods connection.
+- **Battery optimization** — for the 5-minute timer to stay reliable, exempt the app:
+ Settings → Apps → Device Reporter → Battery → **Unrestricted**.
+
+## Build the APK (GitHub Actions)
+
+This repo builds the installable APK for you in CI — no Android Studio needed.
+
+1. Push this project to a GitHub repo.
+2. The **Build APK** workflow runs automatically on every push (or run it manually from
+ the **Actions** tab → *Build APK* → *Run workflow*).
+3. Open the finished run and download the **device-reporter-debug-apk** artifact.
+4. Unzip it to get `app-debug.apk`.
+
+### Build locally instead (optional)
+
+```bash
+./gradlew assembleDebug
+# output: app/build/outputs/apk/debug/app-debug.apk
+```
+
+## Install on the Pixel
+
+1. Copy `app-debug.apk` to the phone (or download the artifact directly on it).
+2. Open it; allow **install from unknown sources** if prompted.
+3. Launch **Device Reporter**, fill in the key, tap **Save**, then **Start reporting service**.
+4. Grant the location, notification, and Bluetooth prompts.
+5. Tap **Send test report now** to confirm the server receives it.
+
+The debug APK is signed with Android's standard debug key — fine for a personal device.
+For a "proper" signed release build, add a keystore and an `assembleRelease` signing config.
+
+## Project layout
+
+```
+app/src/main/java/uk/doughmination/devicereporter/
+ MainActivity.kt settings UI + Bluetooth picker + permissions
+ Prefs.kt SharedPreferences config
+ DeviceState.kt battery / charging / lpm / wifi readers
+ Reporter.kt builds the URL and does the GET (X-Battery-Key header)
+ ReporterService.kt foreground service: receivers + 5-min timer
+ BootReceiver.kt restarts the service after reboot
+.github/workflows/build.yml CI that builds and uploads the APK
+```
diff --git a/api-helper/app/build.gradle.kts b/api-helper/app/build.gradle.kts
new file mode 100644
index 0000000..ceab932
--- /dev/null
+++ b/api-helper/app/build.gradle.kts
@@ -0,0 +1,43 @@
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "uk.doughmination.devicereporter"
+ compileSdk = 34
+
+ defaultConfig {
+ applicationId = "uk.doughmination.devicereporter"
+ minSdk = 26
+ targetSdk = 34
+ versionCode = 1
+ versionName = "1.0"
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = false
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro"
+ )
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+}
+
+dependencies {
+ implementation("androidx.core:core-ktx:1.13.1")
+ implementation("androidx.appcompat:appcompat:1.7.0")
+ implementation("com.google.android.material:material:1.12.0")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
+}
diff --git a/api-helper/app/proguard-rules.pro b/api-helper/app/proguard-rules.pro
new file mode 100644
index 0000000..a6154d4
--- /dev/null
+++ b/api-helper/app/proguard-rules.pro
@@ -0,0 +1 @@
+# Keep default; app has no reflection-sensitive code.
diff --git a/api-helper/app/src/main/AndroidManifest.xml b/api-helper/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..96187d3
--- /dev/null
+++ b/api-helper/app/src/main/AndroidManifest.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
+ <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:roundIcon="@mipmap/ic_launcher"
+ android:supportsRtl="true"
+ android:theme="@style/Theme.DeviceReporter">
+
+ <activity
+ android:name=".MainActivity"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+
+ <service
+ android:name=".ReporterService"
+ android:exported="false"
+ android:foregroundServiceType="dataSync" />
+
+ <receiver
+ android:name=".BootReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ </intent-filter>
+ </receiver>
+
+ </application>
+
+</manifest>
diff --git a/api-helper/app/src/main/java/uk/doughmination/devicereporter/BootReceiver.kt b/api-helper/app/src/main/java/uk/doughmination/devicereporter/BootReceiver.kt
new file mode 100644
index 0000000..ed364a0
--- /dev/null
+++ b/api-helper/app/src/main/java/uk/doughmination/devicereporter/BootReceiver.kt
@@ -0,0 +1,16 @@
+package uk.doughmination.devicereporter
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+
+/** Restarts the reporting service after a reboot, if the user had configured it. */
+class BootReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
+ if (Prefs(context).isConfigured()) {
+ ReporterService.start(context)
+ }
+ }
+ }
+}
diff --git a/api-helper/app/src/main/java/uk/doughmination/devicereporter/DeviceState.kt b/api-helper/app/src/main/java/uk/doughmination/devicereporter/DeviceState.kt
new file mode 100644
index 0000000..b5bfb34
--- /dev/null
+++ b/api-helper/app/src/main/java/uk/doughmination/devicereporter/DeviceState.kt
@@ -0,0 +1,155 @@
+package uk.doughmination.devicereporter
+
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.pm.PackageManager
+import android.location.Geocoder
+import android.location.Location
+import android.location.LocationManager
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import android.net.wifi.WifiManager
+import android.os.BatteryManager
+import android.os.Build
+import android.os.PowerManager
+import androidx.core.content.ContextCompat
+import android.Manifest
+import java.util.Locale
+
+/**
+ * Immutable snapshot of the fields the API accepts.
+ * Only [device] is required by the API; the rest are optional.
+ */
+data class Snapshot(
+ val device: String,
+ val level: Int?,
+ val charging: Boolean?,
+ val lpm: Boolean?,
+ val wifi: String?, // null => omit; "" or a disconnected read => reported as "0"
+ val wifiConnected: Boolean,
+ val watch: Boolean?,
+ val airpods: Boolean?,
+ val location: String? // reverse-geocoded "City, Region, Country"; null => omit
+)
+
+object DeviceState {
+
+ fun batteryLevel(ctx: Context): Int {
+ val bm = ctx.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
+ return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
+ }
+
+ fun isCharging(ctx: Context): Boolean {
+ val bm = ctx.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ return bm.isCharging
+ }
+ val intent: Intent? = ctx.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
+ val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
+ return status == BatteryManager.BATTERY_STATUS_CHARGING ||
+ status == BatteryManager.BATTERY_STATUS_FULL
+ }
+
+ fun isPowerSave(ctx: Context): Boolean {
+ val pm = ctx.getSystemService(Context.POWER_SERVICE) as PowerManager
+ return pm.isPowerSaveMode
+ }
+
+ /** True if wifi is the active, validated network. */
+ fun isWifiConnected(ctx: Context): Boolean {
+ val cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
+ val net = cm.activeNetwork ?: return false
+ val caps = cm.getNetworkCapabilities(net) ?: return false
+ return caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
+ }
+
+ /**
+ * Current wifi SSID, or null if unavailable/disconnected.
+ * On Android 10+ this requires ACCESS_FINE_LOCATION and location services on;
+ * the OS returns "<unknown ssid>" when it will not disclose the name.
+ */
+ @Suppress("DEPRECATION")
+ fun wifiSsid(ctx: Context): String? {
+ if (!isWifiConnected(ctx)) return null
+ return try {
+ val wm = ctx.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
+ val raw = wm.connectionInfo?.ssid ?: return null
+ val ssid = raw.trim('"')
+ if (ssid.isBlank() || ssid == "<unknown ssid>" || ssid == "0x") null else ssid
+ } catch (e: Exception) {
+ null
+ }
+ }
+
+ private fun hasLocationPermission(ctx: Context): Boolean {
+ return ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) ==
+ PackageManager.PERMISSION_GRANTED ||
+ ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) ==
+ PackageManager.PERMISSION_GRANTED
+ }
+
+ /** Freshest last-known fix across the available providers, or null. */
+ private fun lastKnownLocation(ctx: Context): Location? {
+ if (!hasLocationPermission(ctx)) return null
+ val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null
+ val providers = listOf(
+ LocationManager.GPS_PROVIDER,
+ LocationManager.NETWORK_PROVIDER,
+ LocationManager.PASSIVE_PROVIDER
+ )
+ var best: Location? = null
+ for (p in providers) {
+ val loc = try {
+ if (lm.isProviderEnabled(p)) lm.getLastKnownLocation(p) else null
+ } catch (e: SecurityException) {
+ null
+ }
+ if (loc != null && (best == null || loc.time > best!!.time)) best = loc
+ }
+ return best
+ }
+
+ /**
+ * Reverse-geocodes the last-known location into "City, Region, Country".
+ * Blocking (Geocoder) — call from a background thread. Returns null if
+ * permission/location/geocoder is unavailable.
+ */
+ fun locationString(ctx: Context): String? {
+ val loc = lastKnownLocation(ctx) ?: return null
+ if (!Geocoder.isPresent()) return null
+ return try {
+ val geocoder = Geocoder(ctx, Locale.getDefault())
+ @Suppress("DEPRECATION")
+ val results = geocoder.getFromLocation(loc.latitude, loc.longitude, 1)
+ val addr = results?.firstOrNull() ?: return null
+ // city = locality (fallback sub-admin), region = admin area, then country.
+ val city = addr.locality ?: addr.subAdminArea
+ val region = addr.adminArea
+ val country = addr.countryName
+ val parts = listOf(city, region, country).filter { !it.isNullOrBlank() }
+ if (parts.isEmpty()) null else parts.joinToString(", ")
+ } catch (e: Exception) {
+ null
+ }
+ }
+
+ /**
+ * Full current state, honouring user prefs for watch/airpods.
+ * [includeLocation] adds the reverse-geocoded location (used on the 5-min timer).
+ */
+ fun snapshot(ctx: Context, prefs: Prefs, includeLocation: Boolean = false): Snapshot {
+ val connected = isWifiConnected(ctx)
+ return Snapshot(
+ device = prefs.deviceName,
+ level = batteryLevel(ctx).takeIf { it in 0..100 },
+ charging = isCharging(ctx),
+ lpm = isPowerSave(ctx),
+ wifi = if (connected) wifiSsid(ctx) else null,
+ wifiConnected = connected,
+ watch = prefs.watchConnected,
+ airpods = if (prefs.airpodsEnabled) prefs.airpodsConnected else null,
+ location = if (includeLocation) locationString(ctx) else null
+ )
+ }
+}
diff --git a/api-helper/app/src/main/java/uk/doughmination/devicereporter/MainActivity.kt b/api-helper/app/src/main/java/uk/doughmination/devicereporter/MainActivity.kt
new file mode 100644
index 0000000..4557d3b
--- /dev/null
+++ b/api-helper/app/src/main/java/uk/doughmination/devicereporter/MainActivity.kt
@@ -0,0 +1,197 @@
+package uk.doughmination.devicereporter
+
+import android.Manifest
+import android.bluetooth.BluetoothManager
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.Bundle
+import android.widget.Button
+import android.widget.EditText
+import android.widget.TextView
+import android.widget.Toast
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import com.google.android.material.switchmaterial.SwitchMaterial
+
+class MainActivity : AppCompatActivity() {
+
+ private lateinit var prefs: Prefs
+
+ private lateinit var inputBaseUrl: EditText
+ private lateinit var inputApiKey: EditText
+ private lateinit var inputDevice: EditText
+ private lateinit var switchWatch: SwitchMaterial
+ private lateinit var switchAirpods: SwitchMaterial
+ private lateinit var textAirpodsDevice: TextView
+ private lateinit var textStatus: TextView
+
+ private val permissionLauncher =
+ registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_main)
+ prefs = Prefs(this)
+
+ inputBaseUrl = findViewById(R.id.inputBaseUrl)
+ inputApiKey = findViewById(R.id.inputApiKey)
+ inputDevice = findViewById(R.id.inputDevice)
+ switchWatch = findViewById(R.id.switchWatch)
+ switchAirpods = findViewById(R.id.switchAirpods)
+ textAirpodsDevice = findViewById(R.id.textAirpodsDevice)
+ textStatus = findViewById(R.id.textStatus)
+
+ loadIntoViews()
+
+ findViewById<Button>(R.id.btnSelectAirpods).setOnClickListener { pickAirpodsDevice() }
+ findViewById<Button>(R.id.btnSave).setOnClickListener { saveFromViews(); toast("Saved") }
+ findViewById<Button>(R.id.btnStart).setOnClickListener {
+ saveFromViews()
+ if (!prefs.isConfigured()) {
+ toast("Set a base URL and device name first")
+ } else {
+ requestRuntimePermissions()
+ requestBackgroundLocationIfNeeded()
+ ReporterService.start(this)
+ textStatus.text = "Service started."
+ }
+ }
+ findViewById<Button>(R.id.btnStop).setOnClickListener {
+ ReporterService.stop(this)
+ textStatus.text = "Service stopped."
+ }
+ findViewById<Button>(R.id.btnTest).setOnClickListener { sendTestReport() }
+
+ requestRuntimePermissions()
+ }
+
+ private fun loadIntoViews() {
+ inputBaseUrl.setText(prefs.baseUrl)
+ inputApiKey.setText(prefs.apiKey)
+ inputDevice.setText(prefs.deviceName)
+ switchWatch.isChecked = prefs.watchConnected
+ switchAirpods.isChecked = prefs.airpodsEnabled
+ updateAirpodsLabel()
+ }
+
+ private fun saveFromViews() {
+ prefs.baseUrl = inputBaseUrl.text.toString().trim().ifBlank { Prefs.DEFAULT_BASE_URL }
+ prefs.apiKey = inputApiKey.text.toString().trim()
+ prefs.deviceName = inputDevice.text.toString().trim().ifBlank { "pixel" }
+ prefs.watchConnected = switchWatch.isChecked
+ prefs.airpodsEnabled = switchAirpods.isChecked
+ }
+
+ private fun updateAirpodsLabel() {
+ textAirpodsDevice.text = if (prefs.airpodsAddress.isNotBlank()) {
+ "AirPods device: ${prefs.airpodsLabel} (${prefs.airpodsAddress})"
+ } else {
+ "No AirPods device selected"
+ }
+ }
+
+ private fun pickAirpodsDevice() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
+ ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
+ != PackageManager.PERMISSION_GRANTED
+ ) {
+ permissionLauncher.launch(arrayOf(Manifest.permission.BLUETOOTH_CONNECT))
+ toast("Grant Bluetooth permission, then tap again")
+ return
+ }
+
+ val manager = getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
+ val adapter = manager?.adapter
+ if (adapter == null || !adapter.isEnabled) {
+ toast("Turn Bluetooth on first")
+ return
+ }
+
+ val bonded = try {
+ adapter.bondedDevices?.toList().orEmpty()
+ } catch (e: SecurityException) {
+ toast("Bluetooth permission missing")
+ return
+ }
+ if (bonded.isEmpty()) {
+ toast("No paired Bluetooth devices found")
+ return
+ }
+
+ val names = bonded.map { runCatching { it.name }.getOrNull() ?: it.address }.toTypedArray()
+ AlertDialog.Builder(this)
+ .setTitle("Select AirPods device")
+ .setItems(names) { _, which ->
+ val chosen = bonded[which]
+ prefs.airpodsAddress = chosen.address
+ prefs.airpodsLabel = names[which]
+ prefs.airpodsEnabled = true
+ switchAirpods.isChecked = true
+ updateAirpodsLabel()
+ toast("Saved: ${names[which]}")
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ private fun sendTestReport() {
+ saveFromViews()
+ if (!prefs.isConfigured()) {
+ toast("Set a base URL and device name first")
+ return
+ }
+ textStatus.text = "Sending test report…"
+ Thread {
+ val snap = DeviceState.snapshot(this, prefs, includeLocation = true)
+ val url = Reporter.buildUrl(prefs, snap)
+ val result = Reporter.report(prefs, snap)
+ runOnUiThread {
+ textStatus.text = buildString {
+ append(if (result.ok) "Test OK\n" else "Test FAILED: ${result.message}\n")
+ append("\nRequest:\n$url")
+ }
+ }
+ }.start()
+ }
+
+ private fun requestRuntimePermissions() {
+ val needed = ArrayList<String>()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
+ ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
+ != PackageManager.PERMISSION_GRANTED
+ ) needed.add(Manifest.permission.POST_NOTIFICATIONS)
+
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
+ != PackageManager.PERMISSION_GRANTED
+ ) needed.add(Manifest.permission.ACCESS_FINE_LOCATION)
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
+ ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
+ != PackageManager.PERMISSION_GRANTED
+ ) needed.add(Manifest.permission.BLUETOOTH_CONNECT)
+
+ if (needed.isNotEmpty()) permissionLauncher.launch(needed.toTypedArray())
+ }
+
+ /**
+ * Background location must be requested on its own, and only after foreground
+ * location is already granted (Android opens the "Allow all the time" screen).
+ */
+ private fun requestBackgroundLocationIfNeeded() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
+ val fineGranted = ContextCompat.checkSelfPermission(
+ this, Manifest.permission.ACCESS_FINE_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+ val bgGranted = ContextCompat.checkSelfPermission(
+ this, Manifest.permission.ACCESS_BACKGROUND_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+ if (fineGranted && !bgGranted) {
+ permissionLauncher.launch(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION))
+ }
+ }
+
+ private fun toast(msg: String) = Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
+}
diff --git a/api-helper/app/src/main/java/uk/doughmination/devicereporter/Prefs.kt b/api-helper/app/src/main/java/uk/doughmination/devicereporter/Prefs.kt
new file mode 100644
index 0000000..940ced4
--- /dev/null
+++ b/api-helper/app/src/main/java/uk/doughmination/devicereporter/Prefs.kt
@@ -0,0 +1,61 @@
+package uk.doughmination.devicereporter
+
+import android.content.Context
+
+/**
+ * Thin wrapper around SharedPreferences holding all user configuration.
+ */
+class Prefs(context: Context) {
+
+ private val sp = context.getSharedPreferences("device_reporter", Context.MODE_PRIVATE)
+
+ var baseUrl: String
+ get() = sp.getString(KEY_BASE_URL, DEFAULT_BASE_URL) ?: DEFAULT_BASE_URL
+ set(v) = sp.edit().putString(KEY_BASE_URL, v).apply()
+
+ var apiKey: String
+ get() = sp.getString(KEY_API_KEY, "") ?: ""
+ set(v) = sp.edit().putString(KEY_API_KEY, v).apply()
+
+ var deviceName: String
+ get() = sp.getString(KEY_DEVICE, "pixel") ?: "pixel"
+ set(v) = sp.edit().putString(KEY_DEVICE, v).apply()
+
+ /** Manual toggle: an Apple Watch cannot pair to a Pixel, so the user sets this by hand. */
+ var watchConnected: Boolean
+ get() = sp.getBoolean(KEY_WATCH, false)
+ set(v) = sp.edit().putBoolean(KEY_WATCH, v).apply()
+
+ var airpodsEnabled: Boolean
+ get() = sp.getBoolean(KEY_AIRPODS_ENABLED, false)
+ set(v) = sp.edit().putBoolean(KEY_AIRPODS_ENABLED, v).apply()
+
+ /** Bluetooth MAC address of the device we treat as "airpods". Empty = none chosen. */
+ var airpodsAddress: String
+ get() = sp.getString(KEY_AIRPODS_ADDR, "") ?: ""
+ set(v) = sp.edit().putString(KEY_AIRPODS_ADDR, v).apply()
+
+ var airpodsLabel: String
+ get() = sp.getString(KEY_AIRPODS_LABEL, "") ?: ""
+ set(v) = sp.edit().putString(KEY_AIRPODS_LABEL, v).apply()
+
+ /** Last known connection state of the chosen airpods device, updated by the BT receiver. */
+ var airpodsConnected: Boolean
+ get() = sp.getBoolean(KEY_AIRPODS_CONNECTED, false)
+ set(v) = sp.edit().putBoolean(KEY_AIRPODS_CONNECTED, v).apply()
+
+ fun isConfigured(): Boolean = baseUrl.isNotBlank() && deviceName.isNotBlank()
+
+ companion object {
+ const val DEFAULT_BASE_URL = "https://doughmination.uk/v2"
+
+ private const val KEY_BASE_URL = "base_url"
+ private const val KEY_API_KEY = "api_key"
+ private const val KEY_DEVICE = "device"
+ private const val KEY_WATCH = "watch"
+ private const val KEY_AIRPODS_ENABLED = "airpods_enabled"
+ private const val KEY_AIRPODS_ADDR = "airpods_addr"
+ private const val KEY_AIRPODS_LABEL = "airpods_label"
+ private const val KEY_AIRPODS_CONNECTED = "airpods_connected"
+ }
+}
diff --git a/api-helper/app/src/main/java/uk/doughmination/devicereporter/Reporter.kt b/api-helper/app/src/main/java/uk/doughmination/devicereporter/Reporter.kt
new file mode 100644
index 0000000..0a5117d
--- /dev/null
+++ b/api-helper/app/src/main/java/uk/doughmination/devicereporter/Reporter.kt
@@ -0,0 +1,80 @@
+package uk.doughmination.devicereporter
+
+import android.util.Log
+import java.net.HttpURLConnection
+import java.net.URL
+import java.net.URLEncoder
+
+/**
+ * Sends a device-state snapshot to the API as an HTTP GET:
+ * GET {baseUrl}/devices?device=...&level=... with header X-Battery-Key: {key}
+ *
+ * The API updates only the fields supplied and leaves the rest untouched,
+ * so sending a full snapshot on every event is safe.
+ */
+object Reporter {
+
+ private const val TAG = "Reporter"
+
+ data class Result(val ok: Boolean, val code: Int, val message: String)
+
+ fun buildUrl(prefs: Prefs, snap: Snapshot): String = buildUrl(prefs.baseUrl, snap)
+
+ /** Testable core: builds the request URL from a base URL and a snapshot. */
+ fun buildUrl(baseUrl: String, snap: Snapshot): String {
+ val base = baseUrl.trim().trimEnd('/')
+ val params = ArrayList<String>()
+
+ fun add(key: String, value: String) {
+ params.add("$key=${URLEncoder.encode(value, "UTF-8")}")
+ }
+
+ add("device", snap.device)
+ snap.level?.let { add("level", it.toString()) }
+ snap.charging?.let { add("charging", if (it) "1" else "0") }
+ snap.lpm?.let { add("lpm", if (it) "1" else "0") }
+
+ // wifi: disconnected => "0"; connected with a known name => the name;
+ // connected but name withheld by the OS => omit (don't overwrite with a guess).
+ if (!snap.wifiConnected) {
+ add("wifi", "0")
+ } else if (!snap.wifi.isNullOrBlank()) {
+ add("wifi", snap.wifi)
+ }
+
+ snap.watch?.let { add("watch", if (it) "1" else "0") }
+ snap.airpods?.let { add("airpods", if (it) "1" else "0") }
+ snap.location?.let { if (it.isNotBlank()) add("location", it) }
+
+ return "$base/devices?${params.joinToString("&")}"
+ }
+
+ /** Blocking network call — invoke from a background thread / IO dispatcher. */
+ fun report(prefs: Prefs, snap: Snapshot): Result {
+ val urlStr = buildUrl(prefs, snap)
+ return try {
+ val conn = (URL(urlStr).openConnection() as HttpURLConnection).apply {
+ requestMethod = "GET"
+ connectTimeout = 15_000
+ readTimeout = 15_000
+ setRequestProperty("X-Battery-Key", prefs.apiKey)
+ setRequestProperty("Accept", "application/json")
+ instanceFollowRedirects = true
+ }
+ val code = conn.responseCode
+ val ok = code in 200..299
+ val body = try {
+ (if (ok) conn.inputStream else conn.errorStream)
+ ?.bufferedReader()?.use { it.readText() }?.take(300) ?: ""
+ } catch (e: Exception) {
+ ""
+ }
+ conn.disconnect()
+ Log.i(TAG, "GET $urlStr -> $code")
+ Result(ok, code, if (ok) "OK" else "HTTP $code $body")
+ } catch (e: Exception) {
+ Log.w(TAG, "report failed: ${e.message}")
+ Result(false, -1, e.message ?: "network error")
+ }
+ }
+}
diff --git a/api-helper/app/src/main/java/uk/doughmination/devicereporter/ReporterService.kt b/api-helper/app/src/main/java/uk/doughmination/devicereporter/ReporterService.kt
new file mode 100644
index 0000000..81d873b
--- /dev/null
+++ b/api-helper/app/src/main/java/uk/doughmination/devicereporter/ReporterService.kt
@@ -0,0 +1,240 @@
+package uk.doughmination.devicereporter
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.Service
+import android.bluetooth.BluetoothDevice
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.net.ConnectivityManager
+import android.net.Network
+import android.net.NetworkCapabilities
+import android.net.NetworkRequest
+import android.os.Build
+import android.os.IBinder
+import android.os.PowerManager
+import android.util.Log
+import androidx.core.app.NotificationCompat
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+/**
+ * Always-on foreground service. Reports device state on:
+ * - wifi connect / disconnect (ConnectivityManager callback)
+ * - charger connect / disconnect (ACTION_POWER_CONNECTED/DISCONNECTED)
+ * - power-save (lpm) toggle (ACTION_POWER_SAVE_MODE_CHANGED)
+ * - chosen bluetooth device conn/disc (ACL_CONNECTED/DISCONNECTED -> airpods)
+ * - every 5 minutes (periodic battery check)
+ */
+class ReporterService : Service() {
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private val reportMutex = Mutex()
+ private lateinit var prefs: Prefs
+ private var periodicJob: Job? = null
+
+ private var cm: ConnectivityManager? = null
+ private var netCallback: ConnectivityManager.NetworkCallback? = null
+
+ private var lastStatus: String = "starting…"
+
+ // Charger + power-save changes.
+ private val powerReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ when (intent.action) {
+ Intent.ACTION_POWER_CONNECTED -> reportNow("charger connected")
+ Intent.ACTION_POWER_DISCONNECTED -> reportNow("charger disconnected")
+ PowerManager.ACTION_POWER_SAVE_MODE_CHANGED -> reportNow("power-save toggled")
+ }
+ }
+ }
+
+ // Bluetooth connect/disconnect for the chosen "airpods" device.
+ private val bluetoothReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (!prefs.airpodsEnabled || prefs.airpodsAddress.isBlank()) return
+ @Suppress("DEPRECATION")
+ val device: BluetoothDevice? =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
+ } else {
+ intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
+ }
+ if (device?.address != prefs.airpodsAddress) return
+ when (intent.action) {
+ BluetoothDevice.ACTION_ACL_CONNECTED -> {
+ prefs.airpodsConnected = true
+ reportNow("airpods connected")
+ }
+ BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
+ prefs.airpodsConnected = false
+ reportNow("airpods disconnected")
+ }
+ }
+ }
+ }
+
+ override fun onCreate() {
+ super.onCreate()
+ prefs = Prefs(this)
+ createChannel()
+ startForeground(NOTIF_ID, buildNotification("Reporting service running"))
+ registerReceivers()
+ startPeriodic()
+ reportNow("service start")
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ if (intent?.action == ACTION_STOP) {
+ stopSelf()
+ return START_NOT_STICKY
+ }
+ // Restart if killed by the system.
+ return START_STICKY
+ }
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onDestroy() {
+ unregisterReceivers()
+ periodicJob?.cancel()
+ scope.cancel()
+ super.onDestroy()
+ }
+
+ // --- receivers ---------------------------------------------------------
+
+ private fun registerReceivers() {
+ val powerFilter = IntentFilter().apply {
+ addAction(Intent.ACTION_POWER_CONNECTED)
+ addAction(Intent.ACTION_POWER_DISCONNECTED)
+ addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
+ }
+ registerReceiver(powerReceiver, powerFilter)
+
+ val btFilter = IntentFilter().apply {
+ addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
+ addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
+ }
+ registerReceiver(bluetoothReceiver, btFilter)
+
+ cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
+ val request = NetworkRequest.Builder()
+ .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
+ .build()
+ val cb = object : ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: Network) = reportNow("wifi connected")
+ override fun onLost(network: Network) = reportNow("wifi disconnected")
+ }
+ netCallback = cb
+ cm?.registerNetworkCallback(request, cb)
+ }
+
+ private fun unregisterReceivers() {
+ runCatching { unregisterReceiver(powerReceiver) }
+ runCatching { unregisterReceiver(bluetoothReceiver) }
+ netCallback?.let { cb -> runCatching { cm?.unregisterNetworkCallback(cb) } }
+ }
+
+ // --- periodic ----------------------------------------------------------
+
+ private fun startPeriodic() {
+ periodicJob?.cancel()
+ periodicJob = scope.launch {
+ while (isActive) {
+ delay(PERIOD_MS)
+ reportNow("periodic 5-min", includeLocation = true)
+ }
+ }
+ }
+
+ // --- reporting ---------------------------------------------------------
+
+ private fun reportNow(reason: String, includeLocation: Boolean = false) {
+ scope.launch {
+ // Serialise reports so overlapping events don't race.
+ reportMutex.withLock {
+ if (!prefs.isConfigured()) {
+ updateNotification("Not configured — open the app")
+ return@withLock
+ }
+ val snap = DeviceState.snapshot(this@ReporterService, prefs, includeLocation)
+ val result = withContext(Dispatchers.IO) { Reporter.report(prefs, snap) }
+ val stamp = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
+ lastStatus = if (result.ok) {
+ "$stamp OK ($reason)"
+ } else {
+ "$stamp FAIL ${result.message} ($reason)"
+ }
+ Log.i(TAG, lastStatus)
+ updateNotification(lastStatus)
+ }
+ }
+ }
+
+ // --- notification ------------------------------------------------------
+
+ private fun createChannel() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val channel = NotificationChannel(
+ CHANNEL_ID,
+ "Device Reporter",
+ NotificationManager.IMPORTANCE_LOW
+ ).apply { description = "Background device-state reporting" }
+ val nm = getSystemService(NotificationManager::class.java)
+ nm.createNotificationChannel(channel)
+ }
+ }
+
+ private fun buildNotification(text: String): Notification {
+ return NotificationCompat.Builder(this, CHANNEL_ID)
+ .setContentTitle("Device Reporter")
+ .setContentText(text)
+ .setSmallIcon(android.R.drawable.stat_sys_upload)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .build()
+ }
+
+ private fun updateNotification(text: String) {
+ val nm = getSystemService(NotificationManager::class.java)
+ nm.notify(NOTIF_ID, buildNotification(text))
+ }
+
+ companion object {
+ private const val TAG = "ReporterService"
+ private const val CHANNEL_ID = "device_reporter"
+ private const val NOTIF_ID = 1001
+ private const val PERIOD_MS = 5 * 60 * 1000L
+ const val ACTION_STOP = "uk.doughmination.devicereporter.STOP"
+
+ fun start(context: Context) {
+ val intent = Intent(context, ReporterService::class.java)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(intent)
+ } else {
+ context.startService(intent)
+ }
+ }
+
+ fun stop(context: Context) {
+ val intent = Intent(context, ReporterService::class.java).apply { action = ACTION_STOP }
+ context.startService(intent)
+ }
+ }
+}
diff --git a/api-helper/app/src/main/res/drawable/ic_launcher_foreground.xml b/api-helper/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 0000000..5d1f6e6
--- /dev/null
+++ b/api-helper/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,15 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M42,30h24a6,6 0,0 1,6 6v36a6,6 0,0 1,-6 6h-24a6,6 0,0 1,-6 -6v-36a6,6 0,0 1,6 -6zM48,26h12v4h-12z" />
+ <path
+ android:fillColor="#0B6E4F"
+ android:pathData="M42,38h24v28h-24z" />
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M42,58h24v8h-24z" />
+</vector>
diff --git a/api-helper/app/src/main/res/layout/activity_main.xml b/api-helper/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..6e14734
--- /dev/null
+++ b/api-helper/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,153 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:padding="20dp">
+
+ <TextView
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Device Reporter"
+ android:textSize="22sp"
+ android:textStyle="bold"
+ android:paddingBottom="12dp" />
+
+ <TextView
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Base URL"
+ android:textStyle="bold"
+ android:paddingTop="8dp" />
+
+ <EditText
+ android:id="@+id/inputBaseUrl"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:hint="https://doughmination.uk/v2"
+ android:inputType="textUri" />
+
+ <TextView
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="X-Battery-Key"
+ android:textStyle="bold"
+ android:paddingTop="8dp" />
+
+ <EditText
+ android:id="@+id/inputApiKey"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:hint="your secret key"
+ android:inputType="textPassword" />
+
+ <TextView
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Device name"
+ android:textStyle="bold"
+ android:paddingTop="8dp" />
+
+ <EditText
+ android:id="@+id/inputDevice"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:hint="pixel"
+ android:inputType="text" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:gravity="center_vertical"
+ android:paddingTop="16dp">
+
+ <TextView
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Watch connected (manual)"
+ android:textStyle="bold" />
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/switchWatch"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content" />
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:gravity="center_vertical"
+ android:paddingTop="8dp">
+
+ <TextView
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Enable AirPods (Bluetooth) reporting"
+ android:textStyle="bold" />
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/switchAirpods"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content" />
+ </LinearLayout>
+
+ <TextView
+ android:id="@+id/textAirpodsDevice"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="No AirPods device selected"
+ android:paddingTop="4dp" />
+
+ <Button
+ android:id="@+id/btnSelectAirpods"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Select AirPods device"
+ android:layout_marginTop="4dp" />
+
+ <Button
+ android:id="@+id/btnSave"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Save settings"
+ android:layout_marginTop="20dp" />
+
+ <Button
+ android:id="@+id/btnStart"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Start reporting service"
+ android:layout_marginTop="8dp" />
+
+ <Button
+ android:id="@+id/btnStop"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Stop reporting service"
+ android:layout_marginTop="8dp" />
+
+ <Button
+ android:id="@+id/btnTest"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Send test report now"
+ android:layout_marginTop="8dp" />
+
+ <TextView
+ android:id="@+id/textStatus"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Idle."
+ android:paddingTop="20dp"
+ android:textIsSelectable="true" />
+
+ </LinearLayout>
+</ScrollView>
diff --git a/api-helper/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/api-helper/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..a8a8fa5
--- /dev/null
+++ b/api-helper/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background" />
+ <foreground android:drawable="@drawable/ic_launcher_foreground" />
+</adaptive-icon>
diff --git a/api-helper/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/api-helper/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..a8a8fa5
--- /dev/null
+++ b/api-helper/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background" />
+ <foreground android:drawable="@drawable/ic_launcher_foreground" />
+</adaptive-icon>
diff --git a/api-helper/app/src/main/res/values/colors.xml b/api-helper/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..a1a60dc
--- /dev/null
+++ b/api-helper/app/src/main/res/values/colors.xml
@@ -0,0 +1,3 @@
+<resources>
+ <color name="ic_launcher_background">#0B6E4F</color>
+</resources>
diff --git a/api-helper/app/src/main/res/values/strings.xml b/api-helper/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..4f6eb3b
--- /dev/null
+++ b/api-helper/app/src/main/res/values/strings.xml
@@ -0,0 +1,3 @@
+<resources>
+ <string name="app_name">Device Reporter</string>
+</resources>
diff --git a/api-helper/app/src/main/res/values/themes.xml b/api-helper/app/src/main/res/values/themes.xml
new file mode 100644
index 0000000..5ec47c3
--- /dev/null
+++ b/api-helper/app/src/main/res/values/themes.xml
@@ -0,0 +1,3 @@
+<resources>
+ <style name="Theme.DeviceReporter" parent="Theme.MaterialComponents.DayNight.DarkActionBar" />
+</resources>
diff --git a/api-helper/build.gradle.kts b/api-helper/build.gradle.kts
new file mode 100644
index 0000000..017d909
--- /dev/null
+++ b/api-helper/build.gradle.kts
@@ -0,0 +1,4 @@
+plugins {
+ id("com.android.application") version "8.5.2" apply false
+ id("org.jetbrains.kotlin.android") version "1.9.24" apply false
+}
diff --git a/api-helper/gradle.properties b/api-helper/gradle.properties
new file mode 100644
index 0000000..f0a2e55
--- /dev/null
+++ b/api-helper/gradle.properties
@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
+android.useAndroidX=true
+kotlin.code.style=official
+android.nonTransitiveRClass=true
diff --git a/api-helper/gradle/wrapper/gradle-wrapper.jar b/api-helper/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..2c35211
Binary files /dev/null and b/api-helper/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/api-helper/gradle/wrapper/gradle-wrapper.properties b/api-helper/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..09523c0
--- /dev/null
+++ b/api-helper/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/api-helper/gradlew b/api-helper/gradlew
new file mode 100755
index 0000000..f5feea6
--- /dev/null
+++ b/api-helper/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/api-helper/gradlew.bat b/api-helper/gradlew.bat
new file mode 100644
index 0000000..9b42019
--- /dev/null
+++ b/api-helper/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/api-helper/settings.gradle.kts b/api-helper/settings.gradle.kts
new file mode 100644
index 0000000..7e5ef5a
--- /dev/null
+++ b/api-helper/settings.gradle.kts
@@ -0,0 +1,18 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.name = "DeviceReporter"
+include(":app")