From 937c73d81b9afdad8d5f0e64c4916d54211e8406 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Sat, 12 Sep 2026 19:35:38 -0700 Subject: [PATCH] Add battery indicator for Android Wear watch --- .../com/faceclaw/app/FaceclawWearBridge.java | 8 ++ CHANGELOG | 4 + app/apps/glanceboard/widgets/system-card.ts | 9 ++- app/g2/wear-remote.ts | 73 ++++++++++++++++++- app/native/wear-bridge.ts | 11 ++- app/ui/dashboard-settings.ts | 5 ++ app/ui/dashboard/settings-menus.ts | 4 +- app/ui/shell/chrome-layer.ts | 22 +++++- app/ui/shell/shell.ts | 6 +- wear/PROTOCOL.md | 14 +++- wear/app/src/main/AndroidManifest.xml | 11 +++ .../kotlin/com/faceclaw/wear/PhoneLink.kt | 47 +++++++++++- .../com/faceclaw/wear/PhoneListenerService.kt | 24 ++++++ .../main/kotlin/com/faceclaw/wear/Protocol.kt | 4 + .../kotlin/com/faceclaw/wear/WatchBattery.kt | 55 ++++++++++++++ 15 files changed, 279 insertions(+), 18 deletions(-) create mode 100644 wear/app/src/main/kotlin/com/faceclaw/wear/PhoneListenerService.kt create mode 100644 wear/app/src/main/kotlin/com/faceclaw/wear/WatchBattery.kt diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWearBridge.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWearBridge.java index 8e8f96ef..cb0da66f 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWearBridge.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWearBridge.java @@ -60,6 +60,10 @@ public final class FaceclawWearBridge { public static final String PATH_PREFIX = "/faceclaw"; public static final String PATH_STATE = "/faceclaw/state"; public static final String PATH_STATE_REQUEST = "/faceclaw/state/request"; + /** Watch -> phone: the watch's own battery; carries no seq and is never acked. */ + public static final String PATH_WATCH_BATTERY = "/faceclaw/battery"; + /** Phone -> watch: answered with PATH_WATCH_BATTERY even while the watch app is closed. */ + public static final String PATH_WATCH_BATTERY_REQUEST = "/faceclaw/battery/request"; public static final String PATH_ACK = "/faceclaw/ack"; public static final String PATH_EVENT = "/faceclaw/event"; @@ -284,6 +288,10 @@ public final class FaceclawWearBridge { boolean delivered = dispatchMessage(path, json, nodeId); if (delivered) return; + // A battery report answers a poll the dashboard sent; with no + // dashboard to receive it, it is simply dropped (the dashboard polls + // again when it starts), and the watch does not expect an ack. + if (PATH_WATCH_BATTERY.equals(path)) return; // No JS listener yet: tell the watch so it can explain why nothing is // happening. Only state requests are kept for replay (see class doc); diff --git a/CHANGELOG b/CHANGELOG index 09fa2b7f..84646671 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,9 @@ # Changelog +## 0.7.1 - Unreleased + +* Add Wear OS watch battery indicator to the top bar and Glanceboard + ## 0.7.0 - 2026-09-12 ### Major Features diff --git a/app/apps/glanceboard/widgets/system-card.ts b/app/apps/glanceboard/widgets/system-card.ts index ef60ac24..c9b2c601 100644 --- a/app/apps/glanceboard/widgets/system-card.ts +++ b/app/apps/glanceboard/widgets/system-card.ts @@ -11,6 +11,7 @@ import { onAnySettingChanged, phoneBatteryVisibilitySetting, ringBatteryVisibilitySetting, + watchBatteryVisibilitySetting, type BatteryIndicatorVisibility, } from "../../../ui/dashboard-settings"; import { shell } from "../../../ui/shell/shell"; @@ -30,9 +31,10 @@ const BATTERY_LABEL_VALUE = 150; type BatteryItem = { label: string; percent: number; charging: boolean }; /** - * Date and time, the phone's notification icons, the phone/G2/R1 battery - * indicators, and the Timers app's countdowns: the top bar's contents plus - * timers, laid out for a card. Battery style and per-device visibility + * Date and time, the phone's notification icons, the phone/watch/G2/R1 + * battery indicators (the Wear OS watch's only while one is reachable), and + * the Timers app's countdowns: the top bar's contents plus timers, laid out + * for a card. Battery style and per-device visibility * follow Settings > Display > Battery indicators, so the card agrees with * the bar. Countdowns tick once a second only while one is running. */ @@ -137,6 +139,7 @@ function collectBatteryItems(): BatteryItem[] { const phone = readPhoneBatteryState(); push(phoneBatteryVisibilitySetting.get(), "Phone", phone.battery, phone.charging); const levels = shell.getBatteryLevels(); + push(watchBatteryVisibilitySetting.get(), "Watch", levels.watch, levels.watchCharging); push(glassesBatteryVisibilitySetting.get(), "G2", levels.headset, levels.headsetCharging); if (levels.ring !== null && Number.isInteger(levels.ring) && levels.ring >= 0 && levels.ring <= 100) { push(ringBatteryVisibilitySetting.get(), "R1", levels.ring, levels.ringCharging); diff --git a/app/g2/wear-remote.ts b/app/g2/wear-remote.ts index 629d9d96..4e5a464d 100644 --- a/app/g2/wear-remote.ts +++ b/app/g2/wear-remote.ts @@ -14,6 +14,12 @@ * stream to the watch as events so a query made from the wrist can be read * from the wrist. * + * The watch's own battery flows the other way for the glasses' top-bar and + * Glanceboard indicators: the phone polls it (the watch answers from a + * listener service even while its app is closed) and the open watch app + * pushes changes unprompted. The level lives in shell.getBatteryLevels() + * beside the G2 and R1 ones and is cleared when no watch is reachable. + * * Transport is app/native/wear-bridge.ts (Java FaceclawWearBridge); the * message shapes are documented in wear/PROTOCOL.md. */ @@ -88,6 +94,14 @@ const MAX_TEXT_LENGTH = 2000; const STATE_PUBLISH_DEBOUNCE_MS = 150; const STATE_REFRESH_INTERVAL_MS = 30_000; const ASSISTANT_STREAM_MIN_INTERVAL_MS = 250; +// Each poll wakes the watch app's process for a moment; the level changes +// slowly, and a charger being plugged in is pushed at once whenever the +// watch app is open, so a leisurely cadence is enough. +const WATCH_BATTERY_POLL_INTERVAL_MS = 5 * 60_000; +// Floor between polls that state changes (a watch coming into range, the +// glasses connecting) would otherwise trigger back to back. +const WATCH_BATTERY_POLL_MIN_GAP_MS = 20_000; +const WATCH_BATTERY_URGENT_POLL_LIMIT = 3; /** What the dashboard controller lends the watch remote. */ export type WearRemoteHost = { @@ -120,6 +134,11 @@ export class WearRemote { private assistantStreamTimer: ReturnType | null = null; private assistantPendingText: string | null = null; private lastAssistantSentAtMs = 0; + private lastWatchBatteryPollAtMs = 0; + private watchBatteryKnown = false; + // Urgent polls that got no answer; a watch app too old to answer them + // must not be poked every publish, so after a few the cadence drops back. + private watchBatteryPollsUnanswered = 0; constructor(private readonly host: WearRemoteHost) { this.active = wearBridge.isAvailable(); @@ -141,8 +160,16 @@ export class WearRemote { connection.reachable ? `watch: ${connection.watchName || "watch"} reachable` : "watch: no watch reachable", ); } - // A watch that just came into range gets the current state at once. - if (connection.reachable) this.publishNow(true); + // A watch that just came into range gets the current state at once, + // and is asked for its battery; one that left takes its indicator + // with it (no placeholder). + if (changed) this.watchBatteryPollsUnanswered = 0; + if (connection.reachable) { + this.publishNow(true); + this.pollWatchBattery(true); + } else if (changed) { + this.setWatchBattery(null, null); + } }); shell.onAssistantActivity((event) => this.forwardAssistantActivity(event)); shell.onAlertShown((text) => { @@ -155,9 +182,38 @@ export class WearRemote { // Catch-all refresh for state the controller does not announce (cheap: // identical states are dropped on the Java side). setInterval(() => this.schedulePublish(), STATE_REFRESH_INTERVAL_MS); + setInterval(() => this.pollWatchBattery(false), WATCH_BATTERY_POLL_INTERVAL_MS); this.schedulePublish(); } + /** + * Ask the reachable watch for its battery. `urgent` skips the poll gap for + * a level that is not known yet (the glasses just connected, the watch + * just appeared); a level already on screen waits for the regular cadence. + */ + private pollWatchBattery(urgent: boolean): void { + if (!this.active || !this.watchReachable) return; + const now = Date.now(); + const hurry = urgent && !this.watchBatteryKnown && this.watchBatteryPollsUnanswered < WATCH_BATTERY_URGENT_POLL_LIMIT; + const gap = hurry ? WATCH_BATTERY_POLL_MIN_GAP_MS : WATCH_BATTERY_POLL_INTERVAL_MS; + if (now - this.lastWatchBatteryPollAtMs < gap) return; + this.lastWatchBatteryPollAtMs = now; + this.watchBatteryPollsUnanswered++; + wearBridge.sendToWatch(WEAR_PATHS.batteryRequest, {}); + } + + /** Record a watch battery report (or its absence) and repaint the indicators. */ + private setWatchBattery(battery: number | null, charging: boolean | null): void { + const current = shell.getBatteryLevels(); + if (current.watch === battery && current.watchCharging === charging) return; + this.watchBatteryKnown = battery !== null; + shell.setBatteryLevels({ watch: battery, watchCharging: charging }); + // Repaint the top bar, as the controller does for G2/R1 reports. + const phase = this.host.getState().phase; + if (phase === "connected" || phase === "charging") this.host.requestShellRender(); + this.host.appendLog(battery === null ? "watch: battery unknown" : `watch: battery ${battery}%${charging ? " (charging)" : ""}`); + } + /** Whether a watch running the Faceclaw watch app is reachable right now. */ isWatchReachable(): boolean { return this.watchReachable; @@ -183,6 +239,10 @@ export class WearRemote { } catch (error) { this.host.appendLog(`watch: state publish failed: ${formatError(error)}`); } + // The indicator is only ever drawn while the glasses are connected, so + // a still-unknown level is worth asking for as soon as they are. + const phase = this.host.getState().phase; + if (phase === "connected" || phase === "charging") this.pollWatchBattery(true); } private buildState(): Record { @@ -240,6 +300,15 @@ export class WearRemote { ack(true); return; } + if (message.path === WEAR_PATHS.battery) { + // Status, not control: not gated by the remote setting and never + // acked (the watch sends it fire-and-forget, without a seq). + this.watchBatteryPollsUnanswered = 0; + const battery = readNumber(message.payload.battery, -1); + const valid = Number.isInteger(battery) && battery >= 0 && battery <= 100; + this.setWatchBattery(valid ? battery : null, valid ? message.payload.charging === true : null); + return; + } if (!watchRemoteEnabledSetting.get()) { ack(false, "Watch control is turned off in Faceclaw's Settings > Watch."); return; diff --git a/app/native/wear-bridge.ts b/app/native/wear-bridge.ts index 7981809f..6a4e7ca2 100644 --- a/app/native/wear-bridge.ts +++ b/app/native/wear-bridge.ts @@ -24,6 +24,10 @@ export const WEAR_PATHS = { text: "/faceclaw/text", /** Watch -> phone: please re-publish the state item. */ stateRequest: "/faceclaw/state/request", + /** Watch -> phone: the watch's own battery ({battery, charging}); never acked. */ + battery: "/faceclaw/battery", + /** Phone -> watch: please report the watch battery (answered even while the watch app is closed). */ + batteryRequest: "/faceclaw/battery/request", /** Phone -> watch: reply to any of the above. */ ack: "/faceclaw/ack", /** Phone -> watch: assistant activity, alerts, voice-dialog transcripts. */ @@ -157,7 +161,12 @@ class WearBridge { /** Send an event to every reachable watch. */ sendEvent(payload: Record): void { - this.getJava()?.sendToWatch(WEAR_PATHS.event, JSON.stringify(payload)); + this.sendToWatch(WEAR_PATHS.event, payload); + } + + /** Send a message on any phone -> watch path to every reachable watch. */ + sendToWatch(path: string, payload: Record): void { + this.getJava()?.sendToWatch(path, JSON.stringify(payload)); } /** Acknowledge a watch message; `seq` echoes the watch's sequence number. */ diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index 8b3e28f9..5ac7ba8e 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -244,6 +244,10 @@ export const glassesBatteryVisibilitySetting = batteryVisibilitySetting( export const ringBatteryVisibilitySetting = batteryVisibilitySetting( "ringBatteryVisibility", "R1", "display.battery.ringVisibility", ); +/** The Wear OS watch; the indicator only exists while a watch is reachable. */ +export const watchBatteryVisibilitySetting = batteryVisibilitySetting( + "watchBatteryVisibility", "Watch", "display.battery.watchVisibility", +); /** Whether an indicator with this visibility setting shows at the given charge. */ export function batteryIndicatorVisible(visibility: BatteryIndicatorVisibility, percent: number): boolean { @@ -262,6 +266,7 @@ export function batteryIndicatorSettingsKey(): string { phoneBatteryVisibilitySetting.get(), glassesBatteryVisibilitySetting.get(), ringBatteryVisibilitySetting.get(), + watchBatteryVisibilitySetting.get(), ].join("|"); } diff --git a/app/ui/dashboard/settings-menus.ts b/app/ui/dashboard/settings-menus.ts index 790941d3..f67a1066 100644 --- a/app/ui/dashboard/settings-menus.ts +++ b/app/ui/dashboard/settings-menus.ts @@ -38,6 +38,7 @@ import { glassesBatteryVisibilitySetting, phoneBatteryVisibilitySetting, ringBatteryVisibilitySetting, + watchBatteryVisibilitySetting, displayModeSetting, navigateDisplayModeSetting, navigateVerticalPositionSetting, @@ -248,11 +249,12 @@ function batteryIndicatorsMenuItem(): MenuItem { return { label: "Battery indicators", description: - "Top-bar battery indicators for the phone, glasses, and ring: their style, and whether each shows always, only when low, or never.", + "Top-bar battery indicators for the phone, Wear OS watch, glasses, and ring: their style, and whether each shows always, only when low, or never.", onSelect: (ctx) => { openSettingsSubMenu(ctx, "Battery indicators", [ enumSettingMenuItem(batteryDisplayModeSetting), enumSettingMenuItem(phoneBatteryVisibilitySetting), + enumSettingMenuItem(watchBatteryVisibilitySetting), enumSettingMenuItem(glassesBatteryVisibilitySetting), enumSettingMenuItem(ringBatteryVisibilitySetting), ]); diff --git a/app/ui/shell/chrome-layer.ts b/app/ui/shell/chrome-layer.ts index ef5d69e0..ebb57300 100644 --- a/app/ui/shell/chrome-layer.ts +++ b/app/ui/shell/chrome-layer.ts @@ -13,6 +13,7 @@ import { glassesBatteryVisibilitySetting, phoneBatteryVisibilitySetting, ringBatteryVisibilitySetting, + watchBatteryVisibilitySetting, type BatteryIndicatorVisibility, } from "../dashboard-settings"; import { formatClockDate, formatClockTime } from "../clock-format"; @@ -108,7 +109,15 @@ export type ShellChromeState = { /** Height mode of the foreground window; decides where its top bar sits. */ foregroundHeightMode: WindowHeightMode; foregroundAppId?: string; - battery: { headset: number | null; headsetCharging: boolean | null; ring: number | null; ringCharging: boolean | null }; + battery: { + headset: number | null; + headsetCharging: boolean | null; + ring: number | null; + ringCharging: boolean | null; + /** The Wear OS watch (app/g2/wear-remote.ts); null when no watch is reachable. */ + watch: number | null; + watchCharging: boolean | null; + }; /** App-provided tray images, drawn between notification icons and batteries. */ trayIcons: GrayImage[]; }; @@ -342,9 +351,10 @@ export class ShellChromeLayer implements Layer { } /** - * Labelled battery indicators for the phone, G2, and R1, right-aligned in - * the top bar. The Settings > Display > Battery indicators submenu picks - * the style (label beside a gauge icon or percentage, or stacked above + * Labelled battery indicators for the phone, Wear OS watch, G2, and R1, + * right-aligned in the top bar. The watch one exists only while a watch + * running the Faceclaw watch app is reachable (no placeholder otherwise). + * The Settings > Display > Battery indicators submenu picks the style (label beside a gauge icon or percentage, or stacked above * either) and, per device, whether the indicator shows always, only below * 50%, or never. Returns the left edge of the battery block. */ @@ -355,6 +365,10 @@ export class ShellChromeLayer implements Layer { if (phone.battery !== null && Number.isFinite(phone.battery)) { pushBatteryItem(items, phoneBatteryVisibilitySetting.get(), "Phone", phone.battery, Boolean(phone.charging)); } + if (state.battery.watch !== null && Number.isFinite(state.battery.watch)) { + pushBatteryItem(items, watchBatteryVisibilitySetting.get(), "Watch", state.battery.watch, + Boolean(state.battery.watchCharging)); + } if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) { pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", state.battery.headset, Boolean(state.battery.headsetCharging)); diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts index 636f10b7..3d106809 100644 --- a/app/ui/shell/shell.ts +++ b/app/ui/shell/shell.ts @@ -304,7 +304,9 @@ class Shell { private lastInputAtMs = Date.now(); /** The most recent input event received, for windows gaining focus (see ShellWindow.onFocus). */ private lastInput: InputEvent | null = null; - private battery: ShellChromeState["battery"] = { headset: null, headsetCharging: null, ring: null, ringCharging: null }; + private battery: ShellChromeState["battery"] = { + headset: null, headsetCharging: null, ring: null, ringCharging: null, watch: null, watchCharging: null, + }; private attention = new Map(); // App-provided top-bar tray icons, keyed by owner id; drawn between the // notification icons and the battery indicators. @@ -495,7 +497,7 @@ class Shell { return this.screenOn; } - /** Current headset battery levels (for the assistant's get_state tool). */ + /** Current G2, R1, and Wear OS watch battery levels (top bar, Glanceboard, assistant). */ getBatteryLevels(): ShellChromeState["battery"] { return this.battery; } diff --git a/wear/PROTOCOL.md b/wear/PROTOCOL.md index 43215491..90aaf2b0 100644 --- a/wear/PROTOCOL.md +++ b/wear/PROTOCOL.md @@ -11,8 +11,8 @@ Capabilities (`res/values/wear.xml` on each side): the phone advertises `faceclaw_phone`, the watch `faceclaw_watch`. Each side finds the other with `CapabilityClient.getCapability(…, FILTER_REACHABLE)`. -Every watch → phone message carries `seq` (monotonic per watch process) and is -answered on `/faceclaw/ack`. +Every watch → phone message except `/faceclaw/battery` carries `seq` +(monotonic per watch process) and is answered on `/faceclaw/ack`. ## Watch → phone (MessageClient) @@ -23,9 +23,10 @@ answered on `/faceclaw/ack`. | `/faceclaw/assistant` | `{text}` | Send a query to the assistant (`shell.sendToAssistant`) — the reply shows on the glasses and streams back to the watch as events. | | `/faceclaw/text` | `{text}` | Type text into the foreground window (`receiveTextInput`, e.g. the terminal). Refused when the window doesn't take text. | | `/faceclaw/state/request` | `{}` | Re-publish the state item even if unchanged. | +| `/faceclaw/battery` | `{battery, charging}` | The watch's own battery (`battery` 0–100 or null, `charging` bool) for the glasses' top-bar and Glanceboard "Watch" indicator. Sent in answer to `/faceclaw/battery/request` by `PhoneListenerService` (which Play services starts even while the watch app is closed) and, while the app is open, whenever the level or charging state changes. Carries no `seq` and is never acked. | -All of the above except `state/request` are refused with `ok:false` when the -phone's "Watch remote control" setting is off. +All of the above except `state/request` and `battery` are refused with +`ok:false` when the phone's "Watch remote control" setting is off. ## Phone → watch @@ -34,6 +35,11 @@ phone's "Watch remote control" setting is off. app process for the message but the JS dashboard isn't up (the user has not opened Faceclaw since boot); the watch shows "Open Faceclaw on the phone". +`/faceclaw/battery/request` (MessageClient, to every reachable watch): `{}`. +Please send `/faceclaw/battery` now. The phone sends it when a watch becomes +reachable, when the glasses connect with the level still unknown, and every +5 minutes after that; the indicator disappears when no watch is reachable. + `/faceclaw/event` (MessageClient, to every reachable watch): - `{type:"assistant", phase, text}` — `phase` ∈ `thinking`, `streaming` (text so far, replace semantics, ≤ 4/s), `done` (final text), `error` (message), diff --git a/wear/app/src/main/AndroidManifest.xml b/wear/app/src/main/AndroidManifest.xml index 1a700075..e489248b 100644 --- a/wear/app/src/main/AndroidManifest.xml +++ b/wear/app/src/main/AndroidManifest.xml @@ -33,5 +33,16 @@ + + + + + + + + diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/PhoneLink.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/PhoneLink.kt index 0934fa9b..bcd635eb 100644 --- a/wear/app/src/main/kotlin/com/faceclaw/wear/PhoneLink.kt +++ b/wear/app/src/main/kotlin/com/faceclaw/wear/PhoneLink.kt @@ -1,8 +1,12 @@ package com.faceclaw.wear +import android.content.BroadcastReceiver import android.content.Context +import android.content.Intent +import android.content.IntentFilter import android.net.Uri import android.util.Log +import androidx.core.content.ContextCompat import com.google.android.gms.common.api.ApiException import com.google.android.gms.wearable.CapabilityClient import com.google.android.gms.wearable.CapabilityInfo @@ -83,6 +87,15 @@ class PhoneLink(context: Context) : private val pendingAcks = ConcurrentHashMap() private var noticeJob: Job? = null private var started = false + /** The battery state last reported to the phone (pushes only on change). */ + private var lastBatteryReported: WatchBatteryState? = null + // While the app is open, charge and charging changes reach the phone at + // once; closed, the phone polls PhoneListenerService instead. + private val batteryReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == Intent.ACTION_BATTERY_CHANGED) reportBattery(force = false) + } + } private val _state = MutableStateFlow(null) val state: StateFlow = _state.asStateFlow() @@ -105,12 +118,28 @@ class PhoneLink(context: Context) : messageClient.addListener(this) dataClient.addListener(this) capabilityClient.addListener(this, Protocol.CAPABILITY_PHONE) + try { + ContextCompat.registerReceiver( + appContext, + batteryReceiver, + IntentFilter(Intent.ACTION_BATTERY_CHANGED), + ContextCompat.RECEIVER_NOT_EXPORTED, + ) + } catch (error: Exception) { + Log.w(TAG, "battery receiver registration failed", error) + } refresh() } fun stop() { if (!started) return started = false + try { + appContext.unregisterReceiver(batteryReceiver) + } catch (error: Exception) { + Log.w(TAG, "battery receiver unregistration failed", error) + } + lastBatteryReported = null messageClient.removeListener(this) dataClient.removeListener(this) capabilityClient.removeListener(this, Protocol.CAPABILITY_PHONE) @@ -121,10 +150,26 @@ class PhoneLink(context: Context) : scope.launch { findPhone() loadStateItem() - if (_link.value.phoneAppInstalled) requestState() + if (_link.value.phoneAppInstalled) { + requestState() + reportBattery(force = true) + } } } + /** + * Send our battery to the phone (for the glasses' Watch indicator). + * Skipped when unchanged since the last report unless `force`. + */ + private fun reportBattery(force: Boolean) { + val nodeId = _link.value.phoneNodeId ?: return + if (!_link.value.phoneAppInstalled) return + val state = WatchBattery.read(appContext) + if (!force && state == lastBatteryReported) return + lastBatteryReported = state + WatchBattery.report(appContext, nodeId, state) + } + // ---- outbound ----------------------------------------------------- fun sendGesture(gesture: Gesture, steps: Int = 1) { diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/PhoneListenerService.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/PhoneListenerService.kt new file mode 100644 index 00000000..994fb112 --- /dev/null +++ b/wear/app/src/main/kotlin/com/faceclaw/wear/PhoneListenerService.kt @@ -0,0 +1,24 @@ +package com.faceclaw.wear + +import android.util.Log +import com.google.android.gms.wearable.MessageEvent +import com.google.android.gms.wearable.WearableListenerService + +/** + * Play services starts this (in the watch app's process) for messages under + * /faceclaw/battery whether or not the app is open, so the phone can poll + * the watch battery for the glasses' indicator while the watch sits idle. + * Everything else the phone sends (acks, events, the state item) is only + * meaningful to a running PhoneLink and is not routed here. + */ +class PhoneListenerService : WearableListenerService() { + override fun onMessageReceived(event: MessageEvent) { + if (event.path != Protocol.PATH_BATTERY_REQUEST) return + Log.d(TAG, "battery request from ${event.sourceNodeId}") + WatchBattery.report(this, event.sourceNodeId) + } + + private companion object { + const val TAG = "FaceclawWear" + } +} diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt index 7e430742..b8a69790 100644 --- a/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt +++ b/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt @@ -15,6 +15,10 @@ object Protocol { const val PATH_ASSISTANT = "/faceclaw/assistant" const val PATH_TEXT = "/faceclaw/text" const val PATH_STATE_REQUEST = "/faceclaw/state/request" + /** Watch -> phone: our own battery ({battery, charging}); no seq, never acked. */ + const val PATH_BATTERY = "/faceclaw/battery" + /** Phone -> watch: please send PATH_BATTERY now (answered by PhoneListenerService). */ + const val PATH_BATTERY_REQUEST = "/faceclaw/battery/request" const val PATH_ACK = "/faceclaw/ack" const val PATH_EVENT = "/faceclaw/event" const val PATH_STATE = "/faceclaw/state" diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/WatchBattery.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/WatchBattery.kt new file mode 100644 index 00000000..408cb1e6 --- /dev/null +++ b/wear/app/src/main/kotlin/com/faceclaw/wear/WatchBattery.kt @@ -0,0 +1,55 @@ +package com.faceclaw.wear + +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.BatteryManager +import android.util.Log +import com.google.android.gms.wearable.Wearable +import org.json.JSONObject + +/** The watch's own charge level and charging state, for the glasses' battery indicators. */ +data class WatchBatteryState(val battery: Int?, val charging: Boolean) { + fun toJson(): JSONObject = JSONObject() + .put("battery", battery ?: JSONObject.NULL) + .put("charging", charging) +} + +/** + * Reads the watch battery from the sticky ACTION_BATTERY_CHANGED broadcast + * (no receiver needed) and reports it to the phone on /faceclaw/battery. Used + * both by PhoneListenerService, which answers the phone's polls while the app + * is closed, and by PhoneLink, which pushes changes while the app is open. + */ +object WatchBattery { + private const val TAG = "FaceclawWear" + + fun read(context: Context): WatchBatteryState { + val intent: Intent? = try { + context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) + } catch (error: Exception) { + Log.w(TAG, "battery read failed", error) + null + } + if (intent == null) return WatchBatteryState(null, false) + val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) + val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) + val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1) + val percent = if (level >= 0 && scale > 0) (level * 100 + scale / 2) / scale else null + val charging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL + return WatchBatteryState(percent?.coerceIn(0, 100), charging) + } + + /** Fire-and-forget: the phone never acks battery reports. */ + fun report(context: Context, nodeId: String, state: WatchBatteryState = read(context)) { + val payload = state.toJson().toString() + Log.d(TAG, "send ${Protocol.PATH_BATTERY} $payload") + try { + Wearable.getMessageClient(context.applicationContext) + .sendMessage(nodeId, Protocol.PATH_BATTERY, payload.toByteArray(Charsets.UTF_8)) + .addOnFailureListener { error -> Log.w(TAG, "battery report failed", error) } + } catch (error: Exception) { + Log.w(TAG, "battery report failed", error) + } + } +}