Add "Show BLE bandwidth usage" option to developer settings

This commit is contained in:
James Babcock committed 2026-09-01 00:33:07 -07:00
1 parent 641e8e322e
commit 85508b87ca
10 files changed
+153 -2

No files matched your search

@@ -2243,6 +2243,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
return; return;
} }
long ackedAtMs = SystemClock.elapsedRealtime(); long ackedAtMs = SystemClock.elapsedRealtime();
FaceclawBleManager.recordDisplayFrameSent();
BleImageOptimizer.ImageUpdateStats stats = imageUpdateStats.remove(message.imageUpdateId); BleImageOptimizer.ImageUpdateStats stats = imageUpdateStats.remove(message.imageUpdateId);
if (stats != null && stats.firstWriteStartedAtMs > 0) { if (stats != null && stats.firstWriteStartedAtMs > 0) {
emitFrameMetrics(stats.paintMs, (int) Math.max(0, ackedAtMs - stats.firstWriteStartedAtMs), stats.tileCount); emitFrameMetrics(stats.paintMs, (int) Math.max(0, ackedAtMs - stats.firstWriteStartedAtMs), stats.tileCount);
@@ -21,6 +21,7 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
@SuppressLint("MissingPermission") @SuppressLint("MissingPermission")
public class FaceclawBleManager { public class FaceclawBleManager {
@@ -51,6 +52,23 @@ public class FaceclawBleManager {
private volatile FaceclawBleListener listener; private volatile FaceclawBleListener listener;
// Process-wide outbound-traffic totals, sampled by the phone UI's BLE
// bandwidth indicator. Static so counts from every manager instance and
// isolate land in the same totals.
private static final AtomicLong outboundMessages = new AtomicLong();
private static final AtomicLong outboundBytes = new AtomicLong();
private static final AtomicLong displayFramesSent = new AtomicLong();
/** Called by the communicator when a display frame's last message is acked. */
public static void recordDisplayFrameSent() {
displayFramesSent.incrementAndGet();
}
/** Running totals of outbound BLE traffic since process start: [messages, bytes, display frames]. */
public static long[] sampleOutboundTraffic() {
return new long[] { outboundMessages.get(), outboundBytes.get(), displayFramesSent.get() };
}
public FaceclawBleManager(Context context) { public FaceclawBleManager(Context context) {
this.context = context.getApplicationContext(); this.context = context.getApplicationContext();
BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE); BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE);
@@ -250,8 +268,10 @@ public class FaceclawBleManager {
if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) { if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) {
return false; return false;
} }
outboundBytes.addAndGet(frame != null ? frame.length : 0);
} }
} }
outboundMessages.incrementAndGet();
int totalSize = frames.stream().mapToInt(frame -> frame != null ? frame.length : 0).sum(); int totalSize = frames.stream().mapToInt(frame -> frame != null ? frame.length : 0).sum();
Log.i(TAG, "writeFrames wrote " + frames.size() + " frames totaling " + totalSize + " bytes in " + (System.currentTimeMillis() - startMs) + "ms"); Log.i(TAG, "writeFrames wrote " + frames.size() + " frames totaling " + totalSize + " bytes in " + (System.currentTimeMillis() - startMs) + "ms");
return true; return true;
+1
View File
@@ -5,6 +5,7 @@
* Add support for the short-then-long-press gesture * Add support for the short-then-long-press gesture
* Update EvenHub compatibility layer to include new functions from 0.0.14 * Update EvenHub compatibility layer to include new functions from 0.0.14
* EvenHub permissions dialog scrolls when it overflows * EvenHub permissions dialog scrolls when it overflows
* Add "Show BLE bandwidth usage" option to developer settings
## 0.6.2 - 2026-08-30 ## 0.6.2 - 2026-08-30
* Preview Only mode works * Preview Only mode works
+7
View File
@@ -98,6 +98,13 @@ Button.-primary {
font-size: 13; font-size: 13;
} }
/* Developer BLE-bandwidth totals overlaid on the main page's bottom edge. */
.ble-bandwidth-indicator {
color: #777777;
font-size: 12;
padding: 2 8;
}
/* /*
* Stands in for the lens preview when showing it would be misleading (silent * Stands in for the lens preview when showing it would be misleading (silent
* mode, or a disconnect explained by a flat battery). Sized by the view model * mode, or a disconnect explained by a flat battery). Sized by the view model
+1 -1
View File
@@ -71,7 +71,7 @@ const GRAVITY = 240;
const DRAG_PER_S = 0.12; const DRAG_PER_S = 0.12;
const MAX_SPEED = 600; const MAX_SPEED = 600;
const PHYSICS_DT = 1 / 120; const PHYSICS_DT = 1 / 120;
const RENDER_TICK_MS = 110; const RENDER_TICK_MS = 50;
/** Launch speed by power setting (index = power - 1). */ /** Launch speed by power setting (index = power - 1). */
const LAUNCH_SPEEDS = [320, 380, 440, 500, 560] as const; const LAUNCH_SPEEDS = [320, 380, 440, 500, 560] as const;
const BUMPER_KICK = 340; const BUMPER_KICK = 340;
+16
View File
@@ -0,0 +1,16 @@
declare const com: any;
export interface BleTrafficSample {
/** Outbound messages (writeFrames calls) since process start. */
messages: number;
/** Outbound payload bytes (sum of frame sizes) since process start. */
bytes: number;
/** Display frames whose last message was acked, since process start. */
frames: number;
}
/** Running totals of outbound BLE traffic, counted process-wide in FaceclawBleManager. */
export function sampleBleTraffic(): BleTrafficSample {
const raw = com.faceclaw.app.FaceclawBleManager.sampleOutboundTraffic();
return { messages: Number(raw[0]), bytes: Number(raw[1]), frames: Number(raw[2]) };
}
+8
View File
@@ -64,6 +64,14 @@
</StackLayout> </StackLayout>
</GridLayout> </GridLayout>
</GridLayout> </GridLayout>
<!-- Developer BLE-bandwidth indicator: overlays the bottom edge of the
page in both orientations, on every tab. -->
<Label
text="{{ bleBandwidthLabel }}"
visibility="{{ bleBandwidthVisibility }}"
class="ble-bandwidth-indicator"
horizontalAlignment="center"
verticalAlignment="bottom" />
<ScrollView <ScrollView
class="warnings-modal" class="warnings-modal"
visibility="{{ warningsModalVisibility }}" visibility="{{ warningsModalVisibility }}"
+88 -1
View File
@@ -19,9 +19,11 @@ import {
displayModeSetting, displayModeSetting,
mirrorTouchSetting, mirrorTouchSetting,
onAnySettingChanged, onAnySettingChanged,
showBleBandwidthSetting,
type BrightnessSetting, type BrightnessSetting,
type DisplayModeSetting, type DisplayModeSetting,
} from "../ui/dashboard-settings"; } from "../ui/dashboard-settings";
import { sampleBleTraffic } from "../native/ble-traffic";
import { isValidMacAddress, loadDeviceAddresses } from "../g2/device-addresses"; import { isValidMacAddress, loadDeviceAddresses } from "../g2/device-addresses";
import { isAutoReconnectSuppressed, resumeAutoReconnect } from "../g2/reconnect-policy"; import { isAutoReconnectSuppressed, resumeAutoReconnect } from "../g2/reconnect-policy";
import { formatErrorMessage } from "../util/format-error"; import { formatErrorMessage } from "../util/format-error";
@@ -111,7 +113,12 @@ export class MainViewModel extends Observable {
this.refreshPadFocusLine(); this.refreshPadFocusLine();
})); }));
// Brightness / display mode can change from the glasses' Settings app too. // Brightness / display mode can change from the glasses' Settings app too.
this.unsubscribers.push(onAnySettingChanged(() => this.refreshDisplayControls())); this.unsubscribers.push(onAnySettingChanged(() => {
this.refreshDisplayControls();
this.syncBleBandwidthPolling();
}));
this.syncBleBandwidthPolling();
this.unsubscribers.push(() => this.stopBleBandwidthPolling());
} }
/** Detach from the controller and settings; the page calls this when it lets go of the model. */ /** Detach from the controller and settings; the page calls this when it lets go of the model. */
@@ -1128,6 +1135,72 @@ export class MainViewModel extends Observable {
this.notifyPropertyChange("displayModeLabel", this.displayModeLabel); this.notifyPropertyChange("displayModeLabel", this.displayModeLabel);
} }
// ---- BLE bandwidth indicator (Settings > Developer > Show BLE bandwidth usage) ----
//
// A running total of outbound BLE messages/bytes, overlaid at the bottom of
// the page on every tab. Polled from the Java-side counters while enabled.
private _bleBandwidthLabel = "";
private bleBandwidthTimer: ReturnType<typeof setInterval> | null = null;
// Recent counter samples, one per poll tick, for the windowed rates.
private bleRateHistory: Array<{ atMs: number; bytes: number; frames: number }> = [];
get bleBandwidthVisibility(): "visible" | "collapse" {
return showBleBandwidthSetting.get() ? "visible" : "collapse";
}
get bleBandwidthLabel(): string {
return this._bleBandwidthLabel;
}
/** Start or stop the poll to match the setting; safe to call repeatedly. */
private syncBleBandwidthPolling(): void {
const enabled = showBleBandwidthSetting.get();
if (enabled && this.bleBandwidthTimer === null) {
this.refreshBleBandwidth();
this.bleBandwidthTimer = setInterval(() => this.refreshBleBandwidth(), 1000);
this.notifyPropertyChange("bleBandwidthVisibility", this.bleBandwidthVisibility);
} else if (!enabled && this.bleBandwidthTimer !== null) {
this.stopBleBandwidthPolling();
this.notifyPropertyChange("bleBandwidthVisibility", this.bleBandwidthVisibility);
}
}
private stopBleBandwidthPolling(): void {
if (this.bleBandwidthTimer !== null) {
clearInterval(this.bleBandwidthTimer);
this.bleBandwidthTimer = null;
}
// Don't let a later re-enable compute a rate across the disabled gap.
this.bleRateHistory = [];
}
private refreshBleBandwidth(): void {
let label: string;
try {
const sample = sampleBleTraffic();
const atMs = Date.now();
this.bleRateHistory.push({ atMs, bytes: sample.bytes, frames: sample.frames });
while (this.bleRateHistory.length > 0 && this.bleRateHistory[0]!.atMs < atMs - BLE_RATE_WINDOW_MS) {
this.bleRateHistory.shift();
}
label = `BLE sent: ${formatCount(sample.messages)} messages, ${formatCount(sample.bytes)} bytes`;
const oldest = this.bleRateHistory[0]!;
const elapsedSec = (atMs - oldest.atMs) / 1000;
if (elapsedSec > 0) {
const byteRate = (sample.bytes - oldest.bytes) / elapsedSec;
const frameRate = (sample.frames - oldest.frames) / elapsedSec;
label += ` · ${formatByteRate(byteRate)}, ${frameRate.toFixed(1)} fps`;
}
} catch (error) {
label = `BLE sent: ${this.formatError(error)}`;
}
if (label !== this._bleBandwidthLabel) {
this._bleBandwidthLabel = label;
this.notifyPropertyChange("bleBandwidthLabel", label);
}
}
private readLayoutOrientation(): LayoutOrientation { private readLayoutOrientation(): LayoutOrientation {
const applicationOrientation = Application.orientation(); const applicationOrientation = Application.orientation();
if (applicationOrientation === "landscape" || applicationOrientation === "portrait") { if (applicationOrientation === "landscape" || applicationOrientation === "portrait") {
@@ -1141,6 +1214,20 @@ export class MainViewModel extends Observable {
} }
} }
/** 1234567 -> "1,234,567"; kept exact rather than rounded so growth is visible at a glance. */
function formatCount(value: number): string {
return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
/** How far back the BLE bandwidth indicator's rates look. */
const BLE_RATE_WINDOW_MS = 5000;
function formatByteRate(bytesPerSec: number): string {
if (bytesPerSec >= 1e6) return (bytesPerSec / 1e6).toFixed(2) + " MB/s";
if (bytesPerSec >= 1e3) return (bytesPerSec / 1e3).toFixed(1) + " kB/s";
return Math.round(bytesPerSec) + " B/s";
}
/** NativeScript swipe direction -> the watch-scheme directional gesture. */ /** NativeScript swipe direction -> the watch-scheme directional gesture. */
function swipeKind(direction: SwipeDirection): "swipe-up" | "swipe-down" | "swipe-left" | "swipe-right" { function swipeKind(direction: SwipeDirection): "swipe-up" | "swipe-down" | "swipe-left" | "swipe-right" {
switch (direction) { switch (direction) {
+9
View File
@@ -399,6 +399,15 @@ export const useMicControlSetting = new ConfigSettingBoolean({
"Use the custom firmware's per-temple mic-control channel (caps token micctl) for the Microphones app's array capture. When off, behave as if the firmware doesn't have the feature and use the standard single mixed stream.", "Use the custom firmware's per-temple mic-control channel (caps token micctl) for the Microphones app's array capture. When off, behave as if the firmware doesn't have the feature and use the standard single mixed stream.",
}); });
export const showBleBandwidthSetting = new ConfigSettingBoolean({
id: "show-ble-bandwidth",
label: "Show BLE bandwidth usage",
storageKey: "developer.showBleBandwidth",
defaultValue: false,
description:
"Show a running total of Bluetooth messages and bytes sent, at the bottom of the phone app's main screen.",
});
export type RingConnectionMode = "glasses" | "direct"; export type RingConnectionMode = "glasses" | "direct";
export const ringConnectionModeSetting = new ConfigSettingEnum<RingConnectionMode>({ export const ringConnectionModeSetting = new ConfigSettingEnum<RingConnectionMode>({
+2
View File
@@ -47,6 +47,7 @@ import {
firmwareDebugFlagsSetting, firmwareDebugFlagsSetting,
lockScreenEnabledSetting, lockScreenEnabledSetting,
saveVoiceRecordingsSetting, saveVoiceRecordingsSetting,
showBleBandwidthSetting,
suspendEvenHubWhenScreenOffSetting, suspendEvenHubWhenScreenOffSetting,
terminalAutoReconnectSetting, terminalAutoReconnectSetting,
terminalLaunchPresetsSetting, terminalLaunchPresetsSetting,
@@ -176,6 +177,7 @@ function settingsSections(): SettingsSection[] {
toggleSettingMenuItem(firmwareDebugFlagsSetting), toggleSettingMenuItem(firmwareDebugFlagsSetting),
toggleSettingMenuItem(suspendEvenHubWhenScreenOffSetting), toggleSettingMenuItem(suspendEvenHubWhenScreenOffSetting),
toggleSettingMenuItem(useMicControlSetting), toggleSettingMenuItem(useMicControlSetting),
toggleSettingMenuItem(showBleBandwidthSetting),
], ],
}, },
{ {