Custom auto-brightness, and fade in/out effects

This commit is contained in:
James Babcock committed 2026-09-25 00:57:43 -07:00
1 parent f66e0b025f
commit 4f3ad37c20
29 files changed
+589 -93

No files matched your search

@@ -169,6 +169,8 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre
fun setCompassEnabled(owner: String?, enable: Boolean) = core.setCompassEnabled(owner, enable)
fun setBrightness(autoAdjust: Boolean, brightnessLevel: Int) = core.setBrightness(autoAdjust, brightnessLevel)
fun configureBrightness(auto: Boolean, level: Int, minimum: Int, maximum: Int, curve: String, fadeMs: Int) =
core.configureBrightness(auto, level, minimum, maximum, curve, fadeMs)
fun enableWearDetectionAndRequestState() = core.enableWearDetectionAndRequestState()
+26
View File
@@ -0,0 +1,26 @@
export const DEFAULT_BRIGHTNESS_CURVE = "0:0,0.2:7,1.5:33,5:100";
const PREVIOUS_DEFAULT_CURVE = "0:0,1:10,10:30,100:65,1000:100";
/** Percent of the configured range; defaults (20–100) give 20/26/46/100. */
export function brightnessCurveError(value: string): string | null {
const pairs = value.split(",").map(part => part.trim().split(":"));
if (pairs.length < 2 || pairs.length > 16 || pairs.some(p => p.length !== 2 || p.some(s => !s.trim())))
return "Use 2–16 lux:percent pairs separated by commas.";
const points = pairs.map(pair => pair.map(Number));
if (points.some(([lux, percent]) => !Number.isFinite(lux) || !Number.isFinite(percent)
|| lux < 0 || lux > 1_000_000 || percent < 0 || percent > 100))
return "Lux must be 0–1000000 and percent must be 0–100.";
if (points[0][0] !== 0 || points[0][1] !== 0 || points[points.length - 1][1] !== 100)
return "Start at 0:0 and end at 100%. Set dark-room brightness with Auto minimum.";
if (points.some(([lux, percent], i) => i > 0 && (lux <= points[i-1][0] || percent < points[i-1][1])))
return "Lux must increase and brightness must not decrease.";
return null;
}
/** Keep incomplete drafts intact. Validation must never replace typed input. */
export function normalizeBrightnessCurve(value: string | null | undefined): string {
if (value == null) return DEFAULT_BRIGHTNESS_CURVE;
if (brightnessCurveError(value)) return value;
const canonical = value.split(",").map(pair => pair.split(":").map(Number).join(":")).join(",");
return canonical === PREVIOUS_DEFAULT_CURVE ? DEFAULT_BRIGHTNESS_CURVE : canonical;
}
+1
View File
@@ -32,5 +32,6 @@ export const CFW_MSG_DRAW_CALLS = 26
export const CFW_MSG_SET_ROOT_DISPLAY_LIST = 27
export const CFW_MSG_PRESENT = 28
export const CFW_MSG_CREATE_SURFACE = 29
export const CFW_MSG_BRIGHTNESS = 30
export const CFW_MSG_TYPE_MASK = 127
export const CFW_MSG_FLAG_LENSES_DIFFER = 128
+14 -5
View File
@@ -1,6 +1,6 @@
import { startRemoteInput } from "../remote/service";
import { acceptInput, resetRingInputFilter } from "../ui/input-monitor";
import { Application, ImageSource } from "@nativescript/core";
import { Application, Dialogs, ImageSource } from "@nativescript/core";
import { EvenAIStatus, EvenAIStatusName, EventSourceType, EventSourceTypeName, OsEventTypeList, OsEventTypeName, WatchGestureType, WatchGestureTypeName } from "./events";
import { isValidMacAddress, loadDeviceAddresses } from "./device-addresses";
import {
@@ -71,7 +71,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
import { appViewportRect, SIDEBAR_WIDTH, sidebarStripVisible, type WindowHeightMode } from "../ui/shell/geometry";
import { type LayerActions, type TextSettingsEditToggle } from "../ui/layers";
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, displayModeSetting, navigateDisplayModeSetting, navigateVerticalPositionSetting, terminalDisplayModeSetting, terminalVerticalPositionSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayModeSetting, navigateDisplayModeSetting, navigateVerticalPositionSetting, terminalDisplayModeSetting, terminalVerticalPositionSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import {
getInstalledEvenHubAppById,
@@ -908,11 +908,14 @@ class DashboardController {
*/
private pushBrightness(force = false): void {
if (!this.communicator) return;
const value = brightnessSetting.get();
const preferences = getBrightnessPreferences();
const value = JSON.stringify(preferences);
if (!force && value === this.lastPushedBrightness) return;
this.lastPushedBrightness = value;
const level = brightnessSettingToLevel(value);
void this.communicator.setBrightness(level === null, level ?? 0).catch(() => {});
void this.communicator.configureBrightness(preferences).catch((error) => {
this.lastPushedBrightness = null;
this.appendLog(`brightness configuration failed: ${this.formatError(error)}`);
});
}
/** Save the occupied part of the composited screen as a 4-bit grayscale PNG. */
@@ -1341,6 +1344,7 @@ class DashboardController {
// queue is FIFO, so enqueuing the screen size first guarantees it lands
// ahead of them. Mirrors ensurePreviewDisplay.
await communicator.configureCompositorScreen(G2_LENS_WIDTH, G2_LENS_HEIGHT);
await communicator.configureBrightness(getBrightnessPreferences());
this.offState = communicator.onStateChange((state) => {
if (state.phase !== "connected") resetRingInputFilter();
if (state.phase === "unpaired") {
@@ -2035,6 +2039,11 @@ class DashboardController {
*/
finishActiveTextSettingEdit(): void {
if (!this.activeTextSettings.length) return;
const invalid = this.activeTextSettings.find(setting => setting.validationError());
if (invalid) {
void Dialogs.alert({ title: invalid.editorTitle, message: invalid.validationError()!, okButtonText: "OK" });
return;
}
const onFinish = this.activeTextEditorOnFinish;
// Completing is not cancelling: drop the cancel callback before
// endTextSettingEdit, which fires whatever is still set.
+1 -1
View File
@@ -26,7 +26,7 @@ export type FirmwareInfo = {
};
/** The Faceclaw firmware revision this build of the app needs. */
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 29;
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 32;
const FACECLAW_PREFIX = "Faceclaw/";
const LEGACY_PREFIX = "EVENCFW";
+34 -34
View File
@@ -19,12 +19,12 @@ export type FirmwarePatchSet = {
export const CFW_PATCH_SET: FirmwarePatchSet = {
"base": "g2_2.3.0.24.bin",
"baseSha256": "187ccf2bcc5c17a212106e8a376745511e8289c4232b634a7ea94b9bf25a0979",
"outputSha256": "0275d20b0e50cd8fccc2eb4209384cac93ff3ae22149ddcc70da4a375440c818",
"outputSha256": "61f732b4a6ba10c26b1eb4f93253d990380b5a7cff4fdd18482626a883c457e6",
"patches": [
{
"offset": 1045797,
"old": "38b584b0",
"new": "5cf35fb9",
"new": "5df3bbb8",
"desc": "ring receiver entry: timestamped unfiltered reports under framebuffer lease"
},
{
@@ -36,49 +36,49 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1437923,
"old": "fef788ff",
"new": "fcf26efe",
"new": "fdf2cafd",
"desc": "cfw_ancs_event"
},
{
"offset": 1437951,
"old": "fef7e8fb",
"new": "fcf2a8fb",
"new": "fdf204fb",
"desc": "cfw_ancs_open"
},
{
"offset": 1437969,
"old": "fef7e7fb",
"new": "fcf2bffb",
"new": "fdf21bfb",
"desc": "cfw_ancs_close"
},
{
"offset": 1388387,
"old": "39694d00",
"new": "c5547d00",
"new": "7d637d00",
"desc": "connection-bound ANCS EUS write callback"
},
{
"offset": 971497,
"old": "fff717f8",
"new": "6ef38ffa",
"new": "6ff3ebf9",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 971845,
"old": "fef769ff",
"new": "6ef3e1f9",
"new": "6ff33df9",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 979579,
"old": "fdf74ef8",
"new": "6cf3c6fa",
"new": "6df322fa",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 1428895,
"old": "f8f76cfd",
"new": "fbf206fe",
"new": "fcf23afa",
"desc": "bl cfw_receive_packet (private SID-f0 probe before TPL reassembly)"
},
{
@@ -108,145 +108,145 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1248487,
"old": "d4f712fb",
"new": "29f396fc",
"new": "2af304fb",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
"offset": 1246183,
"old": "f5f7e2f8",
"new": "29f372fe",
"new": "2af388fc",
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
},
{
"offset": 975219,
"old": "02f083fc",
"new": "6bf3defe",
"new": "6cf3f4fc",
"desc": "bl faceclaw_display_start @ 0x467d68 (fail-open wake takeover)"
},
{
"offset": 975411,
"old": "02f023fc",
"new": "6bf342ff",
"new": "6cf358fd",
"desc": "bl faceclaw_display_start_headup @ 0x467e28 (fail-open wake takeover)"
},
{
"offset": 975103,
"old": "07f085fb",
"new": "6df398fa",
"new": "6ef3f4f9",
"desc": "bl headup_gate (head-up sensor event -> EvenHub sys event 12 under lease)"
},
{
"offset": 830549,
"old": "19f03efb",
"new": "90f347fc",
"new": "91f3a3fb",
"desc": "bl gesture_ring_press_mode (observe ring touch-down, preserve stock dispatch)"
},
{
"offset": 830795,
"old": "1ff071ff",
"new": "90f300fc",
"new": "91f35cfb",
"desc": "bl gesture_press (owned event 9 before stock menu gate)"
},
{
"offset": 830887,
"old": "1ff043ff",
"new": "90f3fafb",
"new": "91f356fb",
"desc": "bl gesture_short_long (Faceclaw lease gates event 11 vs stock Menu path)"
},
{
"offset": 831763,
"old": "1ff08dfd",
"new": "90f330fa",
"new": "91f38cf9",
"desc": "bl gesture_release (owned event 10 before stock menu gate)"
},
{
"offset": 1570209,
"old": "7fb50600",
"new": "dbf227b8",
"new": "dbf295be",
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
},
{
"offset": 1051545,
"old": "f6f787f9",
"new": "55f30ff8",
"new": "55f311f9",
"desc": "bl display_copy_hook @ 0x47a78e (640x480 direct framebuffer)"
},
{
"offset": 1051861,
"old": "f6f7e9f8",
"new": "54f371ff",
"new": "55f373f8",
"desc": "bl display_copy_hook @ 0x47a8ca (640x480 direct framebuffer)"
},
{
"offset": 1262237,
"old": "d9f7d0fd",
"new": "25f3a7fd",
"new": "26f345fb",
"desc": "bl faceclaw_send_wear_event @ 0x4ade92 (outside onboarding)"
},
{
"offset": 1262337,
"old": "d9f79efd",
"new": "25f375fd",
"new": "26f313fb",
"desc": "bl faceclaw_send_wear_event @ 0x4adef6 (outside onboarding)"
},
{
"offset": 1309405,
"old": "67f02dff",
"new": "19f37ffe",
"new": "1af31dfc",
"desc": "bl compass_decode_capture (sample-matched GAF diagnostics)"
},
{
"offset": 1307865,
"old": "fff7c9fb",
"new": "1af3fdf9",
"new": "1af39bff",
"desc": "bl compass_report_event (stock UI + heading with diagnostics over BLE)"
},
{
"offset": 1300937,
"old": "00210170",
"new": "1bf3e3fe",
"new": "1cf381fc",
"desc": "bl compass_preserve_accuracy (retain magnetic calibration under Faceclaw framebuffer lease)"
},
{
"offset": 4537963,
"old": "",
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf80b5002a18bf10f0030301d186460ce000f1010c864600bf013a0ef8011b04d01cf003030cf1010cf6d1102a11d35ffa81fc4ff001330cfb03fc00bf103acef80cc0cef808c0cef804c04ef810cb0f2af4d8042a0bd35ffa81fc4ff001330cfb03fc00bf043a032a4ef804cbfad8002a08bf80bdaef10103013a03f8011ffbd180bd00bf2de9f04fc5b04ff64c484ef66c6b4ff29c591446cff6ff78ccf2ff0bc2f229094ff6ff75002701260d93cde90e0106e048f2a351c0f24501bff32f8f8847d9f800a0bff35f8fd9f800000321cff680710140b1f1005fbff35f8f02d10168594544d04ff46d7006f04bfc002800f01a81414600bf42180c3182f8b47382f8b57382f8b67382f8b77382f8b87382f8b97382f8ba7382f8bb7382f8bc7382f8bd7382f8be7382f8bf73e4d1c0f800b086728583c583058445848584c584058545858585c585058645868586c5860587458759e8001f5145abd1bff35f8f49e8000121b159e8001f5145f8d0a1e70f99012641ea04410024c0f8701206e048f2a351c0f24501bff32f8f8847d9f80070bff35f8fd9f800000321cff680710140b1f1005fbff35f8f02d10168594544d04ff46d7006f0e5fb002800f0b480414600bf42180c3182f8b44382f8b54382f8b64382f8b74382f8b84382f8b94382f8ba4382f8bb4382f8bc4382f8bd4382f8be4382f8bf43e4d1c0f800b086728583c583058445848584c584058545858585c585058645868586c5860587458759e8001fb942abd1bff35f8f49e8000121b159e8001fb942f8d0a1e7d0f874a242f6f766c0f24406baf1000fbff35f8f4ad006f19a0250464ff0ff314ff0ff379047002840f023810f9800285fd00e980778a7f11700022859d80f980c2840f00c810e9e7078b178084300f00681f0780138022800f20181b279f379747a42ea0322337a307942ea0342717942ea0463b27af67a192f42ea062200f06f83172f40f08483002a40f0e880fe2800f07485812800f06685002840f07b8551ea030040f0db8000f0fabe04460020b047d8b104f51d7151e800afbaf1000f0bd1bff35f8f00bf41e80002002a7bd051e800afbaf1000ff6d00021bff32f8f0029bff35f8f6bd0824694e74ff0ff37bfe047f6df40c0f24f008047002701261197adf8487006e048f2a351c0f24501bff32f8f8847d9f80040bff35f8fd9f800000321cff680710140b1f1005fbff35f8f02d10168594549d04ff46d7006f003fb002842d0414642180c3182f8b47382f8b57382f8b67382f8b77382f8b87382f8b97382f8ba7382f8bb7382f8bc7382f8bd7382f8be7382f8bf73e4d1c0f800b086728583c583058445848584c584058545858585c585058645868586c5860587458759e8001fa142add1bff35f8f49e8000159b159e8001fa142f8d0a3e706f5a971884726e7012189e700200e9999b10f9a8ab1097801f07f02b2f10b0418bf0124b2f11c0618bf01268a2924dc0b2926d01c2924d03fe00d9010a804f0c7f84ff0ff3701269df84900002810a818bf4ff0ff3704f08bf9054646b99df8480028b94af21f30c0f247004c3080470d98002818bfc56013e09c2901d08b291bd160b14af21f31c0f247010746884797f8641119b997f80413384669b14ff0ff3742f6f760c0f2440000f5807150468847384645b0bde8f08f0d9010a8264004f086f80e98007800f07f041d2c00f07e0018bf1a2811d1d9f800100322cff680720a40b2f1005fbff35f8f0ad10a685a4504bf002281f8812303e0a4f115010129e9d90f2c0adc092c00f3cc80052c00f07882072c40f0f282002769e0142c00f37781102c00f07582112c40f0e7820f98022840f00b840e990878112840f006844878002840f0028445f64d50c0f24600804701284ff000077ff475af40f20830c0f210003590ff208df8d00044f25220c0f20100339040f2c960c0f248003446cde93677804798b148f27e30c2f2070000880122c1b264298df8cf2008d80721b0f5807f38bf03218df8cf108df8d00040f2d260adf8d800052035ae8df8da00f01d33a90522fff748fc4ff22507c0f247070120092132460c23b8470746264631e748f2a351c0f24501bff32f8f8847d9f80040bff35f8fd9f800000321cff680710140b1f1005fbff35f8f03d10168594500f04e844ff46d7006f0b4f9002800f04684414642180c3182f8b47382f8b57382f8b67382f8b77382f8b87382f8b97382f8ba7382f8bb7382f8bc7382f8bd7382f8be7382f8bf73e4d10121c0f800b081728583c583058445848584c584058545858585c585058645868586c5860587458759e8001fa142aad1bff35f8f49e80001002900f00c8459e8001fa142f6d09ee70a2c00f0b9810b2c40f02682d9f800500320cff680702840b0f1005fbff35f8f41f059802868002758457ff4baaed5f870030c9642f68d46c0f244060028a5f8807318bfb0470021a5f8b013c5f8ac13c5f8681185f8661185f86411d5f86c01c5f8601185f86511c5f86c11c5f80013a5f86c1320b148f2a351c0f245018847d5f87802002818bf04f02df90024c5f87842d5f8680320b148f2a351c0f245018847c5f86843a5f86c43286ca5f8444040b1b047286c06f166018847002804bf002028644bf63940c0f251008047d9f800400320cff680702040b0f1005fbff35f8f2ad12068584527d194f877010027c4f8807188b149f25962c0f25902002044f2436184f8777190474ef6e378c0f25a08c04708f1bc008047d4f8840184f8707150b1b047d4f8840106f166018847002804bf0020c4f88401d9f800000321cff680710140b1f1005fbff35f8f40f00a860168594540f0068690f8a811002900f0fb8506f0c9fb00f0fdbd152c00f06b811Line truncated
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf80b5002a18bf10f0030301d186460ce000f1010c864600bf013a0ef8011b04d01cf003030cf1010cf6d1102a11d35ffa81fc4ff001330cfb03fc00bf103acef80cc0cef808c0cef804c04ef810cb0f2af4d8042a0bd35ffa81fc4ff001330cfb03fc00bf043a032a4ef804cbfad8002a08bf80bdaef10103013a03f8011ffbd180bd00bf2de9f04fc1b04ff62c484ef66c694ff29c5b1446cff6ff78ccf2ff09c2f2290b4ff6ff75002701260993cde90a0106e048f2a351c0f24501bff32f8f8847dbf800a0bff35f8fdbf800000321cff680710140b1f1005fbff35f8f03d10168494500f0ba804ff4757007f0b8fa002800f0078241464218463182f8d47382f8d57382f8d67382f8d77382f8d87382f8d97382f8da7382f8db7382f8dc7382f8dd7382f8de7382f8df7382f8e07382f8e17382f8e27382f8e37382f8e47382f8e57382f8e67382f8e77382f8e87382f8e97382f8ea7382f8eb7382f8ec7382f8ed7382f8ee7382f8ef7382f8f07382f8f17382f8f27382f8f37382f8f47382f8f57382f8f67382f8f77382f8f87382f8f97382f8fa7382f8fb7382f8fc7382f8fd7382f8fe7382f8ff7382f8007482f8017482f8027482f8037482f8047482f8057482f8067482f8077482f8087482f8097482f80a7482f80b7482f80c7482f80d7482f80e7482f80f7482f8107482f8117482f8127482f8137482f8147482f8157482f8167482f8177482f8187482f819747ff470afc0f8009086728583c583058445848584c584058545858585c585058645868586c586058745875be8001f51457ff436afbff35f8f4be8000121b15be8001f5145f8d02be70b99012641ea04410024c0f8701206e048f2a351c0f24501bff32f8f8847dbf80070bff35f8fdbf800000321cff680710140b1f1005fbff35f8f03d10168494500f0ba804ff4757007f0dcf9002800f02b8141464218463182f8d44382f8d54382f8d64382f8d74382f8d84382f8d94382f8da4382f8db4382f8dc4382f8dd4382f8de4382f8df4382f8e04382f8e14382f8e24382f8e34382f8e44382f8e54382f8e64382f8e74382f8e84382f8e94382f8ea4382f8eb4382f8ec4382f8ed4382f8ee4382f8ef4382f8f04382f8f14382f8f24382f8f34382f8f44382f8f54382f8f64382f8f74382f8f84382f8f94382f8fa4382f8fb4382f8fc4382f8fd4382f8fe4382f8ff4382f8004482f8014482f8024482f8034482f8044482f8054482f8064482f8074482f8084482f8094482f80a4482f80b4482f80c4482f80d4482f80e4482f80f4482f8104482f8114482f8124482f8134482f8144482f8154482f8164482f8174482f8184482f819447ff470afc0f8009086728583c583058445848584c584058545858585c585058645868586c586058745875be8001fb9427ff436afbff35f8f4be8000121b15be8001fb942f8d02be7d0f874a242f6f766c0f24406baf1000fbff35f8f4ad006f19a0250464ff0ff314ff0ff379047002840f09d810b98002861d00a980778a7f1170002285bd80b980c2840f086810a9e7078b178084300f08081f0780138022800f27b81b279f379747a42ea0322337a307942ea0342717942ea0463b27af67a192f42ea062200f01082172f40f02682002a40f06281fe2800f06d86812800f06086002840f0738651ea030040f0558100f0bdbe04460020b047e8b104f51d7151e800afbaf1000f0cd1bff35f8f00bf41e80002002a00f0f58051e800afbaf1000ff5d00021bff32f8f0029bff35f8f00f0e480824692e74ff0ff3737e147f6df40c0f24f008047002701240d97adf8387006e048f2a351c0f24501bff32f8f8847dbf80060bff35f8fdbf800000321cff680710140b1f1005fbff35f8f03d10168494500f0c1804ff4757007f082f8002800f0b98041464218463182f8d47382f8d57382f8d67382f8d77382f8d87382f8d97382f8da7382f8db7382f8dc7382f8dd7382f8de7382f8df7382f8e07382f8e17382f8e27382f8e37382f8e47382f8e57382f8e67382f8e77382f8e87382f8e97382f8ea7382f8eb7382f8ec7382f8ed7382f8ee7382f8ef7382f8f07382f8f17382f8f27382f8f37382f8f47382f8f57382f8f67382f8f77382f8f87382f8f97382f8fa7382f8fb7382f8fc7382f8fd7382f8fe7382f8ff7382f8007482f8017482f8027482f8037482f8047482f8057482f8067482f8077482f8087482f8097482f80a7482f80b7482f80c7482f80d7482f80e7482f80f7482f8107482f8117482f8127482f8137482f8147482f8157482f8167482f8177482f8187482f819747ff470afc0f8009084728583c583058445848584c584058545858585c585058645868586c586058745875be8001fb1427ff436afbff35f8f4be8000159b15be8001fb142f8d02be706f5a9718847ace6012110e700200a9999b10b9a8ab1097801f07f02b2f10b0618bf0126b2f11c0718bf01278a2924dc0b2926d01c2924d03fe009900ca804f0a9fa4ff0ff3701249df8390000280ca818bf4ff0ff3704f0e5fb054644b99df8380028b94af21f30c0f247004c3080470998002818bfc56013e09c2901d08b291bd160b14af21f31c0f247010446884794f8641119b994f80413204669b14ff0ff3742f6f760c0f2440000f5807150468847384641b0bde8f08f09900ca806ea070404f067fa0a98017801f07f061e2e04d10b9908f088fb0746b5e71d2e01f07e0018bf1a2811d1dbf800100322cff680720a40b2f1005fbff35f8f0ad10a684a4504bf002281f8812303e0a6f115010129e9d90f2e0adc092e00f37381052e00f0ef82072e40f01c8300279ae0142e00f32182102e00f0eb82112e40f011830b98022841f0c6800a9908781Line truncated
"desc": "append injected blobs to main-app payload"
},
{
"offset": 779123,
"old": "805a3900",
"new": "384f3a00",
"new": "c86a3a00",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 152,
"old": "005b3900",
"new": "b84f3a00",
"new": "486b3a00",
"desc": "main-app TOC entry size (ps + 128)"
},
{
"offset": 779243,
"old": "805a3904",
"new": "384f3a04",
"new": "c86a3a04",
"desc": "main-app preamble length (low 24 bits)"
},
{
"offset": 779247,
"old": "effdbcea",
"new": "9218d6af",
"new": "0d513b79",
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 156,
"old": "c0c6322a",
"new": "3ef62aed",
"new": "ca6f630a",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
"offset": 779127,
"old": "c0c6322a",
"new": "3ef62aed",
"new": "ca6f630a",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
+18 -9
View File
@@ -44,7 +44,7 @@ import { TextViewerLayer } from '../apps/files/text-viewer'
import { shell, rawInputEventToInputEvent, type ShellWindow } from '../ui/shell/shell'
import { appViewportRect, SIDEBAR_WIDTH, sidebarStripVisible } from '../ui/shell/geometry'
import { DISPLAY_MODE_VALUES, displayModeLabel, displayModeSetting, onAnySettingChanged,
previewColorSetting, lockScreenEnabledSetting, brightnessSetting, brightnessSettingToLevel } from '../ui/dashboard-settings'
previewColorSetting, lockScreenEnabledSetting, getBrightnessPreferences } from '../ui/dashboard-settings'
import type { PhoneGesture } from '../phone-ui/phone-gestures'
import { isWelcomeSoundPending, setWelcomeSoundPending } from '../phone-ui/onboarding-state'
import { findSoundEffect, playSoundEffect } from '../ui/sound-effects'
@@ -332,11 +332,11 @@ export class IosPreviewController {
private pushBrightness(): void {
const communicator = this.communicator
if (!communicator || this.state.phase !== 'connected') { this.lastBrightness = null; return }
const value = brightnessSetting.get()
const preferences = getBrightnessPreferences()
const value = JSON.stringify(preferences)
if (value === this.lastBrightness) return
this.lastBrightness = value
const level = brightnessSettingToLevel(value)
void communicator.setBrightness(level === null, level ?? 0).catch(error => {
void communicator.configureBrightness(preferences).catch(error => {
this.lastBrightness = null
this.logBluetooth(`Brightness: ${String(error)}`)
})
@@ -694,6 +694,7 @@ export class IosPreviewController {
this.displayReady = this.registerSurfaces(communicator)
await this.displayReady
this.update('connecting', 'Connecting to the glasses…')
await communicator.configureBrightness(getBrightnessPreferences())
this.startedCommunicators.add(communicator)
await communicator.start()
for (const window of shell.getWindows()) window.requestRender()
@@ -887,13 +888,21 @@ export class IosPreviewController {
if (this.glassesLocked || !this.active) return
shell.startKeyboardInput()
}
private async editSetting(setting: { editorTitle: string; inputKind?: string; get(): string; set(value: string): void }): Promise<boolean> {
private async editSetting(setting: { editorTitle: string; inputKind?: string; get(): string; set(value: string): void; validationError?(value?: string): string | null }): Promise<boolean> {
if (!this.active) { this.logBluetooth('Editing text settings requires opening Faceclaw on the phone'); return false }
const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: setting.get(), inputType: setting.inputKind, okButtonText: 'Save', cancelButtonText: 'Cancel' })
if (result.result) {
setting.set(result.text)
let draft = setting.get()
while (true) {
const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: draft, inputType: setting.inputKind, okButtonText: 'Save', cancelButtonText: 'Cancel' })
if (!result.result) return false
draft = result.text
const error = setting.validationError?.(draft)
if (error) {
await Dialogs.alert({ title: setting.editorTitle, message: error, okButtonText: 'OK' })
continue
}
setting.set(draft)
if (setting === nightscoutSiteUrlSetting || setting === nightscoutApiTokenSetting) await nightscoutBridge.refreshNow()
return true
}
return result.result
}
}
+5 -1
View File
@@ -443,11 +443,15 @@ export class FaceclawCommunicatorBridge {
await this.enqueueNativeCall(() => this.communicator.setFirmwareDebugFlagsEnabled(Boolean(enabled)));
}
/** Set lens brightness: auto (ambient sensor) or an explicit 0-100 level. */
/** Set lens brightness: Faceclaw auto or a fixed level (clamped to 2–100). */
async setBrightness(autoAdjust: boolean, level: number): Promise<void> {
await this.enqueueNativeCall(() => this.communicator.setBrightnessAutoAdjustBrightnessLevel(Boolean(autoAdjust), Math.round(level)));
}
async configureBrightness(p: { auto: boolean; level: number; minimum: number; maximum: number; curve: string; fadeMs: number }): Promise<void> {
await this.enqueueNativeCall(() => this.communicator.configureBrightnessAutoLevelMinimumMaximumCurveFadeMs(p.auto, p.level, p.minimum, p.maximum, p.curve, p.fadeMs));
}
async enableWearDetectionAndRequestState(): Promise<void> {
await this.enqueueNativeCall(() => this.communicator.enableWearDetectionAndRequestState());
}
+5 -1
View File
@@ -442,11 +442,15 @@ export class FaceclawCommunicatorBridge {
await this.enqueueJavaCall(() => this.communicator.setFirmwareDebugFlags(Boolean(enabled)));
}
/** Set lens brightness: auto (ambient sensor) or an explicit 0-100 level. */
/** Set lens brightness: Faceclaw auto or a fixed level (clamped to 2–100). */
async setBrightness(autoAdjust: boolean, level: number): Promise<void> {
await this.enqueueJavaCall(() => this.communicator.setBrightness(Boolean(autoAdjust), Math.round(level)));
}
async configureBrightness(p: { auto: boolean; level: number; minimum: number; maximum: number; curve: string; fadeMs: number }): Promise<void> {
await this.enqueueJavaCall(() => this.communicator.configureBrightness(p.auto, p.level, p.minimum, p.maximum, p.curve, p.fadeMs));
}
async enableWearDetectionAndRequestState(): Promise<void> {
await this.enqueueJavaCall(() => this.communicator.enableWearDetectionAndRequestState());
}
+1 -1
View File
@@ -102,7 +102,7 @@ export class RemoteControlsViewModel extends Observable {
const raw = typeof args.value === "number" ? args.value : Number(args.object?.value ?? NaN);
if (!Number.isFinite(raw)) return;
// The setting only has every tenth level; snap to the nearest.
const level = Math.min(100, Math.max(0, Math.round(raw / 10) * 10));
const level = Math.min(100, Math.max(2, Math.round(raw / 10) * 10));
this.lastManualBrightness = level;
const value = String(level) as BrightnessSetting;
if (brightnessSetting.get() !== value) brightnessSetting.set(value);
+1 -1
View File
@@ -43,7 +43,7 @@
</GridLayout>
<GridLayout rows="auto" columns="auto,*,auto" class="settings-row">
<Label col="0" text="☀" class="brightness-icon" verticalAlignment="center" />
<Slider col="1" width="100%" minValue="0" maxValue="100" value="{{ brightnessPercent }}" valueChange="{{ onBrightnessChange }}" isEnabled="{{ brightnessSliderEnabled }}" />
<Slider col="1" width="100%" minValue="2" maxValue="100" value="{{ brightnessPercent }}" valueChange="{{ onBrightnessChange }}" isEnabled="{{ brightnessSliderEnabled }}" />
<StackLayout col="2" orientation="horizontal" verticalAlignment="center" class="auto-toggle">
<Label text="Auto" verticalAlignment="center" />
<Switch checked="{{ brightnessAuto }}" checkedChange="{{ onBrightnessAutoChange }}" />
+51 -5
View File
@@ -1,5 +1,6 @@
import { normalizeNightscoutThreshold, type NightscoutThresholds } from "../apps/nightscout/nightscout-alerts";
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
import { DEFAULT_BRIGHTNESS_CURVE, normalizeBrightnessCurve, brightnessCurveError } from "../g2/brightness-curve";
import {
getBooleanSetting,
getStringSetting,
@@ -30,10 +31,9 @@ export type BatteryDisplayMode = "icon" | "percentage" | "stacked" | "stacked-pe
export type BatteryIndicatorVisibility = "always" | "low" | "never";
export type TimeFormat = "24h" | "12h";
export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "3m" | "never";
// "auto" lets the glasses' ambient-light sensor drive brightness; the numeric
// values are exact levels on the firmware's 0-100 scale (nonlinear: ~30 is
// dim-but-readable indoors, ~60 is bright outdoors).
export const BRIGHTNESS_VALUES = ["auto", "0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"] as const;
// Auto runs Faceclaw's light curve. Numeric values use the calibrated firmware
// scale, clamped to 2–100; 2 is also the endpoint for screen fades.
export const BRIGHTNESS_VALUES = ["auto", "2", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"] as const;
export type BrightnessSetting = (typeof BRIGHTNESS_VALUES)[number];
export type WakeWordAction = "voice-input" | "off" | "turn-screen-on";
@@ -173,6 +173,7 @@ type ConfigSettingStringOptions<TId extends string> = ConfigSettingOptions<strin
glassesEditTitle?: string;
inputKind?: "text" | "email" | "password";
normalize?: (value: string | null | undefined) => string;
validate?: (value: string) => string | null;
};
// Every string setting by id, so isolates that can only pass an id over a
@@ -189,6 +190,7 @@ export class ConfigSettingString<TId extends string = string> extends ConfigSett
readonly glassesEditTitle: string;
readonly inputKind: "text" | "email" | "password";
private readonly normalizer: (value: string | null | undefined) => string;
private readonly validator?: (value: string) => string | null;
constructor(options: ConfigSettingStringOptions<TId>) {
super(options);
@@ -196,6 +198,7 @@ export class ConfigSettingString<TId extends string = string> extends ConfigSett
this.glassesEditTitle = options.glassesEditTitle ?? `Edit ${options.label}`;
this.inputKind = options.inputKind ?? "text";
this.normalizer = options.normalize ?? ((value) => value ?? "");
this.validator = options.validate;
stringSettingsById.set(this.id, this);
}
@@ -205,9 +208,23 @@ export class ConfigSettingString<TId extends string = string> extends ConfigSett
set(value: string): string {
const normalized = this.normalizer(value);
// Preserve drafts for the editor/preview; consumers can use getValidValue().
if (this.validator) {
const candidate = this.validator(normalized) ? this.get() : normalized;
if (!this.validator(candidate)) setStringSetting(this.storageKey + ".valid", candidate);
}
setStringSetting(this.storageKey, normalized);
return normalized;
}
validationError(value = this.get()): string | null { return this.validator?.(value) ?? null; }
getValidValue(): string {
const value = this.get();
if (!this.validationError(value)) return value;
const saved = this.normalizer(getStringSetting(this.storageKey + ".valid", this.defaultValue));
return this.validationError(saved) ? this.defaultValue : saved;
}
}
@@ -321,10 +338,36 @@ export const brightnessSetting = new ConfigSettingEnum<BrightnessSetting>({
storageKey: "display.brightness",
defaultValue: "auto",
values: BRIGHTNESS_VALUES,
normalize: (value) => value === "0" ? "2" : BRIGHTNESS_VALUES.includes(value as BrightnessSetting) ? value as BrightnessSetting : "auto",
formatValue: brightnessLabel,
description: "Display brightness. Auto lets the ambient-light sensor pick the level; numbers set an exact level. After picking Auto, it may take some time to first adjust.",
description: "Auto uses Faceclaw's ambient-light curve; numbers set a fixed level. 2 is the dimmest level.",
});
const AUTO_BRIGHTNESS_LEVELS = ["2", "5", "10", "20", "25", "30", "40", "50", "60", "70", "80", "90", "100"] as const;
export const autoBrightnessMinSetting = new ConfigSettingEnum({
id: "autoBrightnessMin", label: "Auto minimum", storageKey: "display.autoBrightnessMin",
defaultValue: "20", values: AUTO_BRIGHTNESS_LEVELS,
description: "Lowest brightness Auto will select. Screen fades can still reach 2.",
});
export const autoBrightnessMaxSetting = new ConfigSettingEnum({
id: "autoBrightnessMax", label: "Auto maximum", storageKey: "display.autoBrightnessMax",
defaultValue: "100", values: AUTO_BRIGHTNESS_LEVELS,
description: "Highest brightness Auto will select. A value below the minimum uses the minimum.",
});
export const autoBrightnessCurveSetting = new ConfigSettingString({
id: "autoBrightnessCurve", label: "Auto light curve", storageKey: "display.autoBrightnessCurve",
defaultValue: DEFAULT_BRIGHTNESS_CURVE, normalize: normalizeBrightnessCurve, validate: brightnessCurveError,
description: "2–16 lux:percent pairs, separated by commas. Percent is within your minimum–maximum range. Start at 0:0, end at 100%, and increase lux without decreasing percent. Incomplete edits stay in the preview; brightness keeps using the last valid curve.",
});
const SCREEN_FADE_MS = 280;
export function getBrightnessPreferences() {
const level = brightnessSettingToLevel(brightnessSetting.get());
return { auto: level === null, level: level ?? 50,
minimum: Number(autoBrightnessMinSetting.get()), maximum: Number(autoBrightnessMaxSetting.get()),
curve: autoBrightnessCurveSetting.getValidValue(), fadeMs: SCREEN_FADE_MS };
}
export const screenTimeoutSetting = new ConfigSettingEnum<ScreenTimeoutSetting>({
id: "screen-timeout",
label: "Screen timeout",
@@ -1148,6 +1191,9 @@ export class EditTextSettingLayer implements Layer {
image.drawText(font, 22, messageTop + index * step, message[index]!, 200);
}
image.drawText(font, 22, messageTop + (message.length + 2) * step, truncateSetting(this.setting.get(), 52), 220);
const error = this.setting.validationError();
if (error) wrapText(font, error, width - 48).forEach((line, index) =>
image.drawText(font, 22, messageTop + (message.length + 4 + index) * step, line, 180));
image.drawText(font, 22, height - 24 - font.lineHeight, `${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
+18
View File
@@ -37,6 +37,9 @@ import {
assistantSkipConfirmationSetting,
batteryDisplayModeSetting,
brightnessSetting,
autoBrightnessMinSetting,
autoBrightnessMaxSetting,
autoBrightnessCurveSetting,
glassesBatteryVisibilitySetting,
phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting,
@@ -97,6 +100,7 @@ function settingsSections(): SettingsSection[] {
// Auto (ambient sensor) or an exact level; pushed to the glasses by
// the dashboard controller when changed and on each connect.
enumSettingMenuItem(brightnessSetting),
autoBrightnessMenuItem(),
enumSettingMenuItem(screenTimeoutSetting, {
onChange: () => {
shell.noteUserActivity();
@@ -261,6 +265,20 @@ function settingsSections(): SettingsSection[] {
});
}
function autoBrightnessMenuItem(): MenuItem {
return {
label: "Auto-brightness",
description: "Adjust the minimum, maximum, and ambient-light curve used by Auto brightness.",
onSelect: (ctx) => {
openSettingsSubMenu(ctx, "Auto-brightness", [
enumSettingMenuItem(autoBrightnessMinSetting),
enumSettingMenuItem(autoBrightnessMaxSetting),
textSettingMenuItem(autoBrightnessCurveSetting),
]);
},
};
}
/**
* The Display section's "Battery indicators" row: opens a modal submenu with
* the style (icon / percentage / stacked) and, per device, when its
+1 -1
View File
@@ -53,7 +53,7 @@ export class BrightnessPickerLayer implements Layer {
const level = brightnessSettingToLevel(brightnessSetting.get());
// Respect Auto if it was enabled on the phone while this dialog was open.
if (level === null) return;
const next = clamp(level + (event.type === "scroll-up" ? 10 : -10), 0, 100);
const next = clamp((level === 2 ? 0 : level) + (event.type === "scroll-up" ? 10 : -10), 2, 100);
if (next !== level) brightnessSetting.set(String(next) as BrightnessSetting);
return;
}
@@ -422,18 +422,17 @@ class BleProtocol {
}
/**
* Set the lens brightness: G2SettingPackage{commandId=1 (DeviceReceiveInfo),
* deviceReceiveInfoFromApp(3){deviceReceiveBrightness(1){autoAdjust(1),
* brightnessLevel(2)}}} on sid 0x09. brightnessLevel is 0-100 (nonlinear; 0 is
* dim-but-visible, not off). When autoAdjust is set the ambient-light sensor drives
* brightness, so the level field is omitted; otherwise the level is always encoded
* (explicit zero included) so brightnessLevel=0 reaches the wire.
* Stock settings helper (Faceclaw uses CFW mode 30). autoAdjust and
* brightnessLevel are oneof alternatives: never encode both. A level
* alone does NOT disable stock auto adjustment; it is a temporary
* manual override when auto remains enabled. Stock clamps to 2..100.
*/
@JvmStatic
fun buildSetBrightness(magic: Int, autoAdjust: Boolean, brightnessLevel: Int): ByteArray {
var brightness: MutableList<ByteArray> = ArrayList()
brightness.add(encodeVarintField(1, (if (autoAdjust) 1 else 0)))
if (!autoAdjust) {
if (autoAdjust) {
brightness.add(encodeVarintField(1, 1))
} else {
brightness.add(encodeVarintField(2, brightnessLevel))
}
return concat(
@@ -0,0 +1,102 @@
package com.faceclaw.app
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.roundToInt
/** Phone-owned policy. Firmware receives only a transient target and fade time. */
class BrightnessPolicy {
var automatic = true
private set
var fadeMs = 280
private set
var target = 40
private set
private var manual = 50
private var minimum = 20
private var maximum = 100
private var curve = parseCurve(DEFAULT_CURVE)
private var filteredLux: Double? = null
private var sampleAt = 0L
fun setMode(auto: Boolean, level: Int) {
automatic = auto
manual = level.coerceIn(2, 100)
target = if (auto) filteredLux?.let { evaluate(it) } ?: target.coerceIn(minimum, maximum) else manual
}
fun configure(auto: Boolean, level: Int, min: Int, max: Int, points: String, fade: Int) {
val parsed = parseCurve(points) // Validate before mutating the live policy.
automatic = auto
manual = level.coerceIn(2, 100)
minimum = min.coerceIn(2, 100)
maximum = max.coerceIn(minimum, 100)
curve = parsed
fadeMs = fade.coerceIn(0, 1500)
target = if (auto) filteredLux?.let { evaluate(it) } ?: target.coerceIn(minimum, maximum) else manual
}
/** Only live successful passive POLL reports count, never cached query/start reports. */
fun sample(report: ByteArray, now: Long): Boolean {
if (report.size < 24 || report[0] != 65.toByte() || report[1] != 76.toByte() ||
report[2] != 1.toByte() || report[3] != 2.toByte() || (report[4].toInt() and 11) != 11) return false
var reading = 0L
for (i in 0..3) reading = reading or ((report[6+i].toLong() and 255) shl (8*i))
val lux = reading / 10.0
val old = filteredLux
val elapsed = (now - sampleAt).coerceAtLeast(0)
filteredLux = if (old == null || elapsed > 10_000) lux else {
val seconds = if (lux > old) 0.8 else 3.0
old + (lux-old) * (1-exp(-elapsed/1000.0/seconds))
}
sampleAt = now
if (!automatic) return false
val next = evaluate(filteredLux!!)
// Compare with the last accepted target, not the previous sample, so
// gradual drift accumulates. Bounds obey the same deadband to avoid
// extra panel writes when light hovers near the minimum or maximum.
if (abs(next-target) < AUTO_CHANGE_THRESHOLD) return false
val changed = target != next
target = next
return changed
}
fun resetSamples() { filteredLux = null; sampleAt = 0 }
private fun evaluate(lux: Double): Int {
val x = ln(1+lux.coerceAtLeast(0.0))
var fraction = curve.last().second / 100
if (x <= curve.first().first) fraction = curve.first().second / 100
else for (i in 1 until curve.size) {
val (right, high) = curve[i]
if (x <= right) {
val (left, low) = curve[i-1]
fraction = (low + (high-low)*(x-left)/(right-left))/100
break
}
}
return (minimum+(maximum-minimum)*fraction).roundToInt().coerceIn(minimum, maximum)
}
companion object {
private const val AUTO_CHANGE_THRESHOLD = 5
const val DEFAULT_CURVE = "0:0,0.2:7,1.5:33,5:100"
/** Lux:percent-of-configured-range knots; interpolate in log(1+lux). */
fun parseCurve(text: String): List<Pair<Double, Double>> {
val entries = text.split(',')
require(entries.size in 2..16) { "Use 2–16 lux:percent pairs" }
val points = entries.map {
val pair = it.trim().split(':')
require(pair.size == 2) { "Expected lux:percent" }
val lux = pair[0].trim().toDouble()
val percent = pair[1].trim().toDouble()
require(lux.isFinite() && lux in 0.0..1_000_000.0 && percent.isFinite() && percent in 0.0..100.0)
ln(1+lux) to percent
}
require(points.first() == (0.0 to 0.0) && points.last().second == 100.0) { "Start at 0:0 and end at 100%" }
require(points.zipWithNext().all { (a,b) -> b.first > a.first && b.second >= a.second }) { "Lux must increase and brightness must not decrease" }
return points
}
}
}
@@ -34,5 +34,6 @@ const val CFW_MSG_DRAW_CALLS = 26
const val CFW_MSG_SET_ROOT_DISPLAY_LIST = 27
const val CFW_MSG_PRESENT = 28
const val CFW_MSG_CREATE_SURFACE = 29
const val CFW_MSG_BRIGHTNESS = 30
const val CFW_MSG_TYPE_MASK = 127
const val CFW_MSG_FLAG_LENSES_DIFFER = 128
@@ -0,0 +1,42 @@
package com.faceclaw.app
/** These functions run under the session monitor. Config survives reconnection;
* queued state and sensor freshness do not. Private commands are ordered with
* frames, so wake starts on the intended PRESENT, never on an older black frame. */
internal fun GlassesSessionCore.enqueueBrightnessLocked(frameVisible: Boolean? = null) {
if (!customFirmwareDetected || !sessionReady || !fixedLayoutCreated || shutdownRequested) return
val visible = frameVisible ?: brightnessSentVisible ?: return
val target = brightnessPolicy.target
if (brightnessSentLevel == target && brightnessSentVisible == visible) return
if (frameVisible == null && hasPendingImageLocked()) return
if (frameVisible == null && hasPendingOrInflightKindLocked("brightness-output")) return
val duration = if (brightnessSentVisible != visible) brightnessPolicy.fadeMs
else if (brightnessPolicy.automatic) 1200 else 120
val payload = byteArrayOf(CFW_MSG_BRIGHTNESS.toByte(), 1, target.toByte(),
(if (visible) 1 else 0).toByte(), duration.toByte(), (duration shr 8).toByte())
val message = messageBuilder.customMessage("brightness-output", payload,
"brightness target=$target visible=$visible fade=$duration", -1, connectionOptions.sendImagesToLeft)
message.onTimeout = MessageCallback {
brightnessSentLevel = -1
brightnessSentVisible = null
// Retry with a PRESENT even if the scene did not change during recovery.
lastEnqueuedFingerprint = ""
}
pendingMessages.addLast(message)
brightnessSentLevel = target
brightnessSentVisible = visible
}
internal fun GlassesSessionCore.maintainBrightnessLocked(now: Long) {
if (!customFirmwareDetected || !sessionReady || !fixedLayoutCreated || shutdownRequested) return
// Passive polling owns stock ALS even in manual mode. Slower manual polling
// keeps stock from writing the panel without needlessly streaming samples.
if (now - brightnessAlsStartedAt >= 2000 && !hasPendingOrInflightKindLocked("als-control")) {
val interval = if (brightnessDemoPolling) 250 else if (brightnessPolicy.automatic) 500 else 5000
val payload = byteArrayOf(CFW_MSG_AMBIENT_LIGHT.toByte(), 1, 1,
interval.toByte(), (interval shr 8).toByte(), 0, 0, 0xe8.toByte(), 3)
enqueueAmbientLightControlLocked(payload, "brightness passive ALS", false)
brightnessAlsStartedAt = now
}
enqueueBrightnessLocked()
}
@@ -183,6 +183,11 @@ class GlassesSessionCore(
* needed here.
*/
internal var customFirmwareDetected = false
internal val brightnessPolicy = BrightnessPolicy()
internal var brightnessSentVisible: Boolean? = null
internal var brightnessSentLevel = -1
internal var brightnessAlsStartedAt = -2000L
internal var brightnessDemoPolling = false
internal var cfwCleanupDelivered = false
internal var lastCfwCleanupAckMagic = 0
@@ -612,28 +617,19 @@ class GlassesSessionCore(
interruptibleSleep.interrupt()
}
/**
* Set the lens brightness. Fire-and-forget, like the IMU control: the
* message is queued ahead of other traffic and any not-yet-sent brightness
* message is superseded. When autoAdjust is true the ambient-light sensor
* drives brightness and brightnessLevel is ignored; otherwise
* brightnessLevel (0-100) is applied directly.
*/
/** Update desired brightness; retained before readiness and across reconnect. */
fun setBrightness(autoAdjust: Boolean, brightnessLevel: Int) {
monitor.withLock {
if (!running || !sessionReady) {
logLine("skip brightness set; session not ready")
return
}
clearMessagesOfKindLocked("brightness-control")
val message = messageBuilder.setBrightness(autoAdjust, brightnessLevel)
message.onTimeout = MessageCallback { logLine("brightness control ack timeout") }
pendingMessages.addFirst(message)
logLine("queue brightness " + (if (autoAdjust) "auto" else "level=$brightnessLevel"))
brightnessPolicy.setMode(autoAdjust, brightnessLevel)
}
interruptibleSleep.interrupt()
}
fun configureBrightness(auto: Boolean, level: Int, minimum: Int, maximum: Int, curve: String, fadeMs: Int) {
monitor.withLock { brightnessPolicy.configure(auto, level, minimum, maximum, curve, fadeMs) }
interruptibleSleep.interrupt()
}
/**
* Enable the stock wear detector, then ask CFW to emit its current cached
* state. The queue order matters: the query must run after the setting is
@@ -798,6 +794,13 @@ class GlassesSessionCore(
*/
fun setAmbientLightPolling(enable: Boolean, intervalMs: Int, minDelta: Int,
heartbeatMs: Int, bindToLease: Boolean) {
// The brightness controller owns passive mode throughout a CFW session.
// The demo can request faster samples without releasing that ownership.
if (customFirmwareDetected) {
monitor.withLock { brightnessDemoPolling = enable; brightnessAlsStartedAt = -2000 }
interruptibleSleep.interrupt()
return
}
val payload = if (enable)
byteArrayOf(
CFW_MSG_AMBIENT_LIGHT.toByte(),
@@ -1467,6 +1470,7 @@ class GlassesSessionCore(
// CFW ambient-light report (field 105) from the master temple.
val alsReport = BleProtocol.parseFaceclawAlsReport(frame.pb)
if (alsReport != null) {
if (address.equals(rightAddress, ignoreCase = true)) brightnessPolicy.sample(alsReport, now())
emitAmbientLight(alsReport)
}
}
@@ -169,6 +169,7 @@ internal fun GlassesSessionCore.driveSession(): Long {
if (benchmarkActive) {
maintainBenchmarkLocked(now)
}
if (!benchmarkActive) maintainBrightnessLocked(now)
// Up to WINDOW_SIZE messages may be in flight at once (full
// pipelining); a slot frees when an ack arrives. An active
@@ -582,6 +583,10 @@ internal fun GlassesSessionCore.logImageUpdateLandmarkLocked(event: String, mess
}
internal fun GlassesSessionCore.enqueueCreateLayoutLocked() {
brightnessSentVisible = null
brightnessSentLevel = -1
brightnessAlsStartedAt = -2000
brightnessPolicy.resetSamples()
// New session: re-assert the firmware-debug-flags overlay once
// the layout is ready (the mode-7 send is gated on this having reset).
firmwareDebugFlagsLastSent = -1
@@ -705,7 +710,7 @@ internal fun GlassesSessionCore.enqueueAmbientLightControlLocked(payload: ByteAr
}
internal fun GlassesSessionCore.enqueueDesiredImageLocked() {
val fingerprint = desiredFingerprintSnapshot()
val fingerprint: String
val packedSnapshot: ByteArray?
val width: Int
val height: Int
@@ -714,6 +719,7 @@ internal fun GlassesSessionCore.enqueueDesiredImageLocked() {
val draws: Array<SurfaceCompositor.ScreenDraw>?
val scene: ShellScene
desiredTilesLock.locked {
fingerprint = desiredFingerprint
packedSnapshot = desiredPacked
width = desiredWidth
height = desiredHeight
@@ -724,6 +730,8 @@ internal fun GlassesSessionCore.enqueueDesiredImageLocked() {
desiredFrameId = 0
}
val packedFrame: ByteArray = packedSnapshot ?: ByteArray(0)
// Visibility belongs to this immutable composite, not the latest UI request.
enqueueBrightnessLocked(!fingerprint.startsWith("blanked:"))
if (customFirmwareDetected && packedFrame.size > 0) {
val rendered = scenePlanner.plan(packedFrame, width, height, draws, scene, nextImageFrameId,
connectionOptions.TEXTURE_CACHE_FRAMES, connectionOptions.INCREMENTAL_FRAMES,
@@ -1195,6 +1203,9 @@ internal fun GlassesSessionCore.clearMessagesOfKindLocked(kind: String) {
}
internal fun GlassesSessionCore.clearAllMessagesLocked(reason: String) {
brightnessSentVisible = null
brightnessSentLevel = -1
brightnessAlsStartedAt = -2000
clearPendingMessagesLocked(reason)
clearInFlightMessagesLocked(reason)
// The image pipeline is gone: drop the pipelined delta base so the next
@@ -1213,6 +1224,9 @@ internal fun GlassesSessionCore.clearAllMessagesLocked(reason: String) {
* direct prelude write.
*/
internal fun GlassesSessionCore.clearAllMessagesPreservingWakeLeaseLocked(reason: String) {
brightnessSentVisible = null
brightnessSentLevel = -1
brightnessAlsStartedAt = -2000
val pendingIterator = pendingMessages.iterator()
while (pendingIterator.hasNext()) {
val message = pendingIterator.next()
@@ -147,6 +147,8 @@ class IosGlassesSession internal constructor(
fun setCompassEnabledForOwner(owner: String?, enable: Boolean) = core.setCompassEnabled(owner, enable)
fun setBrightness(autoAdjust: Boolean, brightnessLevel: Int) = core.setBrightness(autoAdjust, brightnessLevel)
fun configureBrightness(auto: Boolean, level: Int, minimum: Int, maximum: Int, curve: String, fadeMs: Int) =
core.configureBrightness(auto, level, minimum, maximum, curve, fadeMs)
fun enableWearDetectionAndRequestState() = core.enableWearDetectionAndRequestState()
+53
View File
@@ -0,0 +1,53 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { normalizeBrightnessCurve, brightnessCurveError, DEFAULT_BRIGHTNESS_CURVE } = require('../.test-build/app/g2/brightness-curve.js');
test('brightness curve accepts monotone knots and canonicalizes spacing', () => {
assert.equal(normalizeBrightnessCurve(' 0:0, 2.5:20,1000:100 '), '0:0,2.5:20,1000:100');
});
test('invalid brightness drafts survive editing and report an error', () => {
for (const text of ['', '0:0', '1:0,100:100', '0:0,1:80,2:50,3:100', '0:0,0:100', '0:0,NaN:100', '0:0,1:99', '0:0,1e9:100', ':0,1:100']) {
assert.equal(normalizeBrightnessCurve(text), text);
assert.ok(brightnessCurveError(text), text);
}
});
test('only the previous default migrates to the calibrated curve', () => {
assert.equal(normalizeBrightnessCurve('0:0,1:10,10:30,100:65,1000:100'), DEFAULT_BRIGHTNESS_CURVE);
assert.equal(normalizeBrightnessCurve('0:0,3:50,10:100'), '0:0,3:50,10:100');
});
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
function settingsFixture(store = new Map()) {
const context = { exports: {}, global: { isIOS: false }, require: id => {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {}, getStringSetting: (k, d) => store.get(k) ?? d,
setStringSetting: (k, v) => store.set(k, v),
};
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
}};
vm.runInNewContext(ts.transpileModule(fs.readFileSync('app/ui/dashboard-settings.ts', 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
test('auto minimum defaults to 20 and preserves a saved preference', () => {
assert.equal(settingsFixture().getBrightnessPreferences().minimum, 20);
assert.equal(settingsFixture(new Map([['display.autoBrightnessMin', '25']])).getBrightnessPreferences().minimum, 25);
});
test('curve drafts preview exactly while brightness keeps the previous valid saved curve', () => {
const store = new Map([['display.autoBrightnessCurve', '0:0,2:50,8:100']]);
let api = settingsFixture(store), curve = api.autoBrightnessCurveSetting;
assert.equal(api.getBrightnessPreferences().minimum, 20);
curve.set('0:0,2:50,8:');
assert.equal(curve.get(), '0:0,2:50,8:');
assert.ok(curve.validationError());
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
// Restart keeps the draft and the last accepted curve separate.
api = settingsFixture(store); curve = api.autoBrightnessCurveSetting;
assert.equal(curve.get(), '0:0,2:50,8:');
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
curve.set('0:0,2:50,6:100');
assert.equal(curve.validationError(), null);
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,6:100');
});
+2 -2
View File
@@ -66,9 +66,9 @@ test('swipes change the saved level by 10, clamp at both ends, and both tap gest
await f.input('click'); assert.ok(f.stack.isAtBase()); assert.equal(f.closed(), 1);
f.open();
for (let i = 0; i < 12; i++) await f.input('scroll-down');
assert.equal(f.value(), '0'); assert.equal(f.writes(), 17);
assert.equal(f.value(), '2'); assert.equal(f.writes(), 17);
await f.input('double-click'); assert.ok(f.stack.isAtBase()); assert.equal(f.closed(), 2);
assert.equal(f.value(), '0');
assert.equal(f.value(), '2');
});
test('enabling Auto while the picker is open prevents manual changes', async () => {
+17 -2
View File
@@ -229,7 +229,7 @@ test('background glasses input still composites frames; phone resume preserves t
async start() { starts++; this.phase = 'connected'; this.stateListener({ phase: 'connected', status: 'Connected.' }); }
async disconnect() { stops++; this.phase = 'disconnected'; this.stateListener({ phase: 'disconnected', status: 'Disconnected.' }); }
async close() {}
async setBrightness() {} async enableWearDetectionAndRequestState() {}
async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {}
async configureCompositorScreen() {} async configureSurface() {} async setUnderlayDim() {} async setSurfaceVisible() {}
async setScreenBlanked() {} async removeSurface() {}
async submitSurfaceFrame(_id, pixels) { if (this.phase === 'connected') frames.push(pixels); }
@@ -245,7 +245,7 @@ test('background glasses input still composites frames; phone resume preserves t
waitForFrameFinished() { return Promise.resolve('composited'); }
getCompositePreview() { return new Uint8Array([1, 2]); }
}
const settings = { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, lockScreenEnabledSetting: { get: () => true }, onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const settings = { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => true }, onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const modules = {
"../ui/input-monitor": load("app/ui/input-monitor.ts", {}),
'../remote/service': { startRemoteInput() {} },
@@ -498,3 +498,18 @@ test('iOS keyboard action opens the shared destination session and remains block
host.glassesLocked = true; host.typeIntoApp(); assert.equal(opened, 1);
host.glassesLocked = false; host.active = false; host.typeIntoApp(); assert.equal(opened, 1);
});
test('iOS curve editor retains invalid draft and retries Save with a validation message', async () => {
const prompts = [], errors = [], saved = [];
const answers = [{ result: true, text: '0:0,5:' }, { result: true, text: '0:0,5:100' }];
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => id === '@nativescript/core'
? { Dialogs: { prompt: async options => { prompts.push(options.defaultText); return answers.shift(); }, alert: async options => errors.push(options.message) } }
: {} });
const host = Object.create(IosPreviewController.prototype); host.active = true;
const curve = require('../.test-build/app/g2/brightness-curve.js');
assert.equal(await host.editSetting({ editorTitle: 'Auto light curve', get: () => '0:0,8:100',
set: value => saved.push(value), validationError: curve.brightnessCurveError }), true);
assert.deepEqual(prompts, ['0:0,8:100', '0:0,5:']);
assert.equal(errors.length, 1);
assert.deepEqual(saved, ['0:0,5:100']);
});
+2 -2
View File
@@ -86,7 +86,7 @@ function fixture() {
onWearState(fn) { return this.on('wear', fn); } onBatteryState() { return noop(); } onFirmwareInfo() { return noop(); }
onFrameMetrics() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
async writeRawToRight() {} async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
emitState(phase, status = phase) { if (phase === 'connected' || phase === 'disconnected') this.phase = phase; this.listeners.state?.({ phase, status }); }
emitRing(input) { this.listeners.ring?.(input); }
emitWear(wearing) { this.listeners.wear?.(wearing); }
@@ -131,7 +131,7 @@ function fixture() {
'../phone-ui/onboarding-state': { isWelcomeSoundPending: () => false },
'../ui/sound-effects': {},
'../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {},
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, lockScreenEnabledSetting: { get: () => settings.lock }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../apps/ios-availability': { iosAppUnavailableReason: () => null },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
@@ -0,0 +1,108 @@
package com.faceclaw.app
import kotlin.test.*
class BrightnessPolicyTest {
private fun report(lux: Int, reason: Int = 2, flags: Int = 11): ByteArray {
val b = ByteArray(24)
b[0] = 65; b[1] = 76; b[2] = 1; b[3] = reason.toByte(); b[4] = flags.toByte()
val raw = lux * 10
for (i in 0..3) b[6+i] = (raw ushr (8*i)).toByte()
return b
}
@Test fun defaultMatchesMeasuredLightingPreferences() {
val p = BrightnessPolicy()
for ((raw, expected) in listOf(0 to 20, 2 to 26, 15 to 46, 50 to 100, 500 to 100)) {
val b = report(0)
b[6] = raw.toByte(); b[7] = (raw shr 8).toByte()
p.resetSamples(); p.sample(b, 1000)
assertEquals(expected, p.target, "raw ALS=$raw")
}
}
@Test fun curveUsesConfiguredBoundsAndLogInterpolation() {
val p = BrightnessPolicy()
p.configure(true, 50, 10, 90, "0:0,99:100", 280)
p.sample(report(9), 1000)
assertEquals(50, p.target) // log(10) / log(100) = 1/2
p.resetSamples(); p.sample(report(0), 2000); assertEquals(10, p.target)
p.resetSamples(); p.sample(report(10000), 3000); assertEquals(90, p.target)
}
@Test fun onlySuccessfulPassivePollsDriveAuto() {
val p = BrightnessPolicy()
val initial = p.target
for (reason in listOf(0, 1, 3, 4)) assertFalse(p.sample(report(0, reason), 1000))
for (flags in listOf(0, 1, 3, 9, 10)) assertFalse(p.sample(report(0, flags = flags), 1000))
assertFalse(p.sample(byteArrayOf(), 1000))
assertEquals(initial, p.target)
assertTrue(p.sample(report(0), 1000)); assertEquals(20, p.target)
}
@Test fun manualPersistsAcrossSamplesAndModeChangesUseLatestLight() {
val p = BrightnessPolicy()
p.configure(false, 70, 2, 80, "0:0,100:100", 450)
p.sample(report(100), 1000); assertEquals(70, p.target)
p.setMode(true, 50); assertEquals(80, p.target)
p.setMode(false, 0); assertEquals(2, p.target)
assertEquals(450, p.fadeMs)
}
@Test fun brightensFasterThanItDimsAndResetsStaleSamples() {
val up = BrightnessPolicy(); val down = BrightnessPolicy()
for (p in listOf(up, down)) p.configure(true, 50, 2, 100, "0:0,100:100", 280)
up.sample(report(0), 1000); up.sample(report(100), 1500)
down.sample(report(100), 1000); down.sample(report(0), 1500)
assertTrue(up.target - 2 > 100 - down.target)
down.sample(report(0), 20000); assertEquals(2, down.target)
}
@Test fun autoHoldsSmallChangesUntilTheyAccumulateToFivePoints() {
val p = BrightnessPolicy()
p.configure(true, 50, 20, 40, "0:0,1:20,2:25,3:45,4:50,5:100", 280)
var now = 1000L
fun sample(lux: Int, changed: Boolean, target: Int) {
// Space readings beyond the smoothing window to isolate the deadband.
now += 11000
assertEquals(changed, p.sample(report(lux), now), "lux=$lux")
assertEquals(target, p.target, "lux=$lux")
}
sample(0, true, 20)
repeat(5) { sample(1, false, 20) } // Desired 24 stays suppressed.
sample(2, true, 25) // Exact five-point increase is accepted.
sample(3, false, 25) // Desired 29.
sample(4, true, 30)
sample(2, true, 25) // Exact five-point decrease is accepted too.
sample(1, false, 25)
sample(0, true, 20)
}
@Test fun boundsDoNotBypassDeadbandButExplicitChangesDo() {
for ((initial, lux) in listOf(24 to 0, 36 to 5)) {
val p = BrightnessPolicy()
p.configure(false, initial, 20, 40, "0:0,5:100", 280)
p.setMode(true, initial)
assertFalse(p.sample(report(lux), 1000))
assertEquals(initial, p.target)
p.setMode(false, initial + 1)
assertEquals(initial + 1, p.target) // Small manual changes remain exact.
p.setMode(true, initial)
assertEquals(if (lux == 0) 20 else 40, p.target)
}
val p = BrightnessPolicy()
p.sample(report(0), 1000)
p.configure(true, 50, 21, 100, BrightnessPolicy.DEFAULT_CURVE, 280)
assertEquals(21, p.target) // An explicit bounds edit applies immediately.
}
@Test fun invalidCurveDoesNotPartiallyChangeLivePolicy() {
val p = BrightnessPolicy()
for (curve in listOf("", "0:0", "1:0,100:100", "0:0,1:80,2:50,3:100", "0:0,0:100", "0:0,NaN:100", "0:0,1:99")) {
assertFailsWith<IllegalArgumentException> { p.configure(false, 90, 20, 80, curve, 0) }
assertTrue(p.automatic); assertEquals(280, p.fadeMs)
}
p.configure(true, 50, 80, 20, "0:0,100:100", 0)
p.sample(report(0), 1000); assertEquals(80, p.target)
}
}
@@ -262,6 +262,42 @@ private class Session {
}
class GlassesSessionCoreTest {
@Test fun brightnessConfigPrecedesFirstFrameAndSleepWakeFollowsComposites() {
val s = Session()
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
s.core.configureCompositorScreen(640, 480)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.startAndAwaitLayout()
s.core.monitor.withLock { s.core.customFirmwareDetected = true }
try {
s.submitFrame(1, 0x70, 1)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() })
fun outputs() = s.link.writes.filter { it.address == LEFT && it.kind == "brightness-output" }
assertTrue(waitUntil(5000) { outputs().isNotEmpty() })
val first = outputs().first().message!!
assertContentEquals(byteArrayOf(30, 1, 70, 1, 24, 1), first)
val writes = s.link.writes.filter { it.address == LEFT }
assertTrue(writes.indexOfFirst { it.kind == "als-control" } < writes.indexOfFirst { it.kind == "brightness-output" })
assertTrue(writes.indexOfFirst { it.kind == "brightness-output" } < writes.indexOfFirst { it.message?.firstOrNull() == 28.toByte() })
s.core.setScreenBlanked(true)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 0.toByte() })
s.core.setScreenBlanked(false)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 1.toByte() })
// The ordered CFW window may replay accepted commands; those must
// retain the same brightness and visibility, without an extra toggle.
val visibility = outputs().map { it.message!![3].toInt() }
val transitions = visibility.filterIndexed { i, v -> i == 0 || visibility[i-1] != v }
assertEquals(listOf(1, 0, 1), transitions)
assertTrue(outputs().all { it.message!![2] == 70.toByte() })
// The demo cannot restore the stock adjuster while Faceclaw owns brightness.
s.core.setAmbientLightPolling(false, 250, 0, 1000, true)
s.platform.offsetMs += 3000
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5000) { s.link.writes.count { it.address == LEFT && it.kind == "als-control" } >= 2 })
assertTrue(s.link.writes.filter { it.kind == "als-control" }.all { it.message!![1] == 1.toByte() })
} finally { s.core.close() }
}
@Test
fun connectsAuthenticatesPreludesAndCreatesTheLayout() {
val s = Session()
+2 -2
View File
@@ -46,9 +46,9 @@ test('shared brightness controls snap manual levels and restore the manual value
h.model.onBrightnessAutoChange({ value: false });
assert.equal(h.brightness(), '80');
h.model.onBrightnessChange({ value: -10 });
assert.equal(h.brightness(), '0');
assert.equal(h.brightness(), '2');
h.model.onBrightnessChange({ value: NaN });
assert.equal(h.brightness(), '0');
assert.equal(h.brightness(), '2');
});
test('shared screen-size picker preserves cancellation and applies the selected mode', async () => {
+2 -1
View File
@@ -46,6 +46,7 @@
"../app/apps/evenhub/containers.ts",
"../app/apps/timer/timer-model.ts",
"../app/apps/teleprompter/script-tracker.ts",
"../app/apps/nightscout/nightscout-alerts.ts"
"../app/apps/nightscout/nightscout-alerts.ts",
"../app/g2/brightness-curve.ts"
]
}