Add battery indicator for Android Wear watch

This commit is contained in:
James Babcock committed 2026-09-12 19:35:38 -07:00
1 parent 5bbb04abce
commit 937c73d81b
15 files changed
+279 -18

No files matched your search

@@ -60,6 +60,10 @@ public final class FaceclawWearBridge {
public static final String PATH_PREFIX = "/faceclaw"; public static final String PATH_PREFIX = "/faceclaw";
public static final String PATH_STATE = "/faceclaw/state"; public static final String PATH_STATE = "/faceclaw/state";
public static final String PATH_STATE_REQUEST = "/faceclaw/state/request"; 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_ACK = "/faceclaw/ack";
public static final String PATH_EVENT = "/faceclaw/event"; public static final String PATH_EVENT = "/faceclaw/event";
@@ -284,6 +288,10 @@ public final class FaceclawWearBridge {
boolean delivered = dispatchMessage(path, json, nodeId); boolean delivered = dispatchMessage(path, json, nodeId);
if (delivered) return; 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 // 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); // happening. Only state requests are kept for replay (see class doc);
+4
View File
@@ -1,5 +1,9 @@
# Changelog # Changelog
## 0.7.1 - Unreleased
* Add Wear OS watch battery indicator to the top bar and Glanceboard
## 0.7.0 - 2026-09-12 ## 0.7.0 - 2026-09-12
### Major Features ### Major Features
+6 -3
View File
@@ -11,6 +11,7 @@ import {
onAnySettingChanged, onAnySettingChanged,
phoneBatteryVisibilitySetting, phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting, ringBatteryVisibilitySetting,
watchBatteryVisibilitySetting,
type BatteryIndicatorVisibility, type BatteryIndicatorVisibility,
} from "../../../ui/dashboard-settings"; } from "../../../ui/dashboard-settings";
import { shell } from "../../../ui/shell/shell"; import { shell } from "../../../ui/shell/shell";
@@ -30,9 +31,10 @@ const BATTERY_LABEL_VALUE = 150;
type BatteryItem = { label: string; percent: number; charging: boolean }; type BatteryItem = { label: string; percent: number; charging: boolean };
/** /**
* Date and time, the phone's notification icons, the phone/G2/R1 battery * Date and time, the phone's notification icons, the phone/watch/G2/R1
* indicators, and the Timers app's countdowns: the top bar's contents plus * battery indicators (the Wear OS watch's only while one is reachable), and
* timers, laid out for a card. Battery style and per-device visibility * 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 * follow Settings > Display > Battery indicators, so the card agrees with
* the bar. Countdowns tick once a second only while one is running. * the bar. Countdowns tick once a second only while one is running.
*/ */
@@ -137,6 +139,7 @@ function collectBatteryItems(): BatteryItem[] {
const phone = readPhoneBatteryState(); const phone = readPhoneBatteryState();
push(phoneBatteryVisibilitySetting.get(), "Phone", phone.battery, phone.charging); push(phoneBatteryVisibilitySetting.get(), "Phone", phone.battery, phone.charging);
const levels = shell.getBatteryLevels(); const levels = shell.getBatteryLevels();
push(watchBatteryVisibilitySetting.get(), "Watch", levels.watch, levels.watchCharging);
push(glassesBatteryVisibilitySetting.get(), "G2", levels.headset, levels.headsetCharging); push(glassesBatteryVisibilitySetting.get(), "G2", levels.headset, levels.headsetCharging);
if (levels.ring !== null && Number.isInteger(levels.ring) && levels.ring >= 0 && levels.ring <= 100) { if (levels.ring !== null && Number.isInteger(levels.ring) && levels.ring >= 0 && levels.ring <= 100) {
push(ringBatteryVisibilitySetting.get(), "R1", levels.ring, levels.ringCharging); push(ringBatteryVisibilitySetting.get(), "R1", levels.ring, levels.ringCharging);
+71 -2
View File
@@ -14,6 +14,12 @@
* stream to the watch as events so a query made from the wrist can be read * stream to the watch as events so a query made from the wrist can be read
* from the wrist. * 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 * Transport is app/native/wear-bridge.ts (Java FaceclawWearBridge); the
* message shapes are documented in wear/PROTOCOL.md. * 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_PUBLISH_DEBOUNCE_MS = 150;
const STATE_REFRESH_INTERVAL_MS = 30_000; const STATE_REFRESH_INTERVAL_MS = 30_000;
const ASSISTANT_STREAM_MIN_INTERVAL_MS = 250; 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. */ /** What the dashboard controller lends the watch remote. */
export type WearRemoteHost = { export type WearRemoteHost = {
@@ -120,6 +134,11 @@ export class WearRemote {
private assistantStreamTimer: ReturnType<typeof setTimeout> | null = null; private assistantStreamTimer: ReturnType<typeof setTimeout> | null = null;
private assistantPendingText: string | null = null; private assistantPendingText: string | null = null;
private lastAssistantSentAtMs = 0; 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) { constructor(private readonly host: WearRemoteHost) {
this.active = wearBridge.isAvailable(); this.active = wearBridge.isAvailable();
@@ -141,8 +160,16 @@ export class WearRemote {
connection.reachable ? `watch: ${connection.watchName || "watch"} reachable` : "watch: no watch reachable", connection.reachable ? `watch: ${connection.watchName || "watch"} reachable` : "watch: no watch reachable",
); );
} }
// A watch that just came into range gets the current state at once. // A watch that just came into range gets the current state at once,
if (connection.reachable) this.publishNow(true); // 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.onAssistantActivity((event) => this.forwardAssistantActivity(event));
shell.onAlertShown((text) => { shell.onAlertShown((text) => {
@@ -155,9 +182,38 @@ export class WearRemote {
// Catch-all refresh for state the controller does not announce (cheap: // Catch-all refresh for state the controller does not announce (cheap:
// identical states are dropped on the Java side). // identical states are dropped on the Java side).
setInterval(() => this.schedulePublish(), STATE_REFRESH_INTERVAL_MS); setInterval(() => this.schedulePublish(), STATE_REFRESH_INTERVAL_MS);
setInterval(() => this.pollWatchBattery(false), WATCH_BATTERY_POLL_INTERVAL_MS);
this.schedulePublish(); 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. */ /** Whether a watch running the Faceclaw watch app is reachable right now. */
isWatchReachable(): boolean { isWatchReachable(): boolean {
return this.watchReachable; return this.watchReachable;
@@ -183,6 +239,10 @@ export class WearRemote {
} catch (error) { } catch (error) {
this.host.appendLog(`watch: state publish failed: ${formatError(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<string, unknown> { private buildState(): Record<string, unknown> {
@@ -240,6 +300,15 @@ export class WearRemote {
ack(true); ack(true);
return; 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()) { if (!watchRemoteEnabledSetting.get()) {
ack(false, "Watch control is turned off in Faceclaw's Settings > Watch."); ack(false, "Watch control is turned off in Faceclaw's Settings > Watch.");
return; return;
+10 -1
View File
@@ -24,6 +24,10 @@ export const WEAR_PATHS = {
text: "/faceclaw/text", text: "/faceclaw/text",
/** Watch -> phone: please re-publish the state item. */ /** Watch -> phone: please re-publish the state item. */
stateRequest: "/faceclaw/state/request", 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. */ /** Phone -> watch: reply to any of the above. */
ack: "/faceclaw/ack", ack: "/faceclaw/ack",
/** Phone -> watch: assistant activity, alerts, voice-dialog transcripts. */ /** Phone -> watch: assistant activity, alerts, voice-dialog transcripts. */
@@ -157,7 +161,12 @@ class WearBridge {
/** Send an event to every reachable watch. */ /** Send an event to every reachable watch. */
sendEvent(payload: Record<string, unknown>): void { sendEvent(payload: Record<string, unknown>): 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<string, unknown>): void {
this.getJava()?.sendToWatch(path, JSON.stringify(payload));
} }
/** Acknowledge a watch message; `seq` echoes the watch's sequence number. */ /** Acknowledge a watch message; `seq` echoes the watch's sequence number. */
+5
View File
@@ -244,6 +244,10 @@ export const glassesBatteryVisibilitySetting = batteryVisibilitySetting(
export const ringBatteryVisibilitySetting = batteryVisibilitySetting( export const ringBatteryVisibilitySetting = batteryVisibilitySetting(
"ringBatteryVisibility", "R1", "display.battery.ringVisibility", "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. */ /** Whether an indicator with this visibility setting shows at the given charge. */
export function batteryIndicatorVisible(visibility: BatteryIndicatorVisibility, percent: number): boolean { export function batteryIndicatorVisible(visibility: BatteryIndicatorVisibility, percent: number): boolean {
@@ -262,6 +266,7 @@ export function batteryIndicatorSettingsKey(): string {
phoneBatteryVisibilitySetting.get(), phoneBatteryVisibilitySetting.get(),
glassesBatteryVisibilitySetting.get(), glassesBatteryVisibilitySetting.get(),
ringBatteryVisibilitySetting.get(), ringBatteryVisibilitySetting.get(),
watchBatteryVisibilitySetting.get(),
].join("|"); ].join("|");
} }
+3 -1
View File
@@ -38,6 +38,7 @@ import {
glassesBatteryVisibilitySetting, glassesBatteryVisibilitySetting,
phoneBatteryVisibilitySetting, phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting, ringBatteryVisibilitySetting,
watchBatteryVisibilitySetting,
displayModeSetting, displayModeSetting,
navigateDisplayModeSetting, navigateDisplayModeSetting,
navigateVerticalPositionSetting, navigateVerticalPositionSetting,
@@ -248,11 +249,12 @@ function batteryIndicatorsMenuItem(): MenuItem {
return { return {
label: "Battery indicators", label: "Battery indicators",
description: 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) => { onSelect: (ctx) => {
openSettingsSubMenu(ctx, "Battery indicators", [ openSettingsSubMenu(ctx, "Battery indicators", [
enumSettingMenuItem(batteryDisplayModeSetting), enumSettingMenuItem(batteryDisplayModeSetting),
enumSettingMenuItem(phoneBatteryVisibilitySetting), enumSettingMenuItem(phoneBatteryVisibilitySetting),
enumSettingMenuItem(watchBatteryVisibilitySetting),
enumSettingMenuItem(glassesBatteryVisibilitySetting), enumSettingMenuItem(glassesBatteryVisibilitySetting),
enumSettingMenuItem(ringBatteryVisibilitySetting), enumSettingMenuItem(ringBatteryVisibilitySetting),
]); ]);
+18 -4
View File
@@ -13,6 +13,7 @@ import {
glassesBatteryVisibilitySetting, glassesBatteryVisibilitySetting,
phoneBatteryVisibilitySetting, phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting, ringBatteryVisibilitySetting,
watchBatteryVisibilitySetting,
type BatteryIndicatorVisibility, type BatteryIndicatorVisibility,
} from "../dashboard-settings"; } from "../dashboard-settings";
import { formatClockDate, formatClockTime } from "../clock-format"; 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. */ /** Height mode of the foreground window; decides where its top bar sits. */
foregroundHeightMode: WindowHeightMode; foregroundHeightMode: WindowHeightMode;
foregroundAppId?: string; 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. */ /** App-provided tray images, drawn between notification icons and batteries. */
trayIcons: GrayImage[]; trayIcons: GrayImage[];
}; };
@@ -342,9 +351,10 @@ export class ShellChromeLayer implements Layer {
} }
/** /**
* Labelled battery indicators for the phone, G2, and R1, right-aligned in * Labelled battery indicators for the phone, Wear OS watch, G2, and R1,
* the top bar. The Settings > Display > Battery indicators submenu picks * right-aligned in the top bar. The watch one exists only while a watch
* the style (label beside a gauge icon or percentage, or stacked above * 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 * either) and, per device, whether the indicator shows always, only below
* 50%, or never. Returns the left edge of the battery block. * 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)) { if (phone.battery !== null && Number.isFinite(phone.battery)) {
pushBatteryItem(items, phoneBatteryVisibilitySetting.get(), "Phone", phone.battery, Boolean(phone.charging)); 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)) { if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) {
pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", state.battery.headset, pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", state.battery.headset,
Boolean(state.battery.headsetCharging)); Boolean(state.battery.headsetCharging));
+4 -2
View File
@@ -304,7 +304,9 @@ class Shell {
private lastInputAtMs = Date.now(); private lastInputAtMs = Date.now();
/** The most recent input event received, for windows gaining focus (see ShellWindow.onFocus). */ /** The most recent input event received, for windows gaining focus (see ShellWindow.onFocus). */
private lastInput: InputEvent | null = null; 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<string, boolean>(); private attention = new Map<string, boolean>();
// App-provided top-bar tray icons, keyed by owner id; drawn between the // App-provided top-bar tray icons, keyed by owner id; drawn between the
// notification icons and the battery indicators. // notification icons and the battery indicators.
@@ -495,7 +497,7 @@ class Shell {
return this.screenOn; 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"] { getBatteryLevels(): ShellChromeState["battery"] {
return this.battery; return this.battery;
} }
+10 -4
View File
@@ -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 `faceclaw_phone`, the watch `faceclaw_watch`. Each side finds the other with
`CapabilityClient.getCapability(…, FILTER_REACHABLE)`. `CapabilityClient.getCapability(…, FILTER_REACHABLE)`.
Every watch → phone message carries `seq` (monotonic per watch process) and is Every watch → phone message except `/faceclaw/battery` carries `seq`
answered on `/faceclaw/ack`. (monotonic per watch process) and is answered on `/faceclaw/ack`.
## Watch → phone (MessageClient) ## 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/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/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/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 All of the above except `state/request` and `battery` are refused with
phone's "Watch remote control" setting is off. `ok:false` when the phone's "Watch remote control" setting is off.
## Phone → watch ## 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 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". 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): `/faceclaw/event` (MessageClient, to every reachable watch):
- `{type:"assistant", phase, text}` — `phase` ∈ `thinking`, `streaming` (text so - `{type:"assistant", phase, text}` — `phase` ∈ `thinking`, `streaming` (text so
far, replace semantics, ≤ 4/s), `done` (final text), `error` (message), far, replace semantics, ≤ 4/s), `done` (final text), `error` (message),
+11
View File
@@ -33,5 +33,16 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Answers the phone's battery polls (/faceclaw/battery/request) so
the glasses can show the watch battery while this app is closed. -->
<service
android:name=".PhoneListenerService"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/faceclaw/battery" />
</intent-filter>
</service>
</application> </application>
</manifest> </manifest>
@@ -1,8 +1,12 @@
package com.faceclaw.wear package com.faceclaw.wear
import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri import android.net.Uri
import android.util.Log import android.util.Log
import androidx.core.content.ContextCompat
import com.google.android.gms.common.api.ApiException import com.google.android.gms.common.api.ApiException
import com.google.android.gms.wearable.CapabilityClient import com.google.android.gms.wearable.CapabilityClient
import com.google.android.gms.wearable.CapabilityInfo import com.google.android.gms.wearable.CapabilityInfo
@@ -83,6 +87,15 @@ class PhoneLink(context: Context) :
private val pendingAcks = ConcurrentHashMap<Long, Job>() private val pendingAcks = ConcurrentHashMap<Long, Job>()
private var noticeJob: Job? = null private var noticeJob: Job? = null
private var started = false 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<PhoneState?>(null) private val _state = MutableStateFlow<PhoneState?>(null)
val state: StateFlow<PhoneState?> = _state.asStateFlow() val state: StateFlow<PhoneState?> = _state.asStateFlow()
@@ -105,12 +118,28 @@ class PhoneLink(context: Context) :
messageClient.addListener(this) messageClient.addListener(this)
dataClient.addListener(this) dataClient.addListener(this)
capabilityClient.addListener(this, Protocol.CAPABILITY_PHONE) 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() refresh()
} }
fun stop() { fun stop() {
if (!started) return if (!started) return
started = false started = false
try {
appContext.unregisterReceiver(batteryReceiver)
} catch (error: Exception) {
Log.w(TAG, "battery receiver unregistration failed", error)
}
lastBatteryReported = null
messageClient.removeListener(this) messageClient.removeListener(this)
dataClient.removeListener(this) dataClient.removeListener(this)
capabilityClient.removeListener(this, Protocol.CAPABILITY_PHONE) capabilityClient.removeListener(this, Protocol.CAPABILITY_PHONE)
@@ -121,10 +150,26 @@ class PhoneLink(context: Context) :
scope.launch { scope.launch {
findPhone() findPhone()
loadStateItem() 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 ----------------------------------------------------- // ---- outbound -----------------------------------------------------
fun sendGesture(gesture: Gesture, steps: Int = 1) { fun sendGesture(gesture: Gesture, steps: Int = 1) {
@@ -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"
}
}
@@ -15,6 +15,10 @@ object Protocol {
const val PATH_ASSISTANT = "/faceclaw/assistant" const val PATH_ASSISTANT = "/faceclaw/assistant"
const val PATH_TEXT = "/faceclaw/text" const val PATH_TEXT = "/faceclaw/text"
const val PATH_STATE_REQUEST = "/faceclaw/state/request" 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_ACK = "/faceclaw/ack"
const val PATH_EVENT = "/faceclaw/event" const val PATH_EVENT = "/faceclaw/event"
const val PATH_STATE = "/faceclaw/state" const val PATH_STATE = "/faceclaw/state"
@@ -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)
}
}
}