diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt index 29813c9b..df92ac5f 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.kt @@ -265,8 +265,11 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre /** See [GlassesSessionCore.getRingStatus]. */ fun getRingStatus(): String = core.getRingStatus() - fun setHeadUpTrigger(degrees: Int) = core.setHeadUpTrigger(degrees) + /** See [GlassesSessionCore.setHeadUpTrigger]. */ + fun setHeadUpTrigger(degrees: Int, originalSwitch: Int, originalAngle: Int) = + core.setHeadUpTrigger(degrees, originalSwitch, originalAngle) + /** See [GlassesSessionCore.getHeadUpStatus]. */ fun getHeadUpStatus(): String = core.getHeadUpStatus() /** See [GlassesSessionCore.setGlassesRingLink]. */ diff --git a/app/apps/app-definition.ts b/app/apps/app-definition.ts index b46c809d..869cb374 100644 --- a/app/apps/app-definition.ts +++ b/app/apps/app-definition.ts @@ -48,7 +48,7 @@ export type GlanceboardProvider = { isEnabled: () => boolean; /** Whether a single tap shows the board (for tapTimeoutMs). */ showOnTap: () => boolean; - /** How long a tap or head-tilt keeps the board up. */ + /** How long a tap keeps the board up (and a head-tilt, when its head-down is unlikely to come). */ tapTimeoutMs: () => number; /** Whether a long-press holds the board up until released. */ showOnLongPress: () => boolean; diff --git a/app/apps/glanceboard/glanceboard-app.ts b/app/apps/glanceboard/glanceboard-app.ts index 1346b724..cecb75f3 100644 --- a/app/apps/glanceboard/glanceboard-app.ts +++ b/app/apps/glanceboard/glanceboard-app.ts @@ -6,7 +6,15 @@ import { uiFontOverridePickerMenuItem } from "../../ui/font-picker"; import { type InputEvent } from "../../ui/gestures"; import { type Layer, type LayerContext } from "../../ui/layers"; import { drawRightValueMenuItem, drawSelectionHighlight, isMenuItemDisabled, MenuLayer, openModalMenu, submenuItem, type MenuItem } from "../../ui/menu"; -import { applyGlanceAngle, glassesHeadUpTrigger, setGlanceAngleFromHead } from "../../g2/head-angle"; +import { + captureHeadAngleStep, + glassesHeadUpTrigger, + headAngleCaptureRunning, + headAngleCaptureStep, + resetHeadAngleCapture, + syncGlanceAngleOriginal, +} from "../../g2/head-angle"; +import { getHeadUpStatus, headUpControlsAvailable } from "../../native/glasses-controls"; import { Menu } from "../../ui/menu-core"; import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics"; import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window"; @@ -314,8 +322,9 @@ function openGlanceSettings(ctx: LayerContext): void { enumSettingMenuItem(glanceTapDurationSetting), toggleSettingMenuItem(glanceShowOnLongPressSetting), toggleSettingMenuItem(glanceShowOnHeadTiltSetting), - enumSettingMenuItem(glanceAngleSetting, { onChange: () => { applyGlanceAngle(); } }), - headAngleCaptureMenuItem(), + // Only Android can change the glasses' head-up setting (glasses-controls.ts). + // The controller's settings listener sends a new angle to the glasses. + ...(headUpControlsAvailable() ? [enumSettingMenuItem(glanceAngleSetting), headAngleCaptureMenuItem()] : []), toggleSettingMenuItem(glanceShowLinesSetting), uiFontOverridePickerMenuItem(glanceFont, { title: "Glanceboard font", @@ -325,32 +334,51 @@ function openGlanceSettings(ctx: LayerContext): void { enumSettingMenuItem(glanceDepthSetting), ...widgetSettingsMenuItems(), ]; + resetHeadAngleCapture(); + headAngleCapture = null; const layer = new MenuLayer("Glanceboard settings", items(), pageMenuLayout(ctx.stack.getBaseSize().width)); ctx.stack.push(layer); } /** - * "Set to current head angle": measure the head's tilt from the glasses' - * accelerometer, round it to the nearest 5°, store it as the Head tilt angle - * and send it to the glasses. The row's value shows the result, or the - * glasses' current trigger before the first use. + * "Set to current head angle", in two selects: one with the head level, one + * tilted up to where the display should wake (head-angle.ts). The row shows + * the step or the last result; otherwise the glasses' current trigger. A + * result is shown only while the Head tilt angle still has the value it was + * shown with, and only until the menu is reopened. */ -let headAngleCaptureStatus = ""; +let headAngleCapture: { status: string; angleSetting: string } | null = null; function headAngleCaptureMenuItem(): MenuItem { const label = "Set to current head angle"; + const setStatus = (status: string) => { + headAngleCapture = { status, angleSetting: glanceAngleSetting.get() }; + }; return { label, description: - "Tilt your head to where the display should wake, keep still, and select. " + - "Faceclaw reads the glasses' angle for about a second, rounds it to the nearest 5°, and saves it as the Head tilt angle.", - onSelect: async () => { - headAngleCaptureStatus = "Measuring..."; - headAngleCaptureStatus = await setGlanceAngleFromHead(); + "Two steps. Look straight ahead, keep still and select; then tilt your head up to where the display should wake, keep still and select again. " + + "Faceclaw reads the glasses' angle for about a second each time and saves the difference, rounded to 5°, as the Head tilt angle. Keep your head level side to side.", + onSelect: async (ctx) => { + // Selects during a measurement are ignored; it would share the IMU stream. + if (headAngleCaptureRunning()) return; + setStatus("Measuring..."); + ctx.actions.requestRender(); + const status = await captureHeadAngleStep(); + if (status !== null) setStatus(status); + ctx.actions.requestRender(); }, render: ({ image, x, y, width }) => { - const current = glassesHeadUpTrigger(); - const value = headAngleCaptureStatus || (current === null ? "" : current === 0 ? "glasses: off" : `glasses: ${current}°`); + const status = getHeadUpStatus(); + syncGlanceAngleOriginal(status); + let value: string; + if (headAngleCapture && headAngleCapture.angleSetting === glanceAngleSetting.get() && + (headAngleCaptureRunning() || headAngleCaptureStep() === "tilt" || !headAngleCapture.status.startsWith("Now"))) { + value = headAngleCapture.status; + } else { + const current = glassesHeadUpTrigger(status); + value = current === null ? "" : current === 0 ? "glasses: off" : `glasses: ${current}°`; + } drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, label, value); }, }; diff --git a/app/apps/glanceboard/glanceboard-settings.ts b/app/apps/glanceboard/glanceboard-settings.ts index 9b2827a7..2584e87e 100644 --- a/app/apps/glanceboard/glanceboard-settings.ts +++ b/app/apps/glanceboard/glanceboard-settings.ts @@ -44,8 +44,9 @@ export function glanceLayout(): GlanceLayout { /** * Whether sleep-time gestures show the board at all. Off restores the plain - * behaviour: a tap, hold or head-tilt while asleep does nothing (a head-tilt - * wakes the regular UI), double-tap wakes. + * behaviour: a tap or hold while asleep does nothing, a head-tilt wakes the + * regular UI, double-tap wakes; and the head-up angle goes back to the glasses' + * own. */ export const glanceboardEnabledSetting = new ConfigSettingBoolean({ id: "glanceboard-enabled", @@ -61,9 +62,10 @@ export type GlanceTapDuration = "off" | "3s" | "5s" | "7s" | "10s"; const DEFAULT_TAP_DURATION: GlanceTapDuration = "5s"; /** - * How long a tap (or head-tilt) keeps the board up; each further tap restarts - * it. "off" means a single tap does not show the board at all; a head-tilt - * then uses the default duration. + * How long a tap keeps the board up; each further tap restarts it. "off" + * means a single tap does not show the board at all. A head-tilt showing + * lasts until the head comes back down, falling back to this duration (the + * default one when "off") where the head-down is unlikely to arrive. */ export const glanceTapDurationSetting = new ConfigSettingEnum({ id: "glanceboard-tap-duration", @@ -96,7 +98,7 @@ export const glanceShowOnLongPressSetting = new ConfigSettingBoolean({ description: "A long-press or short-then-long-press while asleep shows the Glanceboard until the press is released.", }); -/** The head-tilt wake shows the board (for the tap duration) instead of the regular UI. */ +/** The head-tilt wake shows the board (until the head comes back down) instead of the regular UI. */ export const glanceShowOnHeadTiltSetting = new ConfigSettingBoolean({ id: "glanceboard-show-on-head-tilt", label: "Show on head tilt", @@ -110,9 +112,10 @@ export type GlanceAngle = (typeof GLANCE_ANGLE_VALUES)[number]; /** * How far the head must tilt up for a head-tilt wake, as the glasses' own - * pitch reading (degrees). "glasses" leaves whatever the glasses already have - * (set by the Even app or its calibration). A number is written to the - * glasses' head-up setting on every connection (glasses-controls.ts). + * pitch reading (degrees). "glasses" keeps the glasses' own setting (from the + * Even app), writing back their original values if Faceclaw changed them. A + * number is written to the glasses' head-up setting on every connection while + * the Glanceboard is enabled (head-angle.ts). Android only. */ export const glanceAngleSetting = new ConfigSettingEnum({ id: "glanceboard-head-tilt-angle", @@ -122,13 +125,17 @@ export const glanceAngleSetting = new ConfigSettingEnum({ values: GLANCE_ANGLE_VALUES, formatValue: (value) => (value === "glasses" ? "Glasses default" : `${value}°`), description: - "How far you tilt your head up to wake the display. Glasses default keeps the angle already stored on the glasses.", + "How far you tilt your head up to wake the display. Glasses default uses the glasses' own setting from the Even app. " + + "The board hides when your head drops 20° below this angle; under 25°, looking straight ahead may not count, so it hides after the tap duration instead.", }); -/** The trigger in degrees, or 0 when the glasses keep their own. */ -export function glanceAngleDegrees(): number { +/** + * The trigger Faceclaw should maintain, in degrees: the Head tilt angle while + * the Glanceboard is enabled, else 0 (the glasses' own setting). + */ +export function glanceAngleTriggerDegrees(): number { const value = glanceAngleSetting.get(); - return value === "glasses" ? 0 : Number(value); + return value === "glasses" || !glanceboardEnabledSetting.get() ? 0 : Number(value); } const DEPTH_VALUES = ["-64", "-48", "-32", "-16", "0", "16", "32", "48", "64"] as const; diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 80dcc041..d68b41f5 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -20,8 +20,9 @@ import { shouldShowNotificationOnGlasses } from "../native/notification-sources" import { watchNotificationListenerBinding } from "../native/notification-access"; import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict"; import { defaultRingName, setGlassesRingLink } from "../native/ring-status"; -import { applyGlanceAngle } from "./head-angle"; -import { glanceAngleDegrees } from "../apps/glanceboard/glanceboard-settings"; +import { applyGlanceAngle, glassesHeadUpTrigger, syncGlanceAngleOriginal } from "./head-angle"; +import { glanceAngleTriggerDegrees, glanceTapTimeoutMs } from "../apps/glanceboard/glanceboard-settings"; +import { glanceTiltMaxMs } from "./glance-state"; import { getBooleanSetting, setBooleanSetting } from "../native/settings-store"; import { grayImageToPreviewSource } from "../native/gray-image-preview"; import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from "./firmware-compat"; @@ -335,7 +336,7 @@ class DashboardController { private evenHubResumePromise: Promise | null = null; /** Faceclaw's firmware at the required revision reported in; its extensions can be used. */ private customFirmwareConfirmed = false; - private lastGlanceAngleDegrees = glanceAngleDegrees(); + private lastGlanceAngleDegrees = glanceAngleTriggerDegrees(); private faceclawWakeLeaseState: boolean | null = null; /** Ring connection mode the current session was started with (it applies per connection). */ private ringModeAtConnect: RingConnectionMode = "glasses"; @@ -1758,6 +1759,7 @@ class DashboardController { this.requestShellRender(); this.updateCompositePreview(); this.updateConnectedForegroundNotification(); + syncGlanceAngleOriginal(); }, SHELL_REFRESH_INTERVAL_MS); this.previewTimer = setInterval(() => this.updateCompositePreview(), PREVIEW_INTERVAL_MS); this.screenTimeoutTimer = setInterval(() => { @@ -2520,9 +2522,9 @@ class DashboardController { } } - /** Re-send the head-tilt angle when the setting changed (from either settings UI). */ + /** Re-send the head-tilt angle when it changed (the setting, from either settings UI, or the Glanceboard toggle). */ private applyGlanceAngleIfChanged(): void { - const degrees = glanceAngleDegrees(); + const degrees = glanceAngleTriggerDegrees(); if (degrees === this.lastGlanceAngleDegrees) return; this.lastGlanceAngleDegrees = degrees; applyGlanceAngle(); @@ -2531,12 +2533,20 @@ class DashboardController { /** * The Glanceboard event a sleep-time input means, or null when the shell * should see the input as usual. A display-wake carries the head-tilt - * gesture (HEAD_UP_EVENT) as a press; the double-tap display-wake stays the - * regular UI's wake. + * gesture (HEAD_UP_EVENT) as a tilt, which lasts until the head-down; the + * double-tap display-wake stays the regular UI's wake. */ private glanceEventFor(inputEvent: InputEvent, event: RawInputEvent): GlanceEvent | null { if (inputEvent.type === "display-wake") { - return event.eventType === OsEventTypeList.HEAD_UP_EVENT ? this.glance.eventForGesture("head-tilt") : null; + if (event.eventType !== OsEventTypeList.HEAD_UP_EVENT) return null; + const glanceEvent = this.glance.eventForGesture("head-tilt"); + if (glanceEvent?.type !== "tilt") return glanceEvent; + const maxMs = glanceTiltMaxMs({ + resumedSession: this.evenHubSessionSuspended || this.evenHubResumePromise !== null, + triggerDegrees: glassesHeadUpTrigger() ?? (glanceAngleTriggerDegrees() || null), + tapTimeoutMs: glanceTapTimeoutMs(), + }); + return { type: "tilt", maxMs }; } return this.glance.eventForGesture(inputEvent.type); } diff --git a/app/g2/glance-host.ts b/app/g2/glance-host.ts index cf5d05ff..f0349eb0 100644 --- a/app/g2/glance-host.ts +++ b/app/g2/glance-host.ts @@ -82,7 +82,7 @@ export class GlanceHost { * The glance event a sleep-time gesture means under the board's settings, * or null when the shell should see the input as usual: nothing while the * board is disabled, no press from a tap when "Show on tap" is disabled, - * no hold when "Show on long press" is off, no press from a head-tilt when + * no hold when "Show on long press" is off, no tilt from a head-tilt when * "Show on head tilt" is off (it then wakes the regular UI). A release * always passes so a hold in progress can end. */ diff --git a/app/g2/glance-state.ts b/app/g2/glance-state.ts index bd0bdeb8..23e1f9ef 100644 --- a/app/g2/glance-state.ts +++ b/app/g2/glance-state.ts @@ -1,9 +1,10 @@ /** * The Glanceboard's visibility rules, as a pure reducer so they can be tested * without the display plumbing. The board is an alternate sleep-time display: - * while the shell is asleep a press (single tap, or a head-tilt wake) shows it - * for a short while, a hold (long-press or short-then-long-press) shows it until release, - * and a double-tap dismisses it in favour of the regular UI. GlanceHost feeds + * while the shell is asleep a press (single tap) shows it for a short while, a + * head-tilt wake shows it until the head comes back down, a hold (long-press or + * short-then-long-press) shows it until release, and a double-tap dismisses it + * in favour of the regular UI. GlanceHost feeds * these events in and applies the resulting visibility to the compositor. * * No NativeScript imports: this module is compiled and run under plain node @@ -20,15 +21,38 @@ export const GLANCE_TIMEOUT_MS = 3000; */ export const GLANCE_TILT_MAX_MS = 60_000; +/** + * The firmware reports head-down once the pitch falls 20° below the head-up + * trigger (a fixed hysteresis in DRV_IMUCheckHeadUpEvent). Under this trigger, + * looking level again does not get below that, so the head-down may never come. + */ +export const GLANCE_LOW_TILT_TRIGGER_DEGREES = 25; + +/** + * How long a head-tilt showing may last without a head-down. The full cap, + * except when the head-down is unlikely to arrive, where the tap duration is + * used instead: a tilt that woke a suspended EvenHub session (the head-down + * is only forwarded once the page is back, so a quick glance can end before + * that), or a trigger too low for a level gaze to count as looking down. + * triggerDegrees is the glasses' trigger, or null when not known. + */ +export function glanceTiltMaxMs(options: { resumedSession: boolean; triggerDegrees: number | null; tapTimeoutMs: number }): number { + const lowTrigger = + options.triggerDegrees !== null && options.triggerDegrees > 0 && options.triggerDegrees < GLANCE_LOW_TILT_TRIGGER_DEGREES; + return options.resumedSession || lowTrigger ? options.tapTimeoutMs : GLANCE_TILT_MAX_MS; +} + export type GlanceState = { visible: boolean; /** A long-press is holding the board up; the timer does not run meanwhile. */ holding: boolean; /** * A head-tilt is holding the board up: it stays until the firmware reports - * the head back down (or GLANCE_TILT_MAX_MS passes). + * the head back down (or tiltMaxMs passes). */ tilted: boolean; + /** The current head-tilt's cap (0 when not tilted); a hold ending mid-tilt re-arms it. */ + tiltMaxMs: number; /** When the board hides on its own (epoch ms), or null while held / hidden. */ hideAtMs: number | null; }; @@ -36,8 +60,8 @@ export type GlanceState = { export type GlanceEvent = /** Single tap: show, and (re)start the auto-hide timer. */ | { type: "press" } - /** Head-tilt (IMU head-up): show until the head comes back down. */ - | { type: "tilt" } + /** Head-tilt (IMU head-up): show until the head comes back down, or maxMs (default GLANCE_TILT_MAX_MS). */ + | { type: "tilt"; maxMs?: number } /** The IMU reported the head back down: ends a head-tilt showing. */ | { type: "head-down" } /** Long-press: show and keep showing until the release. */ @@ -49,7 +73,7 @@ export type GlanceEvent = /** Double-tap (or any other wake of the regular UI): hide now. */ | { type: "dismiss" }; -export const GLANCE_HIDDEN: GlanceState = Object.freeze({ visible: false, holding: false, tilted: false, hideAtMs: null }); +export const GLANCE_HIDDEN: GlanceState = Object.freeze({ visible: false, holding: false, tilted: false, tiltMaxMs: 0, hideAtMs: null }); export function reduceGlance( state: GlanceState, @@ -61,20 +85,24 @@ export function reduceGlance( case "press": // A tap during a hold or a head-tilt changes nothing: those decide when it ends. if (state.holding || state.tilted) return state; - return { visible: true, holding: false, tilted: false, hideAtMs: nowMs + timeoutMs }; - case "tilt": - return { visible: true, holding: state.holding, tilted: true, hideAtMs: state.holding ? null : nowMs + GLANCE_TILT_MAX_MS }; + return { visible: true, holding: false, tilted: false, tiltMaxMs: 0, hideAtMs: nowMs + timeoutMs }; + case "tilt": { + const maxMs = event.maxMs ?? GLANCE_TILT_MAX_MS; + return { visible: true, holding: state.holding, tilted: true, tiltMaxMs: maxMs, hideAtMs: state.holding ? null : nowMs + maxMs }; + } case "head-down": // Only a head-tilt showing ends with the head; a tap's timer or a hold keeps running. if (!state.tilted) return state; - return state.holding ? { ...state, tilted: false } : GLANCE_HIDDEN; + return state.holding ? { ...state, tilted: false, tiltMaxMs: 0 } : GLANCE_HIDDEN; case "hold": - return { visible: true, holding: true, tilted: state.tilted, hideAtMs: null }; + return { visible: true, holding: true, tilted: state.tilted, tiltMaxMs: state.tiltMaxMs, hideAtMs: null }; case "release": // Releases delivered late or after a disabled hold gesture mean nothing here. if (!state.holding) return state; // Head still up: the board stays, as if the tilt had just shown it. - return state.tilted ? { visible: true, holding: false, tilted: true, hideAtMs: nowMs + GLANCE_TILT_MAX_MS } : GLANCE_HIDDEN; + return state.tilted + ? { visible: true, holding: false, tilted: true, tiltMaxMs: state.tiltMaxMs, hideAtMs: nowMs + state.tiltMaxMs } + : GLANCE_HIDDEN; case "timeout": if (!state.visible || state.holding || state.hideAtMs === null || nowMs < state.hideAtMs) return state; return GLANCE_HIDDEN; diff --git a/app/g2/head-angle.ts b/app/g2/head-angle.ts index cd5c12ab..f4651420 100644 --- a/app/g2/head-angle.ts +++ b/app/g2/head-angle.ts @@ -1,6 +1,8 @@ import { addImuListener, setImuReportEnabled, type ImuReading } from "../native/imu"; import { getHeadUpStatus, setHeadUpTrigger, type HeadUpStatus } from "../native/glasses-controls"; -import { glanceAngleDegrees, glanceAngleSetting, type GlanceAngle } from "../apps/glanceboard/glanceboard-settings"; +import { getStringSetting, setStringSetting } from "../native/settings-store"; +import { glanceAngleSetting, glanceAngleTriggerDegrees, type GlanceAngle } from "../apps/glanceboard/glanceboard-settings"; +import { angleBetweenDegrees, glanceAngleForTilt, meanVector, type Vec3 } from "./head-tilt-math"; // Same ImuReportPace code the accelerometer demo uses (not literal Hz). const IMU_REPORT_PACE = 200; @@ -9,27 +11,14 @@ const SAMPLE_WINDOW_MS = 1_200; /** Give up when the glasses send nothing for this long. */ const FIRST_SAMPLE_TIMEOUT_MS = 3_000; const MIN_SAMPLES = 3; -/** The setting's range; the firmware itself accepts 1..90. */ -export const MIN_GLANCE_ANGLE = 5; -export const MAX_GLANCE_ANGLE = 60; - -/** degrees/rounded are set on success; reason on failure. */ -export type HeadAngleResult = { ok: boolean; degrees?: number; rounded?: number; reason?: string }; +/** The level reading is used for a tilt reading taken within this long. */ +const LEVEL_READING_VALID_MS = 60_000; /** - * Measure how far the head is tilted up right now, from the glasses' - * accelerometer stream (the same IMU whose pitch the firmware compares with - * its head-up threshold). - * - * The temple's sensor axes are not documented, so this does not assume which - * axis points forward. When worn, gravity lies mostly along the sensor's - * vertical axis, and tilting the head up turns it toward the forward axis; the - * angle between gravity and the dominant axis is therefore the tilt, whichever - * axis that is and whichever sign it has. Head roll adds to it, so the wearer - * should keep the head level side to side. Past 45° the dominant axis swaps, - * which is why the setting stops at 60° and readings are clamped there. + * Average the glasses' accelerometer (gravity) over about a second, with the + * report stream on only for that long. */ -export async function measureHeadTilt(): Promise { +async function measureGravity(): Promise<{ ok: true; gravity: Vec3 } | { ok: false; reason: string }> { const samples: ImuReading[] = []; let firstAt = 0; const unsubscribe = addImuListener((reading) => { @@ -55,46 +44,104 @@ export async function measureHeadTilt(): Promise { if (samples.length < MIN_SAMPLES) { return { ok: false, reason: samples.length === 0 ? "no sensor data" : "too few samples" }; } - let x = 0, y = 0, z = 0; - for (const s of samples) { - x += s.x; - y += s.y; - z += s.z; - } - x /= samples.length; - y /= samples.length; - z /= samples.length; - const magnitude = Math.hypot(x, y, z); - if (!(magnitude > 1e-6)) return { ok: false, reason: "sensor reads zero" }; - const dominant = Math.max(Math.abs(x), Math.abs(y), Math.abs(z)); - const degrees = (Math.acos(Math.min(1, dominant / magnitude)) * 180) / Math.PI; - return { ok: true, degrees, rounded: roundGlanceAngle(degrees) }; + const gravity = meanVector(samples); + return gravity ? { ok: true, gravity } : { ok: false, reason: "sensor reads zero" }; } -/** Nearest multiple of 5, kept within the setting's range. */ -export function roundGlanceAngle(degrees: number): number { - const rounded = Math.round(degrees / 5) * 5; - return Math.min(MAX_GLANCE_ANGLE, Math.max(MIN_GLANCE_ANGLE, rounded)); +let levelReading: { gravity: Vec3; atMs: number } | null = null; +let measuring = false; + +/** Which reading the next capture takes: the level one, or the tilted one after it. */ +export function headAngleCaptureStep(): "level" | "tilt" { + return levelReading && Date.now() - levelReading.atMs < LEVEL_READING_VALID_MS ? "tilt" : "level"; +} + +export function headAngleCaptureRunning(): boolean { + return measuring; } /** - * Measure, store the rounded angle in the Head tilt angle setting, and send - * it to the glasses. Returns a short status for the menu row. + * One step of "Set to current head angle". The first call reads the head + * level; the next (within a minute) reads it tilted up, stores the angle + * between the two, rounded to 5°, as the Head tilt angle, and the + * controller's settings listener sends it to the glasses. Returns a short + * status for the menu row, or null when a capture is already running. */ -export async function setGlanceAngleFromHead(): Promise { - const result = await measureHeadTilt(); - if (!result.ok) return `Failed: ${result.reason}`; - glanceAngleSetting.set(String(result.rounded) as GlanceAngle); - const sent = applyGlanceAngle(); - return sent ? `Set to ${result.rounded}°` : `Saved ${result.rounded}° (glasses offline)`; +export async function captureHeadAngleStep(): Promise { + if (measuring) return null; + measuring = true; + try { + const step = headAngleCaptureStep(); + const result = await measureGravity(); + if (result.ok === false) return `Failed: ${result.reason}`; + if (step === "level") { + levelReading = { gravity: result.gravity, atMs: Date.now() }; + return "Now tilt up, select"; + } + const level = levelReading!.gravity; + levelReading = null; + const angle = glanceAngleForTilt(angleBetweenDegrees(level, result.gravity)); + if (angle.ok === false) return `Failed: ${angle.reason}`; + glanceAngleSetting.set(String(angle.rounded) as GlanceAngle); + return getHeadUpStatus() ? `Set to ${angle.rounded}°` : `Saved ${angle.rounded}° (offline)`; + } finally { + measuring = false; + } } -/** Push the Head tilt angle setting to the session (on change and on each connect). */ +/** Forget a level reading (the settings menu was reopened). */ +export function resetHeadAngleCapture(): void { + if (!measuring) levelReading = null; +} + +// The glasses' own head-up switch and angle from before Faceclaw first changed +// them, as "switch,angle", or "" when none is held. Kept here (not only in the +// session) so "Glasses default" can still restore them after an app restart. +const ORIGINAL_KEY = "glanceboard.headTiltOriginal"; + +function savedOriginal(): { switch: number; angle: number } | null { + const [sw, angle] = getStringSetting(ORIGINAL_KEY, "").split(",").map(Number); + return (sw === 0 || sw === 1) && Number.isInteger(angle) ? { switch: sw, angle } : null; +} + +/** + * Push the wanted trigger to the session (on change and on each connect): + * the Head tilt angle while the Glanceboard is enabled, else none, which + * writes back the glasses' own values if Faceclaw changed them. + */ export function applyGlanceAngle(): boolean { - return setHeadUpTrigger(glanceAngleDegrees()); + const sent = setHeadUpTrigger(glanceAngleTriggerDegrees(), savedOriginal()); + syncGlanceAngleOriginal(); + return sent; } -/** The glasses' current head-up trigger (angle + calibration), or null when not read yet. */ +/** + * Keep the persisted original in step with the session: save the values the + * session captured before its first write, and drop them once a read shows + * them restored. Called on apply, from the controller's periodic refresh, and + * when the settings row draws. + */ +export function syncGlanceAngleOriginal(status: HeadUpStatus | null = getHeadUpStatus()): void { + if (!status) return; + const saved = savedOriginal(); + if (!saved) { + if (status.originalSwitch === 0 || status.originalSwitch === 1) { + setStringSetting(ORIGINAL_KEY, `${status.originalSwitch},${status.originalAngle}`); + } + return; + } + if ( + glanceAngleTriggerDegrees() === 0 && + status.desired < 0 && + !status.restorePending && + status.switch === saved.switch && + status.angle === saved.angle + ) { + setStringSetting(ORIGINAL_KEY, ""); + } +} + +/** The glasses' current head-up trigger (angle + calibration), 0 when off, or null when not read yet. */ export function glassesHeadUpTrigger(status: HeadUpStatus | null = getHeadUpStatus()): number | null { if (!status || status.switch < 0) return null; return status.switch === 1 ? status.angle + status.calibration : 0; diff --git a/app/g2/head-tilt-math.ts b/app/g2/head-tilt-math.ts new file mode 100644 index 00000000..e19a0e8c --- /dev/null +++ b/app/g2/head-tilt-math.ts @@ -0,0 +1,58 @@ +/** + * Math for "Set to current head angle", kept free of NativeScript imports so + * tests/head-tilt-math.test.cjs can run it under plain node. + * + * The temple's accelerometer axes are not documented (nor whether the report + * stream applies the firmware's mount matrix), so nothing here assumes which + * axis points forward. Instead the capture takes two readings, one with the + * head level and one tilted up, and the tilt is the angle between the two + * gravity vectors. That works for any mounting and any angle; what it cannot + * tell is direction (tilting down by 30° reads the same as up by 30°), so the + * row's instructions say to tilt up, and head roll between the two readings + * adds to the result. + */ + +export type Vec3 = { x: number; y: number; z: number }; + +/** The setting's range; the firmware itself accepts 1..90. */ +export const MIN_GLANCE_ANGLE = 5; +export const MAX_GLANCE_ANGLE = 60; + +/** Mean of the samples, or null when there are none or they sum to zero. */ +export function meanVector(samples: readonly Vec3[]): Vec3 | null { + if (samples.length === 0) return null; + let x = 0, y = 0, z = 0; + for (const s of samples) { + x += s.x; + y += s.y; + z += s.z; + } + const mean = { x: x / samples.length, y: y / samples.length, z: z / samples.length }; + return Math.hypot(mean.x, mean.y, mean.z) > 1e-6 ? mean : null; +} + +/** Angle between two gravity readings, in degrees (0..180). */ +export function angleBetweenDegrees(a: Vec3, b: Vec3): number { + const dot = a.x * b.x + a.y * b.y + a.z * b.z; + const cross = Math.hypot(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); + // atan2 stays accurate near 0° and 180°, where acos of the normalized dot does not. + return (Math.atan2(cross, dot) * 180) / Math.PI; +} + +/** Nearest multiple of 5, kept within the setting's range. */ +export function roundGlanceAngle(degrees: number): number { + const rounded = Math.round(degrees / 5) * 5; + return Math.min(MAX_GLANCE_ANGLE, Math.max(MIN_GLANCE_ANGLE, rounded)); +} + +/** + * The setting value for a measured tilt, or why it cannot be used: a tilt that + * would round below the minimum is reported (a head that did not move, not a + * 5° trigger), and so is one past the maximum. + */ +export function glanceAngleForTilt(degrees: number): { ok: true; rounded: number } | { ok: false; reason: string } { + if (!Number.isFinite(degrees)) return { ok: false, reason: "no reading" }; + if (degrees < MIN_GLANCE_ANGLE - 2.5) return { ok: false, reason: "head not tilted" }; + if (degrees >= MAX_GLANCE_ANGLE + 2.5) return { ok: false, reason: `over ${MAX_GLANCE_ANGLE}°` }; + return { ok: true, rounded: roundGlanceAngle(degrees) }; +} diff --git a/app/native/glasses-controls.ts b/app/native/glasses-controls.ts index d77bb658..f5d3cc30 100644 --- a/app/native/glasses-controls.ts +++ b/app/native/glasses-controls.ts @@ -3,10 +3,15 @@ declare const com: any; /** * Head-up (look-up wake) trigger on the active glasses session * (GlassesSessionCore.setHeadUpTrigger / getHeadUpStatus). Android only for - * now: on iOS, or with no session, the setter does nothing and the getter - * returns null. + * now (headUpControlsAvailable): on iOS, or with no session, the setter does + * nothing and the getter returns null. */ +/** Whether this platform can change the glasses' head-up setting at all. */ +export function headUpControlsAvailable(): boolean { + return Boolean(global.isAndroid); +} + /** GlassesSessionCore.getHeadUpStatus. switch -1 = not read on this connection. */ export type HeadUpStatus = { switch: number; @@ -15,6 +20,11 @@ export type HeadUpStatus = { /** The trigger Faceclaw is maintaining, or -1 when it leaves the glasses' own setting. */ desired: number; readAgeMs: number; + /** The glasses' own switch and angle from before Faceclaw changed them (switch -1 = none held). */ + originalSwitch: number; + originalAngle: number; + /** Those originals are being written back. */ + restorePending: boolean; }; function activeCommunicator(): any { @@ -26,12 +36,16 @@ function activeCommunicator(): any { } } -/** Ask the session to keep the head-up trigger at `degrees` (1..90); 0 stops managing it. */ -export function setHeadUpTrigger(degrees: number): boolean { +/** + * Ask the session to keep the head-up trigger at `degrees` (1..90); 0 stops + * managing it and writes back `original` (or what the session saved itself) + * if Faceclaw changed the glasses' values. + */ +export function setHeadUpTrigger(degrees: number, original: { switch: number; angle: number } | null = null): boolean { const active = activeCommunicator(); if (!active) return false; try { - active.setHeadUpTrigger(Math.round(degrees)); + active.setHeadUpTrigger(Math.round(degrees), original ? original.switch : -1, original ? Math.round(original.angle) : 0); return true; } catch (error) { console.warn(`setHeadUpTrigger failed: ${error}`); diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt index f9a0413b..0fad95e5 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt @@ -358,6 +358,14 @@ class GlassesSessionCore( // The trigger pitch TS asked for (degrees, 1..90), or -1 to leave the glasses' // own setting alone. Reapplied after every read that disagrees with it. internal var desiredHeadUpTrigger = -1 + // The glasses' own switch and angle from before Faceclaw first changed them + // (switch -1 = unknown): captured before the first write, or handed back by TS, + // which persists them across app restarts. Written back while + // headUpRestorePending (TS stopped managing the trigger), then forgotten once a + // read confirms them. + internal var headUpOriginalSwitch = -1 + internal var headUpOriginalAngle = 0 + internal var headUpRestorePending = false // Set after queueing a correction so the next settings read comes right away to // confirm it; cleared by that read, so a firmware that refuses the value is // retried on the normal poll cadence, not in a loop. @@ -962,15 +970,32 @@ class GlassesSessionCore( * managing it. Kept for the life of this object and reapplied on every connection: the * next settings read supplies the glasses' calibration, then the switch and angle are * written (see reconcileHeadUpLocked) and a follow-up read confirms them. + * + * [originalSwitch] (0/1, or -1 when unknown) and [originalAngle] are the glasses' own + * values from before Faceclaw changed them, as TS saved them from getHeadUpStatus; they + * take precedence over what this object captured. With degrees 0 they are written back. */ - fun setHeadUpTrigger(degrees: Int) { + fun setHeadUpTrigger(degrees: Int, originalSwitch: Int, originalAngle: Int) { monitor.withLock { + if (originalSwitch in 0..1) { + headUpOriginalSwitch = originalSwitch + headUpOriginalAngle = originalAngle + } + // A change of mind drops writes still queued for the previous value. + clearMessagesOfKindLocked("head-up-control") + headUpVerifyPending = false desiredHeadUpTrigger = if (degrees in 1..90) degrees else -1 - logLine(if (desiredHeadUpTrigger > 0) "head-up trigger requested: ${desiredHeadUpTrigger}°" - else "head-up trigger: left to the glasses") - if (!running || !sessionReady || desiredHeadUpTrigger <= 0) return + headUpRestorePending = desiredHeadUpTrigger < 0 && headUpOriginalSwitch >= 0 + logLine(when { + desiredHeadUpTrigger > 0 -> "head-up trigger requested: ${desiredHeadUpTrigger}°" + headUpRestorePending -> "head-up trigger: restore the glasses' own " + + "(switch=$headUpOriginalSwitch angle=$headUpOriginalAngle)" + else -> "head-up trigger: left to the glasses" + }) + if (!running || !sessionReady) return + if (desiredHeadUpTrigger <= 0 && !headUpRestorePending) return if (headUpSwitch >= 0) { - queueHeadUpWritesLocked(desiredHeadUpTrigger - headUpCalibration) + applyHeadUpLocked(verifying = false) } else { // Calibration unknown: read the settings first; the ack applies the trigger. lastBatteryRefreshAtMs = 0L @@ -987,6 +1012,9 @@ class GlassesSessionCore( status["angle"] = headUpAngle status["calibration"] = headUpCalibration status["desired"] = desiredHeadUpTrigger + status["originalSwitch"] = headUpOriginalSwitch + status["originalAngle"] = headUpOriginalAngle + status["restorePending"] = headUpRestorePending status["readAgeMs"] = if (headUpReadAtMs == 0L) -1L else maxOf(0L, now() - headUpReadAtMs) return try { Json.write(status) } catch (e: Exception) { "{}" } } diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt index bd78b09b..e1a53345 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionSend.kt @@ -1059,30 +1059,69 @@ internal fun GlassesSessionCore.reconcileHeadUpLocked(ackPayload: ByteArray?) { headUpCalibration = headUp[2] headUpReadAtMs = now() } + if (headUpSwitch < 0 || !sessionReady) return + applyHeadUpLocked(verifying) +} + +/** + * Compare the last read with what is wanted (the trigger, or the glasses' original values + * while a restore is pending) and queue writes when they differ. After a verifying read + * that still disagrees nothing is queued: the next regular poll retries, so a firmware + * that clamps or refuses the value costs one attempt per poll interval, not a write loop. + */ +internal fun GlassesSessionCore.applyHeadUpLocked(verifying: Boolean) { val desired = desiredHeadUpTrigger - if (desired <= 0 || headUpSwitch < 0 || !sessionReady) return - val wantAngle = desired - headUpCalibration - if (headUpSwitch == 1 && headUpAngle == wantAngle) { - if (verifying) logLine("head-up trigger confirmed: ${desired}° (angle $wantAngle + calibration $headUpCalibration)") + val wantSwitch: Int + val wantAngle: Int + if (desired > 0) { + wantSwitch = 1 + wantAngle = desired - headUpCalibration + } else if (headUpRestorePending) { + wantSwitch = headUpOriginalSwitch + wantAngle = headUpOriginalAngle + } else { + return + } + if (headUpSwitch == wantSwitch && headUpAngle == wantAngle) { + if (desired > 0) { + if (verifying) logLine("head-up trigger confirmed: ${desired}° (angle $wantAngle + calibration $headUpCalibration)") + } else { + logLine("head-up setting restored (switch=$wantSwitch angle=$wantAngle)") + headUpRestorePending = false + headUpOriginalSwitch = -1 + headUpOriginalAngle = 0 + } return } if (verifying) { - logLine("head-up trigger not applied yet (switch=$headUpSwitch angle=$headUpAngle); retrying on next poll") + logLine("head-up setting not applied yet (switch=$headUpSwitch angle=$headUpAngle); retrying on next poll") + return } - queueHeadUpWritesLocked(wantAngle) + if (desired > 0 && headUpOriginalSwitch < 0) { + headUpOriginalSwitch = headUpSwitch + headUpOriginalAngle = headUpAngle + logLine("head-up original saved (switch=$headUpSwitch angle=$headUpAngle)") + } + queueHeadUpWritesLocked(wantSwitch, wantAngle) } -internal fun GlassesSessionCore.queueHeadUpWritesLocked(angle: Int) { +internal fun GlassesSessionCore.queueHeadUpWritesLocked(switch: Int, angle: Int) { clearMessagesOfKindLocked("head-up-control") - val on = messageBuilder.setHeadUp(BleProtocol.HEAD_UP_FIELD_SWITCH, 1) - on.onTimeout = MessageCallback { logLine("head-up switch ack timeout") } + val sw = messageBuilder.setHeadUp(BleProtocol.HEAD_UP_FIELD_SWITCH, switch) + sw.onTimeout = MessageCallback { logLine("head-up switch ack timeout") } val set = messageBuilder.setHeadUp(BleProtocol.HEAD_UP_FIELD_ANGLE, angle) set.onTimeout = MessageCallback { logLine("head-up angle ack timeout") } - pendingMessages.addLast(on) - pendingMessages.addLast(set) + // Switch on before the angle; when switching off, the angle goes first. + if (switch == 1) { + pendingMessages.addLast(sw) + pendingMessages.addLast(set) + } else { + pendingMessages.addLast(set) + pendingMessages.addLast(sw) + } headUpVerifyPending = true lastBatteryRefreshAtMs = 0L - logLine("queue head-up switch on + angle $angle (trigger ${desiredHeadUpTrigger}°, calibration $headUpCalibration)") + logLine("queue head-up switch $switch + angle $angle (trigger ${desiredHeadUpTrigger}°, calibration $headUpCalibration)") } internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessage { diff --git a/tests/glance-state.test.cjs b/tests/glance-state.test.cjs index 73eb9f0d..7d753b04 100644 --- a/tests/glance-state.test.cjs +++ b/tests/glance-state.test.cjs @@ -6,6 +6,7 @@ const { GLANCE_TIMEOUT_MS, GLANCE_TILT_MAX_MS, glanceEventForGesture, + glanceTiltMaxMs, reduceGlance, } = require("../.test-build/app/g2/glance-state.js"); @@ -13,7 +14,7 @@ const T0 = 1_000_000; test("a press shows the board and arms the auto-hide timer", () => { const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0); - assert.deepEqual(shown, { visible: true, holding: false, tilted: false, hideAtMs: T0 + GLANCE_TIMEOUT_MS }); + assert.deepEqual(shown, { visible: true, holding: false, tilted: false, tiltMaxMs: 0, hideAtMs: T0 + GLANCE_TIMEOUT_MS }); // A timer firing early is ignored; on time it hides. assert.equal(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS - 1), shown); assert.deepEqual(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), GLANCE_HIDDEN); @@ -28,7 +29,7 @@ test("a further press renews the timer from the new press", () => { test("a hold shows the board without a timer and the release hides it", () => { const held = reduceGlance(GLANCE_HIDDEN, { type: "hold" }, T0); - assert.deepEqual(held, { visible: true, holding: true, tilted: false, hideAtMs: null }); + assert.deepEqual(held, { visible: true, holding: true, tilted: false, tiltMaxMs: 0, hideAtMs: null }); assert.equal(reduceGlance(held, { type: "timeout" }, T0 + 60_000), held); // A tap mid-hold neither hides nor starts a timer. assert.equal(reduceGlance(held, { type: "press" }, T0 + 500), held); @@ -71,7 +72,7 @@ test("the press timeout is the host's when supplied", () => { test("a head-tilt shows the board until the head comes back down", () => { const up = reduceGlance(GLANCE_HIDDEN, { type: "tilt" }, T0); - assert.deepEqual(up, { visible: true, holding: false, tilted: true, hideAtMs: T0 + GLANCE_TILT_MAX_MS }); + assert.deepEqual(up, { visible: true, holding: false, tilted: true, tiltMaxMs: GLANCE_TILT_MAX_MS, hideAtMs: T0 + GLANCE_TILT_MAX_MS }); // The tap duration no longer applies, and taps change nothing. assert.equal(reduceGlance(up, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), up); assert.equal(reduceGlance(up, { type: "press" }, T0 + 500), up); @@ -89,10 +90,27 @@ test("head-down leaves a tap's or a hold's showing alone", () => { test("a hold and a head-tilt together: the board stays until both end", () => { const both = reduceGlance(reduceGlance(GLANCE_HIDDEN, { type: "tilt" }, T0), { type: "hold" }, T0 + 100); - assert.deepEqual(both, { visible: true, holding: true, tilted: true, hideAtMs: null }); + assert.deepEqual(both, { visible: true, holding: true, tilted: true, tiltMaxMs: GLANCE_TILT_MAX_MS, hideAtMs: null }); const released = reduceGlance(both, { type: "release" }, T0 + 200); - assert.deepEqual(released, { visible: true, holding: false, tilted: true, hideAtMs: T0 + 200 + GLANCE_TILT_MAX_MS }); + assert.deepEqual(released, { visible: true, holding: false, tilted: true, tiltMaxMs: GLANCE_TILT_MAX_MS, hideAtMs: T0 + 200 + GLANCE_TILT_MAX_MS }); const downWhileHeld = reduceGlance(both, { type: "head-down" }, T0 + 200); - assert.deepEqual(downWhileHeld, { visible: true, holding: true, tilted: false, hideAtMs: null }); + assert.deepEqual(downWhileHeld, { visible: true, holding: true, tilted: false, tiltMaxMs: 0, hideAtMs: null }); assert.deepEqual(reduceGlance(downWhileHeld, { type: "release" }, T0 + 300), GLANCE_HIDDEN); }); + +test("a tilt with a shorter cap keeps it, also across a hold", () => { + const up = reduceGlance(GLANCE_HIDDEN, { type: "tilt", maxMs: 5000 }, T0); + assert.equal(up.hideAtMs, T0 + 5000); + assert.deepEqual(reduceGlance(up, { type: "timeout" }, T0 + 5000), GLANCE_HIDDEN); + const held = reduceGlance(up, { type: "hold" }, T0 + 100); + assert.equal(reduceGlance(held, { type: "release" }, T0 + 1000).hideAtMs, T0 + 1000 + 5000); +}); + +test("the tilt cap falls back to the tap duration where the head-down is unlikely", () => { + const tapTimeoutMs = 5000; + assert.equal(glanceTiltMaxMs({ resumedSession: false, triggerDegrees: 30, tapTimeoutMs }), GLANCE_TILT_MAX_MS); + assert.equal(glanceTiltMaxMs({ resumedSession: false, triggerDegrees: null, tapTimeoutMs }), GLANCE_TILT_MAX_MS); + assert.equal(glanceTiltMaxMs({ resumedSession: true, triggerDegrees: 30, tapTimeoutMs }), tapTimeoutMs); + assert.equal(glanceTiltMaxMs({ resumedSession: false, triggerDegrees: 20, tapTimeoutMs }), tapTimeoutMs); + assert.equal(glanceTiltMaxMs({ resumedSession: false, triggerDegrees: 25, tapTimeoutMs }), GLANCE_TILT_MAX_MS); +}); diff --git a/tests/head-tilt-math.test.cjs b/tests/head-tilt-math.test.cjs new file mode 100644 index 00000000..12bed277 --- /dev/null +++ b/tests/head-tilt-math.test.cjs @@ -0,0 +1,67 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + MAX_GLANCE_ANGLE, + MIN_GLANCE_ANGLE, + angleBetweenDegrees, + glanceAngleForTilt, + meanVector, + roundGlanceAngle, +} = require("../.test-build/app/g2/head-tilt-math.js"); + +const rad = (deg) => (deg * Math.PI) / 180; + +/** + * Gravity (m/s^2) after pitching the head by pitchDeg, in a sensor frame + * mounted so that no axis lines up with the head: the level reading points + * along an arbitrary direction, and the pitch rotates it about an arbitrary + * axis perpendicular to that (Rodrigues' formula). + */ +function gravityPitched(pitchDeg) { + const v = normalize({ x: 0.3, y: -0.9, z: 0.2 }); + const k0 = { x: 0.9, y: 0.4, z: 0.45 }; + const dot = k0.x * v.x + k0.y * v.y + k0.z * v.z; + const k = normalize({ x: k0.x - dot * v.x, y: k0.y - dot * v.y, z: k0.z - dot * v.z }); + const c = Math.cos(rad(pitchDeg)); + const s = Math.sin(rad(pitchDeg)); + const cross = { x: k.y * v.z - k.z * v.y, y: k.z * v.x - k.x * v.z, z: k.x * v.y - k.y * v.x }; + return { x: 9.8 * (v.x * c + cross.x * s), y: 9.8 * (v.y * c + cross.y * s), z: 9.8 * (v.z * c + cross.z * s) }; +} + +function normalize(v) { + const m = Math.hypot(v.x, v.y, v.z); + return { x: v.x / m, y: v.y / m, z: v.z / m }; +} + +test("the tilt between two readings does not depend on the sensor's axes, past 45° too", () => { + const level = gravityPitched(0); + for (const pitch of [5, 20, 30, 45, 50, 60, 75]) { + assert.ok(Math.abs(angleBetweenDegrees(level, gravityPitched(pitch)) - pitch) < 1e-6, `pitch ${pitch}`); + } + // From a non-zero level reading the difference is what counts. + assert.ok(Math.abs(angleBetweenDegrees(gravityPitched(-10), gravityPitched(40)) - 50) < 1e-6); + assert.ok(Math.abs(angleBetweenDegrees(level, level)) < 1e-6); +}); + +test("meanVector averages and rejects empty or zero input", () => { + assert.deepEqual(meanVector([{ x: 1, y: 2, z: 3 }, { x: 3, y: 2, z: 1 }]), { x: 2, y: 2, z: 2 }); + assert.equal(meanVector([]), null); + assert.equal(meanVector([{ x: 0, y: 0, z: 0 }]), null); +}); + +test("roundGlanceAngle rounds to 5° within the setting's range", () => { + assert.equal(roundGlanceAngle(27.4), 25); + assert.equal(roundGlanceAngle(27.5), 30); + assert.equal(roundGlanceAngle(1), MIN_GLANCE_ANGLE); + assert.equal(roundGlanceAngle(80), MAX_GLANCE_ANGLE); +}); + +test("glanceAngleForTilt reports a head that did not move or went too far instead of clamping", () => { + assert.deepEqual(glanceAngleForTilt(31), { ok: true, rounded: 30 }); + assert.deepEqual(glanceAngleForTilt(52), { ok: true, rounded: 50 }); + assert.deepEqual(glanceAngleForTilt(3), { ok: true, rounded: 5 }); + assert.equal(glanceAngleForTilt(0.5).ok, false); + assert.equal(glanceAngleForTilt(65).ok, false); + assert.equal(glanceAngleForTilt(NaN).ok, false); +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index 5c5fd912..6efa67a4 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -36,6 +36,7 @@ "../app/g2/glasses-artwork.ts", "../app/g2/glasses-display-state.ts", "../app/g2/glance-state.ts", + "../app/g2/head-tilt-math.ts", "../app/ui/shell/notification-modal-queue.ts", "../app/ui/shell/notification-popup-delay.ts", "../app/apps/glanceboard/layout.ts",