Implement a bunch of features for alarm reliability

This commit is contained in:
James Babcock committed 2026-09-04 02:24:02 -07:00
1 parent f601a62c75
commit 74199390d2
18 files changed
+2011 -282

No files matched your search

+7 -2
View File
@@ -16,14 +16,19 @@ const timerApp: AppDefinition = {
boot: (ctx) => {
timerEngine.boot({
playBuzzer: (payload) => ctx.actions.playBuzzerSequence(payload),
onRing: () => {
onRing: (item) => {
// Bring the ringing item on screen: focus the Timers window, then
// wake the display if it is off (a setting, since a wearer may
// prefer the phone notification alone while the glasses sleep).
// prefer the phone alone while the glasses sleep). Only once it is
// actually showing does the phone start its acknowledgement clock;
// otherwise the phone adds its own sound within seconds.
void ctx
.launchApp("timer")
.then(() => {
if (timersWakeSetting.get() && !shell.isScreenOn()) shell.wake("window");
if (shell.isScreenOn() && shell.foregroundWindow()?.windowId === TIMER_WINDOW_ID) {
timerEngine.markDeliveredToGlasses(item);
}
})
.catch((error) => console.error(`timers ring launch failed: ${error}`));
},
+16
View File
@@ -36,6 +36,7 @@ import {
drawSelectionHighlight,
drawToggleMenuItem,
scrollToKeepSelectionVisible,
TextPageLayer,
type MenuItem,
} from "../../ui/menu";
import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics";
@@ -820,6 +821,19 @@ export class TimersLayer implements Layer {
drawRightValueMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, timersSnoozeSetting.displayValue()),
},
toggle("12-hour clock", () => twelveHour(), (value) => timeFormatSetting.set(value ? "12h" : "24h")),
{
label: "Phone alarm check",
onSelect: (ctx) => {
timerEngine.refreshReliability(true);
const issues = timerEngine.phoneReliabilityIssues();
const body =
issues.length === 0
? "No problems found: the phone can ring for alarms when the glasses cannot."
: issues.map((issue) => `- ${issue.message}`).join("\n") +
"\n\nFix these from the warning triangle on the phone's home screen.";
ctx.stack.push(new TextPageLayer("Phone alarm check", body));
},
},
];
}
@@ -1047,6 +1061,8 @@ export class TimersLayer implements Layer {
status = next === null ? "Off" : `Rings in ${formatSpanWords(next - now)}`;
}
block.line(image, status, 150);
const warning = timerEngine.phoneReliabilityIssues()[0];
if (alarm.enabled && warning) block.line(image, `Phone: ${warning.message}`, 120);
block.hints(image, [[GESTURE_CLICK, alarm.enabled ? "turn off" : "turn on"], [GESTURE_SHORT_THEN_LONG_PRESS, "edit"]]);
}
+158 -23
View File
@@ -1,26 +1,39 @@
/**
* The Timers app's clock engine: a main-thread singleton that owns the
* timers / stopwatch / alarms state, persists it, schedules the durable
* Android alarms behind every expiry, rings the glasses buzzer, and tells
* phone alarms behind every expiry, rings the glasses buzzer, and tells
* listeners (the window, the tray icon, the assistant tools) when anything
* changes. It is booted at shell start, so everything here works with the
* window closed; the window is only a view on it.
*
* Two expiry paths run side by side, as before: a JS deadline for prompt
* on-glasses ringing while the process is awake, and an AlarmManager alarm
* (see FaceclawTimerNotifications.java) that posts the phone notification
* at the right moment even if the process is asleep or dead. The Java side
* deduplicates the two.
* Two expiry paths run side by side: a JS deadline for prompt on-glasses
* ringing while the process is awake, and an AlarmManager alarm-clock alarm
* (FaceclawAlarms.java) that rings on the phone at the right moment even if
* the process is asleep or dead. The phone shows the item silently first
* and adds its own sound when the glasses cannot carry it (not connected,
* not worn, charging, not shown within seconds, or not acknowledged within
* 30 s); this engine keeps the phone told about the glasses, reports
* delivery and acknowledgement, and replays what the wearer did on the
* phone (dismiss / snooze) into its own state.
*/
import { ConfigSettingBoolean, ConfigSettingEnum } from "../../ui/dashboard-settings";
import { ConfigSettingBoolean, ConfigSettingEnum, timeFormatSetting } from "../../ui/dashboard-settings";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import {
cancelTimerNotification,
fireTimerNotification,
scheduleTimerNotification,
} from "../../native/timer-notifications";
acknowledgePhoneAlarm,
cancelPhoneAlarm,
checkPhoneAlarmReliability,
drainPhoneAlarmJournal,
onPhoneAlarmAction,
openPhoneAlarmReliabilityFix,
phoneAlarmDeliveredToGlasses,
ringPhoneAlarm,
schedulePhoneAlarm,
setPhoneAlarmGlassesStatus,
type AlarmReliabilityIssue,
type PhoneAlarmAction,
} from "../../native/alarms";
import { getGlassesPresence, glassesCanCarryAlert, onGlassesPresenceChanged } from "../../g2/glasses-presence";
import { buildSoundSequencePayload, findSoundEffect, effectPhrases } from "../../ui/sound-effects";
import { timeFormatSetting } from "../../ui/dashboard-settings";
import {
alarmNextRingMs,
createAlarm,
@@ -55,6 +68,10 @@ const RING_MAX_MS = 2 * 60_000;
* delayed by Doze or a clock jump can't leave a due item unnoticed for long.
*/
const MAX_ARM_MS = 30_000;
/** How often the phone is reminded of the glasses' status (it distrusts stale reports). */
const GLASSES_STATUS_HEARTBEAT_MS = 60_000;
/** How often the phone-side reliability self-check reruns while something is armed. */
const RELIABILITY_CHECK_MS = 5 * 60_000;
export const timersSoundSetting = new ConfigSettingBoolean({
id: "timersSound",
@@ -100,6 +117,8 @@ export class TimerEngine {
private deadlineTimer: ReturnType<typeof setTimeout> | null = null;
private ringTimer: ReturnType<typeof setInterval> | null = null;
private booted = false;
private reliabilityIssues: AlarmReliabilityIssue[] = [];
private reliabilityCheckedAtMs = 0;
constructor(private readonly now: () => number = () => Date.now()) {
this.state = emptyTimersState();
@@ -118,12 +137,117 @@ export class TimerEngine {
// Loaded here rather than at module evaluation, so the settings store is
// certainly up before the first read.
this.state = parseTimersState(getStringSetting(STATE_KEY, ""));
// What the wearer did on the phone while this side was down comes first,
// so a dismissed alarm is not rung again by the check below.
for (const action of drainPhoneAlarmJournal()) this.applyPhoneAction(action);
onPhoneAlarmAction((action) => {
this.applyPhoneAction(action);
this.commit();
});
this.pushGlassesStatus();
onGlassesPresenceChanged(() => this.pushGlassesStatus());
setInterval(() => this.pushGlassesStatus(), GLASSES_STATUS_HEARTBEAT_MS);
this.check();
for (const timer of this.state.timers) {
if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
}
for (const alarm of this.state.alarms) this.schedulePhoneAlarm(alarm);
this.save();
this.refreshReliability(true);
setInterval(() => this.refreshReliability(false), RELIABILITY_CHECK_MS);
}
/**
* The glasses are showing a ringing item (the window is up and the screen
* on). The phone's 30-second acknowledgement clock starts from here; without
* this, the phone adds its sound within seconds.
*/
markDeliveredToGlasses(item: RingingItem): void {
if (!glassesCanCarryAlert()) return;
phoneAlarmDeliveredToGlasses(item.kind === "timer" ? item.timer.id : item.alarm.id);
}
private pushGlassesStatus(): void {
const presence = getGlassesPresence();
setPhoneAlarmGlassesStatus(presence.connected, presence.worn === true, presence.charging);
}
/**
* Replay a phone-side dismiss or snooze. The item may be ringing here too,
* may not have been noticed yet (the phone rang it while this side slept),
* or may already be gone; each case lands on the same end state.
*/
private applyPhoneAction(action: PhoneAlarmAction): void {
const at = action.atMs || this.now();
const timer = this.findTimer(action.id);
if (timer) {
if (action.action === "dismiss") {
this.state.timers = this.state.timers.filter((candidate) => candidate.id !== timer.id);
} else {
const extra = Math.max(1, action.minutes) * 60_000;
timer.rungAtMs = null;
timer.pausedRemainingMs = null;
timer.durationMs = extra;
timer.endsAtMs = at + extra;
}
return;
}
const alarm = this.findAlarm(action.id);
if (!alarm) return;
alarm.ringingSinceMs = null;
alarm.lastFiredAtMs = Math.max(alarm.lastFiredAtMs ?? 0, at);
if (action.action === "dismiss") {
alarm.snoozedUntilMs = null;
if (alarm.days === 0) alarm.enabled = false;
} else {
alarm.snoozedUntilMs = at + Math.max(1, action.minutes) * 60_000;
}
}
// -------------------------------------------------------------------------
// Phone reliability
/** Conditions under which the phone may fail to ring, most serious first (cached). */
phoneReliabilityIssues(): AlarmReliabilityIssue[] {
return this.reliabilityIssues;
}
/**
* One-line warning for the UI, or "" when nothing is armed that could
* suffer (no enabled alarm, no running timer) or nothing is wrong.
*/
phoneReliabilityMessage(): string {
if (this.reliabilityIssues.length === 0) return "";
const armed =
this.state.alarms.some((alarm) => alarm.enabled) ||
this.state.timers.some((timer) => timer.endsAtMs !== null && timer.rungAtMs === null);
if (!armed) return "";
return `The phone may not ring for alarms: ${this.reliabilityIssues[0]!.message}`;
}
/** Open the system screen for the most serious fixable issue, if any. */
openPhoneReliabilityFix(): void {
const issue = this.reliabilityIssues.find((candidate) => candidate.fixable);
if (issue) openPhoneAlarmReliabilityFix(issue.code);
}
/** Re-run the phone self-check (rate-limited unless forced) and notify on change. */
refreshReliability(force: boolean): void {
const now = this.now();
if (!force && now - this.reliabilityCheckedAtMs < 30_000) return;
this.reliabilityCheckedAtMs = now;
let issues: AlarmReliabilityIssue[];
try {
issues = checkPhoneAlarmReliability();
} catch (error) {
console.warn(`alarm reliability check failed: ${error}`);
return;
}
const changed =
issues.length !== this.reliabilityIssues.length ||
issues.some((issue, index) => issue.code !== this.reliabilityIssues[index]?.code);
this.reliabilityIssues = issues;
if (changed) this.notify();
}
onChange(listener: () => void): () => void {
@@ -174,7 +298,7 @@ export class TimerEngine {
if (!timer || timer.endsAtMs === null || timer.rungAtMs !== null) return;
timer.pausedRemainingMs = Math.max(0, timer.endsAtMs - this.now());
timer.endsAtMs = null;
cancelTimerNotification(timer.id);
cancelPhoneAlarm(timer.id);
this.commit();
}
@@ -195,7 +319,7 @@ export class TimerEngine {
timer.rungAtMs = null;
timer.durationMs = deltaMs;
timer.endsAtMs = this.now() + deltaMs;
cancelTimerNotification(timer.id);
cancelPhoneAlarm(timer.id);
this.schedulePhoneNotification(timer);
} else if (timer.pausedRemainingMs !== null) {
timer.pausedRemainingMs += deltaMs;
@@ -215,7 +339,7 @@ export class TimerEngine {
timer.rungAtMs = null;
timer.pausedRemainingMs = null;
timer.endsAtMs = this.now() + timer.durationMs;
cancelTimerNotification(timer.id);
cancelPhoneAlarm(timer.id);
this.schedulePhoneNotification(timer);
this.commit();
}
@@ -232,7 +356,7 @@ export class TimerEngine {
removeTimer(id: number): void {
const index = this.state.timers.findIndex((timer) => timer.id === id);
if (index < 0) return;
cancelTimerNotification(id);
acknowledgePhoneAlarm(id);
this.state.timers.splice(index, 1);
this.commit();
}
@@ -330,7 +454,7 @@ export class TimerEngine {
deleteAlarm(id: number): void {
const index = this.state.alarms.findIndex((alarm) => alarm.id === id);
if (index < 0) return;
cancelTimerNotification(id);
cancelPhoneAlarm(id);
this.state.alarms.splice(index, 1);
this.commit();
}
@@ -340,6 +464,7 @@ export class TimerEngine {
if (!alarm || alarm.ringingSinceMs === null) return;
alarm.ringingSinceMs = null;
alarm.snoozedUntilMs = this.now() + minutes * 60_000;
acknowledgePhoneAlarm(alarm.id);
this.schedulePhoneAlarm(alarm);
this.commit();
}
@@ -351,6 +476,7 @@ export class TimerEngine {
alarm.ringingSinceMs = null;
alarm.snoozedUntilMs = null;
if (alarm.days === 0) alarm.enabled = false;
acknowledgePhoneAlarm(alarm.id);
this.schedulePhoneAlarm(alarm);
this.commit();
}
@@ -381,9 +507,13 @@ export class TimerEngine {
timer.rungAtMs = timer.endsAtMs;
timer.endsAtMs = null;
changed = true;
// Late (found due after a restart): the phone rang or missed it on
// its own schedule; only a fresh expiry starts the phone flow here.
const late = now - timer.rungAtMs > RING_GRACE_MS;
fireTimerNotification(timer.id, "Timer finished", timerNotificationText(timer));
if (!late) this.startRinging({ kind: "timer", timer });
if (!late) {
ringPhoneAlarm(timer.id, "Timer finished", timerNotificationText(timer), "timer", snoozeMinutes());
this.startRinging({ kind: "timer", timer });
}
}
for (const alarm of this.state.alarms) {
if (alarm.ringingSinceMs !== null) continue;
@@ -394,13 +524,13 @@ export class TimerEngine {
alarm.lastFiredAtMs = due;
changed = true;
const late = now - due > RING_GRACE_MS;
fireTimerNotification(alarm.id, "Alarm", alarmNotificationText(alarm));
if (late) {
// Missed by too much to ring now: fall through to the next occurrence.
alarm.ringingSinceMs = null;
if (alarm.days === 0) alarm.enabled = false;
this.schedulePhoneAlarm(alarm);
} else {
ringPhoneAlarm(alarm.id, "Alarm", alarmNotificationText(alarm), "alarm", snoozeMinutes());
this.startRinging({ kind: "alarm", alarm });
}
}
@@ -492,17 +622,17 @@ export class TimerEngine {
private schedulePhoneNotification(timer: CountdownTimer): void {
if (timer.endsAtMs === null) return;
scheduleTimerNotification(timer.id, timer.endsAtMs, "Timer finished", timerNotificationText(timer));
schedulePhoneAlarm(timer.id, timer.endsAtMs, "Timer finished", timerNotificationText(timer), "timer", snoozeMinutes());
}
/** (Re)arm or cancel the phone alarm for an alarm's next occurrence. */
private schedulePhoneAlarm(alarm: Alarm): void {
const due = alarm.ringingSinceMs === null ? this.alarmDueMs(alarm, this.now()) : null;
if (due === null) {
cancelTimerNotification(alarm.id);
cancelPhoneAlarm(alarm.id);
return;
}
scheduleTimerNotification(alarm.id, due, "Alarm", alarmNotificationText(alarm));
schedulePhoneAlarm(alarm.id, due, "Alarm", alarmNotificationText(alarm), "alarm", snoozeMinutes());
}
// -------------------------------------------------------------------------
@@ -512,6 +642,7 @@ export class TimerEngine {
this.save();
this.check();
this.notify();
if (this.booted) this.refreshReliability(false);
}
private save(): void {
@@ -533,6 +664,10 @@ export class TimerEngine {
}
}
function snoozeMinutes(): number {
return Number(timersSnoozeSetting.get()) || 10;
}
function timerNotificationText(timer: CountdownTimer): string {
const duration = formatDurationWords(timer.durationMs);
return timer.label ? `${timer.label} (${duration}) is up` : `${duration} timer is up`;
+41
View File
@@ -52,6 +52,8 @@ import { getDefaultMediumFont } from "../graphics/ui-fonts";
import { wrapText } from "../graphics/textwrap";
import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell";
import { registerSystemTools } from "../assistant/system-tools";
import { updateGlassesPresence } from "./glasses-presence";
import { timerEngine } from "../apps/timer/timer-engine";
import { registerNavigateTools } from "../assistant/navigate-tools";
import { registerRoamTools } from "../assistant/roam-tools";
import { assistantBridge } from "../assistant/bridge-client";
@@ -116,6 +118,8 @@ export type DashboardSnapshot = {
screenRecordingActive: boolean;
batteryOptimizationWarningVisible: boolean;
fontsMissingWarningVisible: boolean;
/** Why the phone may fail to ring for a set alarm; "" when nothing is wrong or armed. */
alarmReliabilityMessage: string;
/**
* True while the headless preview display is standing in for a glasses
* connection (preview-only mode): the mirror is live and interactive, but
@@ -219,6 +223,7 @@ class DashboardController {
private firmwareWarningMessage = "";
private batteryOptimizationWarningVisible = false;
private fontsMissingWarningVisible = false;
private alarmReliabilityMessage = "";
// Sticky positive: the extracted-font file doesn't vanish mid-session, so a
// successful check spares later refreshes the file read and JSON parse.
private extractedFontsConfirmed = false;
@@ -361,6 +366,7 @@ class DashboardController {
for (const app of ALL_APPS) {
app.boot?.(this.buildAppContext(app));
}
timerEngine.onChange(() => this.refreshAlarmReliabilityWarning());
this.offAndroidNotification = onAndroidNotificationPosted((notificationKey) => {
void this.handleAndroidNotificationPosted(notificationKey).catch((error) => {
this.appendLog(`notification wake failed: ${this.formatError(error)}`);
@@ -562,6 +568,7 @@ class DashboardController {
private handleWearState(wearing: boolean): void {
this.glassesWorn = wearing;
updateGlassesPresence({ worn: wearing });
this.appendLog(wearing ? "glasses wear state: ON_HEAD" : "glasses wear state: OFF_HEAD");
this.wearRemote?.schedulePublish();
if (!wearing && this.phoneLocked && lockScreenEnabledSetting.get()) {
@@ -930,6 +937,7 @@ class DashboardController {
screenRecordingActive: this.screenRecordingActive,
batteryOptimizationWarningVisible: this.batteryOptimizationWarningVisible,
fontsMissingWarningVisible: this.fontsMissingWarningVisible,
alarmReliabilityMessage: this.alarmReliabilityMessage,
previewMode: this.isPreviewDisplayActive(),
};
}
@@ -1021,9 +1029,35 @@ class DashboardController {
}
}
/**
* Mirror the Timers engine's phone self-check into the warnings modal. The
* engine re-checks on its own schedule and on every timer/alarm change;
* a page load forces a fresh check so a just-fixed setting clears at once.
*/
refreshAlarmReliabilityWarning(force = false): void {
if (force) timerEngine.refreshReliability(true);
const message = timerEngine.phoneReliabilityMessage();
if (message !== this.alarmReliabilityMessage) {
this.alarmReliabilityMessage = message;
this.emit();
}
}
openAlarmReliabilityFix(): void {
timerEngine.openPhoneReliabilityFix();
// The system screen is asynchronous with no result; poll briefly so the
// warning clears once the setting is changed.
let checksLeft = 12;
const poll = setInterval(() => {
this.refreshAlarmReliabilityWarning(true);
if (!this.alarmReliabilityMessage || --checksLeft <= 0) clearInterval(poll);
}, 5_000);
}
refreshEvenAppStatus(): void {
this.refreshBatteryOptimizationStatus();
this.refreshEvenHubFontStatus();
this.refreshAlarmReliabilityWarning(true);
const state = readEvenAppNotificationState();
const wasActive = this.evenNotificationActive;
this.evenNotificationActive = state.evenNotificationActive;
@@ -1288,6 +1322,7 @@ class DashboardController {
// the transport comes back, so do not make lock decisions from a
// stale pre-disconnect value in the meantime.
this.glassesWorn = null;
updateGlassesPresence({ worn: null });
// The mic enable was session-scoped too: park any live capture so
// the next session restarts it, instead of leaving a holder that
// makes every later request think the mic is already running.
@@ -1329,6 +1364,7 @@ class DashboardController {
headset: hasBatteryLevel ? state.battery : this.lastHeadsetBattery,
headsetCharging: state.chargingStatus > 0,
});
updateGlassesPresence({ charging: state.chargingStatus > 0 || this.phase === "charging" });
if ((this.phase === "connected" || this.phase === "charging") && this.communicator) {
// Repaint the top bar (battery indicators live in the shell chrome).
this.requestShellRender();
@@ -2453,6 +2489,11 @@ class DashboardController {
private setPhase(phase: ConnectionPhase): void {
if (this.phase === phase) return;
this.phase = phase;
// "charging" is a live BLE link with the glasses in their case.
updateGlassesPresence({
connected: phase === "connected" || phase === "charging",
charging: phase === "charging" || (shell.getBatteryLevels().headsetCharging ?? false),
});
if (phase === "disconnected") {
// Kept across "connecting": silent mode blocks app launches, so it can
// itself cause the reconnect churn, and Java re-reports it either way.
+46
View File
@@ -0,0 +1,46 @@
/**
* Whether the glasses could carry an alert right now: connected over BLE, on
* a head, and not charging. Fed by the dashboard controller from the
* transport's phase, wear-state and battery reports; consumed by the Timers
* engine, which mirrors it to the phone's alarm clock so the phone knows
* when to add its own sound.
*/
export type GlassesPresence = {
connected: boolean;
/** null until the firmware has reported a wear state this session. */
worn: boolean | null;
charging: boolean;
};
let presence: GlassesPresence = { connected: false, worn: null, charging: false };
const listeners = new Set<(presence: GlassesPresence) => void>();
export function getGlassesPresence(): GlassesPresence {
return presence;
}
/** True when a fresh, positive report says the glasses are worn and usable. */
export function glassesCanCarryAlert(current: GlassesPresence = presence): boolean {
return current.connected && current.worn === true && !current.charging;
}
export function updateGlassesPresence(patch: Partial<GlassesPresence>): void {
const next = { ...presence, ...patch };
if (next.connected === presence.connected && next.worn === presence.worn && next.charging === presence.charging) return;
presence = next;
for (const listener of Array.from(listeners)) {
try {
listener(presence);
} catch (error) {
console.warn(`glasses presence listener failed: ${error}`);
}
}
}
export function onGlassesPresenceChanged(listener: (presence: GlassesPresence) => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
+154
View File
@@ -0,0 +1,154 @@
import { Utils } from "@nativescript/core";
declare const com: any;
/**
* Bridge to the Java alarm clock (FaceclawAlarms / FaceclawAlarmService):
* the durable phone side of the Timers app's timers and alarms. The phone
* schedules an exact alarm-clock alarm per item, re-arms them after reboots
* and time changes, and when one comes due shows it on the phone (silently
* at first) and adds phone sound if the glasses cannot carry it. Ids are the
* engine's item ids.
*/
export type AlarmKind = "timer" | "alarm";
export type PhoneAlarmAction = { id: number; action: "dismiss" | "snooze"; minutes: number; atMs: number };
export type AlarmReliabilityIssue = { code: string; message: string; fixable: boolean };
function getContext(): android.content.Context | null {
if (!global.isAndroid) return null;
return Utils.android.getApplicationContext() ?? null;
}
/** Schedule (or move) the phone alarm that rings `title` / `text` at triggerAtMs. */
export function schedulePhoneAlarm(
itemId: number,
triggerAtMs: number,
title: string,
text: string,
kind: AlarmKind,
snoozeMinutes: number,
): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.schedule(context, itemId, triggerAtMs, title, text, kind, snoozeMinutes);
}
/** Cancel the pending phone alarm, stop it if ringing, and clear its notification. */
export function cancelPhoneAlarm(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.cancel(context, itemId);
}
/** The engine's own expiry path: start the phone ringing flow (deduplicated against the alarm's). */
export function ringPhoneAlarm(itemId: number, title: string, text: string, kind: AlarmKind, snoozeMinutes: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.ring(context, itemId, title, text, kind, snoozeMinutes);
}
/** The glasses are showing the item: the phone starts its 30-second acknowledgement clock. */
export function phoneAlarmDeliveredToGlasses(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.deliveredToGlasses(context, itemId);
}
/** The wearer dealt with the item on the glasses: the phone goes quiet. */
export function acknowledgePhoneAlarm(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.acknowledge(context, itemId);
}
/** Tell the phone whether the glasses could carry an alarm right now. */
export function setPhoneAlarmGlassesStatus(connected: boolean, worn: boolean, charging: boolean): void {
if (!global.isAndroid) return;
com.faceclaw.app.FaceclawAlarms.setGlassesStatus(connected, worn, charging);
}
let retainedListenerProxy: any = null;
const actionListeners = new Set<(action: PhoneAlarmAction) => void>();
/** Live phone-side dismiss / snooze events (journaled ones arrive through drainPhoneAlarmJournal). */
export function onPhoneAlarmAction(listener: (action: PhoneAlarmAction) => void): () => void {
if (retainedListenerProxy === null && global.isAndroid) {
retainedListenerProxy = new com.faceclaw.app.FaceclawAlarmListener({
onPhoneAction: (id: number, action: string, minutes: number) => {
const event: PhoneAlarmAction = {
id: Number(id),
action: String(action) === "snooze" ? "snooze" : "dismiss",
minutes: Number(minutes),
atMs: Date.now(),
};
for (const registered of Array.from(actionListeners)) {
try {
registered(event);
} catch (error) {
console.warn(`phone alarm action listener failed: ${error}`);
}
}
},
});
com.faceclaw.app.FaceclawAlarms.setListener(retainedListenerProxy);
}
actionListeners.add(listener);
return () => {
actionListeners.delete(listener);
};
}
/** Phone-side actions taken while the engine was not listening, oldest first; cleared on read. */
export function drainPhoneAlarmJournal(): PhoneAlarmAction[] {
const context = getContext();
if (!context) return [];
let parsed: any;
try {
parsed = JSON.parse(String(com.faceclaw.app.FaceclawAlarms.drainJournal(context)));
} catch {
return [];
}
if (!Array.isArray(parsed)) return [];
return parsed
.filter((entry) => entry && typeof entry === "object" && Number.isFinite(Number(entry.id)))
.map((entry) => ({
id: Number(entry.id),
action: entry.action === "snooze" ? "snooze" : "dismiss",
minutes: Number(entry.minutes) || 0,
atMs: Number(entry.at) || 0,
}));
}
/** Conditions under which the phone may fail to ring, most serious first. */
export function checkPhoneAlarmReliability(): AlarmReliabilityIssue[] {
const context = getContext();
if (!context) return [];
let parsed: any;
try {
parsed = JSON.parse(String(com.faceclaw.app.FaceclawAlarms.checkReliability(context)));
} catch (error) {
console.warn(`alarm reliability check failed: ${error}`);
return [];
}
if (!Array.isArray(parsed)) return [];
return parsed
.filter((entry) => entry && typeof entry === "object" && typeof entry.code === "string")
.map((entry) => ({ code: entry.code, message: String(entry.message ?? ""), fixable: entry.fixable !== false }));
}
/** Open the system screen where a reliability issue can be fixed. */
export function openPhoneAlarmReliabilityFix(code: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.openReliabilityFix(context, code);
}
/** The phone's ring / miss / action log, one line per entry, newest last. */
export function readPhoneAlarmLog(): string {
const context = getContext();
if (!context) return "";
return String(com.faceclaw.app.FaceclawAlarms.readLog(context));
}
-36
View File
@@ -1,36 +0,0 @@
import { Utils } from "@nativescript/core";
declare const com: any;
/**
* Bridge to FaceclawTimerNotifications.java: the durable Android alarm and
* phone notification behind every Timers-app expiry (countdown timers and
* alarms alike, keyed by the item's id). The phone posts the notification at
* `triggerAtMs` even if the app process is asleep or gone.
*/
function getContext(): android.content.Context | null {
if (!global.isAndroid) return null;
return Utils.android.getApplicationContext() ?? null;
}
/** Schedule (or move) the Android alarm that posts `title` / `text` at triggerAtMs. */
export function scheduleTimerNotification(itemId: number, triggerAtMs: number, title: string, text: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.schedule(context, itemId, triggerAtMs, title, text);
}
/** Cancel both a pending alarm and any already-posted notification. */
export function cancelTimerNotification(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.cancel(context, itemId);
}
/** The engine's own expiry path; Java deduplicates it against the alarm's. */
export function fireTimerNotification(itemId: number, title: string, text: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.fireNow(context, itemId, title, text);
}
+4
View File
@@ -96,6 +96,10 @@
<Label text="The G2 fonts have not been extracted, so EvenHub apps will render with fallback fonts. Preparing them downloads the official firmware to extract its fonts; your glasses are not reflashed." textWrap="true" />
<Button text="Prepare G2 fonts" tap="{{ onPrepareFontsTap }}" class="-primary" />
</StackLayout>
<StackLayout visibility="{{ alarmReliabilityWarningVisibility }}" class="warnings-modal-item">
<Label text="{{ alarmReliabilityMessage }}" textWrap="true" />
<Button text="Open phone settings" tap="{{ onFixAlarmReliabilityTap }}" class="-primary" />
</StackLayout>
<Button text="Close" tap="{{ onWarningsModalCloseTap }}" />
</StackLayout>
</ScrollView>
+26 -1
View File
@@ -66,6 +66,7 @@ export class MainViewModel extends Observable {
private _screenRecordingActive = false;
private _batteryOptimizationWarningVisible = false;
private _fontsMissingWarningVisible = false;
private _alarmReliabilityMessage = "";
private _warningsModalVisible = false;
private _previewMode = false;
private _phase: "disconnected" | "connecting" | "connected" | "charging" | "disconnecting" = "disconnected";
@@ -116,6 +117,7 @@ export class MainViewModel extends Observable {
this.screenRecordingActive = snapshot.screenRecordingActive;
this.batteryOptimizationWarningVisible = snapshot.batteryOptimizationWarningVisible;
this.fontsMissingWarningVisible = snapshot.fontsMissingWarningVisible;
this.alarmReliabilityMessage = snapshot.alarmReliabilityMessage;
this.refreshPadFocusLine();
}));
// Brightness / display mode can change from the glasses' Settings app too.
@@ -721,6 +723,28 @@ export class MainViewModel extends Observable {
dashboardController.requestBatteryOptimizationExemption();
}
get alarmReliabilityMessage(): string {
return this._alarmReliabilityMessage;
}
set alarmReliabilityMessage(value: string) {
if (this._alarmReliabilityMessage !== value) {
this._alarmReliabilityMessage = value;
this.notifyPropertyChange("alarmReliabilityMessage", value);
this.notifyPropertyChange("alarmReliabilityWarningVisibility", this.alarmReliabilityWarningVisibility);
this.refreshWarningIndicator();
}
}
get alarmReliabilityWarningVisibility(): "visible" | "collapse" {
return this._alarmReliabilityMessage ? "visible" : "collapse";
}
onFixAlarmReliabilityTap(): void {
this.setWarningsModalVisible(false);
dashboardController.openAlarmReliabilityFix();
}
// ---- the action bar's warning triangle and the modal behind it ----
get anyWarningVisible(): boolean {
@@ -728,7 +752,8 @@ export class MainViewModel extends Observable {
this._evenAppConflictWarningVisible ||
this._firmwareWarningVisible ||
this._batteryOptimizationWarningVisible ||
this._fontsMissingWarningVisible
this._fontsMissingWarningVisible ||
this._alarmReliabilityMessage.length > 0
);
}