File size: 33,295 Bytes
b450976 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 | import {createScanSession} from "./scanSession"
import {NativeModule, requireNativeModule} from "expo"
import {Platform} from "react-native"
import {installNativeLogConsole, installSdkUpdateNotice} from "./nativeLogConsole"
import {
BluetoothSettingsUpdate,
BluetoothSdkModuleEvents,
BluetoothStatus,
PhotoCaptureDefaults,
CalendarEvent,
CAMERA_FOV_DEFAULT,
CAMERA_FOV_MAX,
CAMERA_FOV_MIN,
CameraFovPreset,
CameraFovRequest,
CameraFovOverrideRequest,
CameraFovResult,
CameraFovSetting,
CameraRoiPosition,
CameraStatusEvent,
ConnectOptions,
DashboardMenuItem,
Device,
DeviceModel,
GlassesMediaVolumeGetResult,
GlassesMediaVolumeSetResult,
GlassesStatus,
GalleryStatusEvent,
HotspotStatusChangeEvent,
MicPreference,
NativePhoneNotification,
NativeNotificationConfig,
NativeNotificationStatus,
MicTuning,
ObservableStoreCategory,
OtaQueryResult,
OtaStartAckEvent,
PhotoRequestParams,
PhotoSuccessResponseEvent,
PublicBluetoothStatus,
RgbLedAction,
RgbLedColor,
RgbLedControlSuccessResponseEvent,
ScanDiagnostic,
ScanModelOptions,
ScanOptions,
SettingsAckSuccessEvent,
StreamStartRequest,
StreamStatusEvent,
TouchGesture,
VideoRecordingStartedStatusEvent,
VideoRecordingSettings,
VideoRecordingStoppedStatusEvent,
VideoRecordingStatusEvent,
VersionInfoResult,
WarmUpCameraParams,
SavedWifiNetworksResult,
WifiForgetResult,
WifiSearchResult,
WifiStatusChangeEvent,
} from "../BluetoothSdk.types"
import {warmUpCameraParamsForNative} from "./cameraRequestPayload"
import {photoRequestParamsForNative} from "./photoRequestPayload"
import {streamRequestParamsForNative} from "./streamRequestPayload"
/**
* Private React Native native-module facade.
*
* This file intentionally lives under `_private` so the package root can expose
* a small SDK surface while MentraOS uses its monorepo-only internal alias
* during migration. Raw status getters/listeners stay here so React hooks can
* shape native store snapshots before app code sees them.
*/
type GlassesListener = (changed: Partial<GlassesStatus>) => void
type BluetoothStatusListener = (changed: Partial<PublicBluetoothStatus>) => void
type MaybePromise<T> = T | Promise<T>
declare class BluetoothSdkNativeModule extends NativeModule<BluetoothSdkModuleEvents> {
// Observable Store Functions (native)
getGlassesStatus(): Promise<GlassesStatus>
getBluetoothStatus(): Promise<PublicBluetoothStatus>
getDefaultDevice(): Promise<Device | null>
update(category: ObservableStoreCategory, values: object): Promise<void>
// Display Commands
displayEvent(params: Record<string, unknown>): Promise<void>
displayText(text: string, x?: number, y?: number, size?: number): Promise<void>
clearDisplay(): Promise<void>
setDashboardContent(content: string): Promise<void>
// Connection Commands
requestStatus(): Promise<void>
connectDefault(options?: ConnectOptions): Promise<void>
connectDefaultWithOptions(options: Required<ConnectOptions>): Promise<void>
setDefaultDevice(device: Device | null): Promise<void>
clearDefaultDevice(): Promise<void>
/** Android only: iOS cannot read its Bluetooth bonds. */
getBondedGlasses?: () => Promise<{name: string; address: string} | null>
getScanDiagnostic?: (model: DeviceModel) => Promise<ScanDiagnostic | null>
startScan(model: DeviceModel): Promise<void>
stopScan(): Promise<void>
scan(options: ScanOptions): Promise<Device[]>
scan(model: DeviceModel, options?: ScanModelOptions): Promise<Device[]>
connect(device: Device, options?: ConnectOptions): Promise<void>
connectWithOptions(device: Device, options: Required<ConnectOptions>): Promise<void>
cancelConnectionAttempt(): Promise<void>
connectDefaultController(): Promise<void>
disconnectController(): Promise<void>
connectSimulated(): Promise<void>
disconnect(): Promise<void>
forget(): Promise<void>
/** Explicit Unpair also resets connected NIMO glasses before forgetting. */
unpair(): Promise<void>
forgetController(): Promise<void>
showDashboard(): Promise<void>
setBrightness(level: number, autoMode?: boolean | null): Promise<void>
setAutoBrightness(enabled: boolean): Promise<void>
setDashboardPosition(height: number, depth: number): Promise<void>
setDashboardMenu(items: DashboardMenuItem[]): Promise<void>
setCalendarEvents(events: CalendarEvent[]): Promise<void>
setHeadUpAngle(angleDegrees: number): Promise<void>
setImuEnabled(enabled: boolean): Promise<void>
setScreenDisabled(disabled: boolean): Promise<void>
ping(): Promise<void>
dbg1(): Promise<void>
dbg2(): Promise<void>
// Incident Reporting
sendIncidentId(incidentId: string, apiBaseUrl?: string | null): Promise<void>
/**
* Tell Mentra Live that Cloud recorded `reportId` for the BES crash incident
* `incidentKey`. Resolves only on the glasses' matching `ok:true` ack; rejects
* on `ok:false`, disconnect, or after 10 s. Call `sendIncidentId` only after it resolves.
*/
sendBesCrashReported(incidentKey: string, reportId: string): Promise<void>
// WiFi Commands
requestWifiScan(): Promise<WifiSearchResult[]>
getSavedWifiNetworks(): Promise<SavedWifiNetworksResult>
sendWifiCredentials(ssid: string, password: string): Promise<WifiStatusChangeEvent>
forgetWifiNetwork(ssid: string): Promise<WifiForgetResult>
setHotspotState(enabled: boolean): Promise<HotspotStatusChangeEvent>
/** Enable or disable Wi-Fi ADB on Mentra Live (no-op on other devices). */
setWifiAdbState(enabled: boolean, expectedBluetoothMac?: string): Promise<void>
/** Set the glasses system clock when phone detects clock skew (Mentra Live and G2). */
setSystemTime(timestampMs: number): Promise<void>
/** Logs current WiFi frequency (MHz) and 5 GHz band to Android logcat. */
logCurrentWifiFrequency(): Promise<void>
// Gallery Commands
setGalleryServerEnabled(enabled: boolean): Promise<SettingsAckSuccessEvent>
setTouchGestureDefaultBehaviorEnabled(gesture: TouchGesture, enabled: boolean): Promise<SettingsAckSuccessEvent>
setGalleryModeEnabled(enabled: boolean): Promise<SettingsAckSuccessEvent>
setVoiceActivityDetectionEnabled(enabled: boolean): Promise<void>
/** Mentra Live center-mic loudness / Barrier gate (cs_swit type 10). */
setLoudnessGateEnabled(enabled: boolean): Promise<void>
/** Mentra Live power-off after ~20 min unworn (cs_swit type 11). */
setAutoPowerOffEnabled(enabled: boolean): Promise<void>
/**
* Mentra Live mic tuning. `null` clears every override and returns the
* glasses to firmware defaults.
*
* Deliberately absent from the public SDK surface: it is a super-mode
* calibration aid whose values only make sense next to a live RMS readout.
*/
setMicTuning(tuning: MicTuning | null): Promise<void>
/**
* Ask the glasses to report the tuning they are actually running. The answer
* arrives as a `mic_tuning_state` event, which is also emitted unprompted
* after every set, so a screen that subscribes on mount and calls this on
* focus never has to guess.
*/
requestMicTuningState(): Promise<void>
/** Enable or disable the `mic_rms` readout. Auto-disabled on disconnect. */
setMicRmsTelemetry(enabled: boolean): Promise<void>
/**
* Mentra Live wear detection. Internal / Super Mode only.
*
* Reporting is RAM-only on the glasses and must not go through `cs_swit`
* type 1 (that bit is NV-backed). `resetWearTuning` both restores the
* firmware vote defaults and turns reporting off.
*/
queryWearState(): Promise<void>
setWearReporting(enabled: boolean): Promise<void>
/** Negative values leave that field unchanged. */
setWearTuning(intervalMs: number, count: number, majority: number): Promise<void>
requestWearTuning(): Promise<void>
resetWearTuning(): Promise<void>
/**
* @deprecated Sticky action-button photo presets are deprecated. Prefer per-request
* `requestPhoto(...)` options (e.g. `mode: "text"` for text sensor size/crop).
*/
setPhotoCaptureDefaults(settings: PhotoCaptureDefaults): Promise<SettingsAckSuccessEvent>
setVideoRecordingDefaults(width: number, height: number, fps: number): Promise<SettingsAckSuccessEvent>
setMaxVideoRecordingDuration(minutes: number): Promise<SettingsAckSuccessEvent>
setCameraFov(request: CameraFovRequest): Promise<CameraFovResult>
setLegacyCameraFov(request: CameraFovRequest): Promise<CameraFovResult>
restoreLegacyCameraFov(): Promise<void>
setCameraFovOverride(request: CameraFovOverrideRequest): Promise<CameraFovResult>
releaseCameraFovOverride(leaseId: string): Promise<SettingsAckSuccessEvent>
/**
* Configure camera HAL tuning (ANR / gain) on Mentra Live glasses.
* Sends a {@code camera_tuning_config} BLE message; the ASG client relays it as a
* {@code camconfig} broadcast so the HAL picks up new parameters without a reboot.
*
* Scan-mode convention: pass `{anr: false, gain: false}` when activating scan mode
* (disables ANR and pixsmart gain) and `{anr: true, gain: true}` to restore defaults.
*/
setCameraTuningConfig(anrOn: boolean, gainOn: boolean): Promise<SettingsAckSuccessEvent>
queryGalleryStatus(): Promise<GalleryStatusEvent>
requestPhoto(params: PhotoRequestParams): Promise<PhotoSuccessResponseEvent>
warmUpCamera(params: WarmUpCameraParams): Promise<CameraStatusEvent>
stopCameraWarmUp(requestId: string): Promise<void>
// OTA Commands
setOtaVersionUrl(otaVersionUrl: string): void
getOtaVersionUrl(): string
checkForOtaUpdate(): Promise<boolean>
startOtaUpdate(otaVersionUrl?: string | null): Promise<OtaStartAckEvent>
sendOtaQueryStatus(): Promise<OtaQueryResult>
startAr99OtaFromFile(path: string): Promise<boolean>
cancelAr99Ota(): Promise<void>
sendAr99FactoryReset(): Promise<void>
buildAr99OtaSignature(
secret: string,
appName: string,
currentVersion: string,
serialNumber: string,
nonce: string,
): string
// Version Info Commands
requestVersionInfo(): Promise<VersionInfoResult>
// Video Recording Commands
startVideoRecording(
requestId: string,
save: boolean,
sound: boolean,
settings?: VideoRecordingSettings,
): Promise<VideoRecordingStartedStatusEvent>
stopVideoRecording(
requestId: string,
webhookUrl?: string,
authToken?: string,
): Promise<VideoRecordingStoppedStatusEvent>
queryVideoRecordingStatus(requestId: string): Promise<VideoRecordingStatusEvent>
// Stream Commands
startStream(params: StreamStartRequest): Promise<StreamStatusEvent>
stopStream(): Promise<StreamStatusEvent>
// Microphone Commands
setMicState(enabled: boolean, useGlassesMic?: boolean, sendTranscript?: boolean, sendLc3Data?: boolean): Promise<void>
setPreferredMic(preferredMic: MicPreference): Promise<void>
/**
* Lock microphone selection to one source (`"glasses"`) until released with `null`.
*
* Stronger than [setPreferredMic]: a preference is a ranking the SDK falls through when a source
* is unavailable, while a pin has no fallback and reports `mic_health` with
* `reason: "pinned-source-unavailable"` instead. Android only; the iOS implementation is a no-op,
* so a caller that depends on the guarantee must gate on platform.
*/
setMicSourcePin(source: string | null): Promise<void>
/** See the public `setWakeWordDetection`. `modelDir` is required when enabling. */
setWakeWordDetection(enabled: boolean, modelDir?: string | null): Promise<void>
/** Whether the active recognizer has `path` loaded. Never blocks on a model load. */
isSttModelLoaded(path: string): Promise<boolean>
/** See the public `finishTranscription`. */
finishTranscription(): Promise<string | null>
/** See the public `restartTranscriber`. */
restartTranscriber(): Promise<void>
/** See the public `setSpeechActivityDetection`. */
setSpeechActivityDetection(enabled: boolean, options?: {minSilenceMs?: number}): Promise<void>
// Audio Playback Monitoring
// Notify native side when our app starts/stops playing audio
// Used to suspend LC3 mic during audio playback to avoid MCU overload
setOwnAppAudioPlaying(playing: boolean): Promise<void>
// Live PCM output stream (miniapp speaker.createStream). MentraOS-internal
// ? 16-bit LE PCM chunks into a streaming AudioTrack (USAGE_MEDIA, so it
// follows the phone's media route, e.g. A2DP to glasses). Implemented with
// AudioTrack on Android and AVAudioEngine on iOS.
/**
* Open a PCM stream session. One AudioTrack per id; caller manages ids.
*
* `jitterMs` (default 500) is how much audio is queued before playback starts, and the playout
* cushion after that. Omit it for one-way media, where the default cushion is inaudible; pass a
* small value for conversational audio, where the same cushion is delay before the far end is
* heard. Both platforms honor it: playback starts once `jitterMs` is queued or the stream is
* closed, so a sound shorter than `jitterMs` still plays.
*
* A stream that has not received audio yet is aborted when the audio route changes (Bluetooth
* or glasses connect/disconnect, a call starting or ending, an audio-session interruption), so
* its next write rejects with "stream not open" instead of playing on a stale route.
*/
pcmStreamOpen(
streamId: string,
sampleRate: number,
channels: number,
volume: number,
jitterMs?: number,
): Promise<void>
/**
* Append base64 PCM. Resolves with the queued-but-unplayed backlog in ms;
* blocks (on a background dispatcher) while the backlog is above the
* backpressure ceiling, so awaited writes self-throttle to realtime.
*/
pcmStreamWrite(streamId: string, base64: string): Promise<{bufferedMs: number}>
/** Drain the backlog, then stop. Resolves with the total played duration. */
pcmStreamClose(streamId: string): Promise<{durationMs: number}>
/** Stop immediately, dropping any backlog. Idempotent. */
pcmStreamAbort(streamId: string): Promise<void>
/**
* Fetch `url` (HTTP GET) and play its body as raw 16-bit little-endian mono PCM at `sampleRate`
* while it downloads, through the same stream player as `pcmStreamOpen`. Native code reads the
* body; audio never crosses into JavaScript. Resolves with the played duration after the whole
* body has played. Rejects on a non-2xx response or a network error (whatever already played
* stays played), and with "aborted" after `pcmStreamAbort(streamId)`. Must not block the shared
* module queue while it runs.
*/
pcmStreamPlayUrl(
streamId: string,
url: string,
sampleRate: number,
volume: number,
jitterMs?: number,
): Promise<{durationMs: number}>
/** Mentra Live only: K900 `cs_getvol` / `sr_getvol`. */
getGlassesMediaVolume(): Promise<GlassesMediaVolumeGetResult>
/** Mentra Live only: K900 `cs_vol` / `sr_vol`; level clamped 0??5 on native. */
setGlassesMediaVolume(level: number): Promise<GlassesMediaVolumeSetResult>
// RGB LED Control
rgbLedControl(
requestId: string,
packageName: string | null,
action: RgbLedAction,
color: RgbLedColor | null,
onDurationMs: number,
offDurationMs: number,
count: number,
): Promise<RgbLedControlSuccessResponseEvent>
// STT Commands
setSttModelDetails(path: string, languageCode: string): Promise<void>
getSttModelPath(): Promise<string>
checkSttModelAvailable(): Promise<boolean>
validateSttModel(path: string): Promise<boolean>
extractTarBz2(sourcePath: string, destinationPath: string): Promise<boolean>
// TTS Commands
setTtsModelDetails(path: string, languageCode: string): Promise<void>
getTtsModelPath(): Promise<string>
getTtsModelLanguage(): Promise<string>
checkTtsModelAvailable(): Promise<boolean>
validateTtsModel(path: string): Promise<boolean>
generateTtsAudio(
text: string,
modelPath: string,
outputPath: string,
speakerId: number,
speed: number,
): Promise<boolean>
/** Android G2 content upload. iOS receives ANCS directly and rejects uploads. */
sendPhoneNotification(notification: NativePhoneNotification): Promise<void>
configureNativeNotifications(config: NativeNotificationConfig): Promise<void>
getNativeNotificationStatus(): Promise<NativeNotificationStatus>
// Helper methods for type-safe observable store access
updateGlasses(values: Partial<GlassesStatus>): Promise<void>
updateBluetoothSettings(values: BluetoothSettingsUpdate): Promise<void>
onGlassesStatus(callback: GlassesListener): () => void
onBluetoothStatus(callback: BluetoothStatusListener): () => void
// Process resident-set-size in MB. iOS-only; Android stub returns 0.
getMemoryMB(): number
}
export type BluetoothSdkInternalModule = BluetoothSdkNativeModule
// This call loads the native module object from the JSI.
// NativeModule<BluetoothSdkModuleEvents> already extends EventEmitter<BluetoothSdkModuleEvents>
const NativeBluetoothSdkModule = requireNativeModule<BluetoothSdkNativeModule>("BluetoothSdk")
installNativeLogConsole(NativeBluetoothSdkModule, Platform.OS)
installSdkUpdateNotice(NativeBluetoothSdkModule)
const DEFAULT_CONNECT_OPTIONS: Required<ConnectOptions> = {
saveAsDefault: true,
cancelExistingConnectionAttempt: true,
requiresAncs: true,
enableTransportBridging: true,
}
const DEFAULT_SCAN_TIMEOUT_MS = 15_000
function bindNativeMethod<T extends (...args: never[]) => unknown>(module: Record<string, unknown>, name: string): T {
const method = module[name]
if (typeof method !== "function") {
console.warn(`[BluetoothSdk] Native method "${name}" is unavailable ??rebuild the app (bun android / bun ios)`)
return (async () => {
throw new Error(`BluetoothSdk.${name} is not available in this native build. Rebuild the app.`)
}) as T
}
return method.bind(module) as T
}
const CAMERA_ROI_MIN = 0
const CAMERA_ROI_MAX = 2
const CAMERA_ROI_POSITION_VALUES: Record<CameraRoiPosition, CameraFovSetting["roiPosition"]> = {
center: 0,
bottom: 1,
top: 2,
}
// Named presets are a convenience layer over the numeric {fov, roiPosition} API.
// The default is the full sensor; "standard" preserves the historical 102° crop.
const CAMERA_FOV_PRESETS: Record<CameraFovPreset, CameraFovSetting> = {
narrow: {fov: 82, roiPosition: 0},
standard: {fov: 102, roiPosition: 0},
wide: {fov: CAMERA_FOV_MAX, roiPosition: 0},
}
function clampInteger(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, Math.round(value)))
}
function normalizeCameraFov(request: CameraFovRequest): CameraFovSetting {
if ("preset" in request) {
return CAMERA_FOV_PRESETS[request.preset] ?? CAMERA_FOV_PRESETS.standard
}
const roiPosition = request.roiPosition ?? "center"
return {
fov: clampInteger(Number.isFinite(request.fov) ? request.fov : CAMERA_FOV_DEFAULT, CAMERA_FOV_MIN, CAMERA_FOV_MAX),
roiPosition: clampInteger(CAMERA_ROI_POSITION_VALUES[roiPosition] ?? 0, CAMERA_ROI_MIN, CAMERA_ROI_MAX) as
| 0
| 1
| 2,
}
}
function searchResultsForModel(status: Partial<PublicBluetoothStatus>, model: DeviceModel): Device[] {
return status.searchResults?.filter((device) => device.model === model) ?? []
}
function normalizeScanArgs(modelOrOptions: DeviceModel | ScanOptions, options?: ScanModelOptions): ScanOptions {
if (typeof modelOrOptions === "string") {
return {model: modelOrOptions, ...options}
}
return modelOrOptions
}
function normalizeTimeoutMs(timeoutMs: number | undefined, defaultTimeoutMs: number): number {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : defaultTimeoutMs
}
function dashboardMenuItemToNative(item: DashboardMenuItem): Record<string, unknown> {
return {
...(item.values ?? {}),
title: item.title,
packageName: item.packageName,
}
}
function adaptConnectionStatusToNative(connection: GlassesStatus["connection"]): Record<string, unknown> {
switch (connection.state) {
case "connected":
return {connectionState: "CONNECTED", connected: true, fullyBooted: connection.fullyBooted}
case "scanning":
return {connectionState: "SCANNING", connected: false, fullyBooted: false}
case "connecting":
return {connectionState: "CONNECTING", connected: false, fullyBooted: false}
case "bonding":
return {connectionState: "BONDING", connected: false, fullyBooted: false}
case "disconnected":
return {connectionState: "DISCONNECTED", connected: false, fullyBooted: false}
}
}
function adaptGlassesUpdateToNative(values: Partial<GlassesStatus>): Record<string, unknown> {
const {wifi, hotspot, connection, ...rest} = values
let update: Record<string, unknown> = {...rest}
if (connection) {
update = {
...update,
...adaptConnectionStatusToNative(connection),
}
}
if (wifi?.state === "connected") {
update = {
...update,
wifiConnected: true,
wifiSsid: wifi.ssid,
wifiLocalIp: wifi.localIp ?? "",
}
} else if (wifi?.state === "disconnected") {
update = {
...update,
wifiConnected: false,
wifiSsid: "",
wifiLocalIp: "",
}
}
if (hotspot?.state === "enabled") {
update = {
...update,
hotspotEnabled: true,
hotspotSsid: hotspot.ssid,
hotspotPassword: hotspot.password,
hotspotGatewayIp: hotspot.localIp,
}
} else if (hotspot?.state === "disabled") {
update = {
...update,
hotspotEnabled: false,
hotspotSsid: "",
hotspotPassword: "",
hotspotGatewayIp: "",
}
}
return update
}
// Add helper methods to the module
const nativeGetGlassesStatus = NativeBluetoothSdkModule.getGlassesStatus.bind(
NativeBluetoothSdkModule,
) as () => MaybePromise<GlassesStatus>
NativeBluetoothSdkModule.getGlassesStatus = function () {
return Promise.resolve(nativeGetGlassesStatus())
}
const nativeGetBluetoothStatus = NativeBluetoothSdkModule.getBluetoothStatus.bind(
NativeBluetoothSdkModule,
) as () => MaybePromise<BluetoothStatus>
NativeBluetoothSdkModule.getBluetoothStatus = function () {
return Promise.resolve(nativeGetBluetoothStatus())
}
const nativeGetDefaultDevice = NativeBluetoothSdkModule.getDefaultDevice.bind(
NativeBluetoothSdkModule,
) as () => MaybePromise<Device | null>
NativeBluetoothSdkModule.getDefaultDevice = function () {
return Promise.resolve(nativeGetDefaultDevice())
}
const nativeSetMicState = NativeBluetoothSdkModule.setMicState.bind(NativeBluetoothSdkModule) as (
enabled: boolean,
useGlassesMic: boolean,
sendTranscript: boolean,
sendLc3Data: boolean,
) => MaybePromise<void>
const nativeDisplayText = NativeBluetoothSdkModule.displayText.bind(NativeBluetoothSdkModule) as (
text: string,
x: number,
y: number,
size: number,
) => MaybePromise<void>
NativeBluetoothSdkModule.updateGlasses = function (values: Partial<GlassesStatus>) {
return this.update("glasses", adaptGlassesUpdateToNative(values))
}
NativeBluetoothSdkModule.updateBluetoothSettings = function (values: BluetoothSettingsUpdate) {
return this.update("bluetooth", values)
}
NativeBluetoothSdkModule.displayText = function (text: string, x?: number, y?: number, size?: number) {
return Promise.resolve(nativeDisplayText(text, x ?? 0, y ?? 0, size ?? 24))
}
NativeBluetoothSdkModule.setBrightness = function (level: number, autoMode?: boolean | null) {
return this.updateBluetoothSettings({
...(autoMode == null ? {} : {auto_brightness: autoMode}),
brightness: level,
})
}
NativeBluetoothSdkModule.setAutoBrightness = function (enabled: boolean) {
return this.updateBluetoothSettings({auto_brightness: enabled})
}
NativeBluetoothSdkModule.setDashboardPosition = function (height: number, depth: number) {
return this.updateBluetoothSettings({
dashboard_height: height,
dashboard_depth: depth,
})
}
NativeBluetoothSdkModule.setDashboardMenu = function (items: DashboardMenuItem[]) {
return this.updateBluetoothSettings({menu_apps: items.map(dashboardMenuItemToNative)})
}
NativeBluetoothSdkModule.setCalendarEvents = function (events: CalendarEvent[]) {
return this.updateBluetoothSettings({calendar_events: events})
}
NativeBluetoothSdkModule.setHeadUpAngle = function (angleDegrees: number) {
return this.updateBluetoothSettings({head_up_angle: angleDegrees})
}
NativeBluetoothSdkModule.setImuEnabled = function (enabled: boolean) {
return this.updateBluetoothSettings({imu_enabled: enabled})
}
NativeBluetoothSdkModule.setScreenDisabled = function (disabled: boolean) {
return this.updateBluetoothSettings({screen_disabled: disabled})
}
NativeBluetoothSdkModule.setVoiceActivityDetectionEnabled = function (enabled: boolean) {
return this.updateBluetoothSettings({voice_activity_detection_enabled: enabled})
}
NativeBluetoothSdkModule.setLoudnessGateEnabled = function (enabled: boolean) {
return this.updateBluetoothSettings({loudness_gate_enabled: enabled})
}
NativeBluetoothSdkModule.setAutoPowerOffEnabled = function (enabled: boolean) {
return this.updateBluetoothSettings({auto_power_off_enabled: enabled})
}
NativeBluetoothSdkModule.setMicTuning = function (tuning: MicTuning | null) {
// `{}` rather than null: the store drops null writes, and the native side
// reads an empty object as "no overrides" and sends an explicit reset.
return this.updateBluetoothSettings({mic_tuning: tuning ?? {}})
}
const nativeMicModule = NativeBluetoothSdkModule as unknown as Record<string, unknown>
NativeBluetoothSdkModule.requestMicTuningState = bindNativeMethod<() => Promise<void>>(
nativeMicModule,
"requestMicTuningState",
)
NativeBluetoothSdkModule.setMicRmsTelemetry = bindNativeMethod<(enabled: boolean) => Promise<void>>(
nativeMicModule,
"setMicRmsTelemetry",
)
const nativeSetCameraFov = bindNativeMethod<(fov: CameraFovSetting) => MaybePromise<CameraFovResult>>(
NativeBluetoothSdkModule as unknown as Record<string, unknown>,
"setCameraFov",
)
NativeBluetoothSdkModule.setCameraFov = function (request: CameraFovRequest) {
const setting = normalizeCameraFov(request)
return Promise.resolve(nativeSetCameraFov(setting))
}
const nativeSetLegacyCameraFov = bindNativeMethod<(fov: CameraFovSetting) => MaybePromise<CameraFovResult>>(
NativeBluetoothSdkModule as unknown as Record<string, unknown>,
"setLegacyCameraFov",
)
NativeBluetoothSdkModule.setLegacyCameraFov = function (request: CameraFovRequest) {
return Promise.resolve(nativeSetLegacyCameraFov(normalizeCameraFov(request)))
}
const nativeRestoreLegacyCameraFov = bindNativeMethod<() => MaybePromise<void>>(
NativeBluetoothSdkModule as unknown as Record<string, unknown>,
"restoreLegacyCameraFov",
)
NativeBluetoothSdkModule.restoreLegacyCameraFov = function () {
return Promise.resolve(nativeRestoreLegacyCameraFov())
}
const nativeSetCameraFovOverride = bindNativeMethod<
(request: CameraFovSetting & {leaseId: string; ttlMs: number}) => MaybePromise<CameraFovResult>
>(NativeBluetoothSdkModule as unknown as Record<string, unknown>, "setCameraFovOverride")
NativeBluetoothSdkModule.setCameraFovOverride = function (request: CameraFovOverrideRequest) {
const setting = normalizeCameraFov(request)
const requestedTtl =
typeof request.ttlMs === "number" && Number.isFinite(request.ttlMs) && request.ttlMs > 0
? Math.round(request.ttlMs)
: 300_000
return Promise.resolve(
nativeSetCameraFovOverride({
...setting,
leaseId: request.leaseId,
ttlMs: Math.min(requestedTtl, 600_000),
}),
)
}
NativeBluetoothSdkModule.setMicState = function (
enabled: boolean,
useGlassesMic?: boolean,
sendTranscript?: boolean,
sendLc3Data?: boolean,
) {
return Promise.resolve(
nativeSetMicState(enabled, useGlassesMic ?? true, sendTranscript ?? false, sendLc3Data ?? false),
)
}
NativeBluetoothSdkModule.setPreferredMic = function (preferredMic: MicPreference) {
return this.updateBluetoothSettings({preferred_mic: preferredMic})
}
NativeBluetoothSdkModule.onGlassesStatus = function (callback: GlassesListener) {
const subscription = this.addListener("glasses_status", callback)
return () => subscription.remove()
}
NativeBluetoothSdkModule.onBluetoothStatus = function (callback: BluetoothStatusListener) {
const subscription = this.addListener("bluetooth_status", callback)
return () => subscription.remove()
}
const nativeConnectDefault = NativeBluetoothSdkModule.connectDefault.bind(NativeBluetoothSdkModule)
NativeBluetoothSdkModule.connectDefault = function (options?: ConnectOptions) {
if (!options) {
return nativeConnectDefault()
}
return this.connectDefaultWithOptions({...DEFAULT_CONNECT_OPTIONS, ...options})
}
NativeBluetoothSdkModule.connect = function (device: Device, options?: ConnectOptions) {
return this.connectWithOptions(device, {...DEFAULT_CONNECT_OPTIONS, ...options})
}
const nativeStopScan = NativeBluetoothSdkModule.stopScan.bind(NativeBluetoothSdkModule)
const activeScanCancellations = new Set<() => Promise<void>>()
NativeBluetoothSdkModule.stopScan = async function () {
if (activeScanCancellations.size === 0) return nativeStopScan()
await Promise.all([...activeScanCancellations].map((cancel) => cancel()))
}
NativeBluetoothSdkModule.scan = async function (modelOrOptions: DeviceModel | ScanOptions, options?: ScanModelOptions) {
if (activeScanCancellations.size > 0) await this.stopScan()
const scanOptions = normalizeScanArgs(modelOrOptions, options)
const timeoutMs = normalizeTimeoutMs(scanOptions.timeoutMs ?? scanOptions.timeout, DEFAULT_SCAN_TIMEOUT_MS)
const session = createScanSession(
{
start: (model) => this.startScan(model),
stop: nativeStopScan,
subscribe: (onResults) =>
this.onBluetoothStatus((status) => {
if (Array.isArray(status.searchResults)) onResults(searchResultsForModel(status, scanOptions.model))
}),
getResults: async () => searchResultsForModel(await this.getBluetoothStatus(), scanOptions.model),
// Older native binaries simply omit diagnostics until the host is rebuilt.
getDiagnostic:
typeof this.getScanDiagnostic === "function" ? () => this.getScanDiagnostic!(scanOptions.model) : undefined,
},
{...scanOptions, timeoutMs},
)
activeScanCancellations.add(session.cancel)
try {
return await session.result
} finally {
activeScanCancellations.delete(session.cancel)
}
}
const nativeRequestPhoto = NativeBluetoothSdkModule.requestPhoto.bind(NativeBluetoothSdkModule)
NativeBluetoothSdkModule.requestPhoto = function (params: PhotoRequestParams) {
return nativeRequestPhoto(photoRequestParamsForNative(params) as unknown as PhotoRequestParams)
}
const nativeWarmUpCamera = NativeBluetoothSdkModule.warmUpCamera.bind(NativeBluetoothSdkModule)
NativeBluetoothSdkModule.warmUpCamera = function (params: WarmUpCameraParams) {
return nativeWarmUpCamera(warmUpCameraParamsForNative(params) as unknown as WarmUpCameraParams)
}
const nativeStartStream = bindNativeMethod<(params: StreamStartRequest) => Promise<StreamStatusEvent>>(
NativeBluetoothSdkModule as unknown as Record<string, unknown>,
"startStream",
)
NativeBluetoothSdkModule.startStream = function (params: StreamStartRequest) {
return nativeStartStream(streamRequestParamsForNative(params) as unknown as StreamStartRequest)
}
const nativeWearModule = NativeBluetoothSdkModule as unknown as Record<string, unknown>
NativeBluetoothSdkModule.queryWearState = bindNativeMethod<() => Promise<void>>(nativeWearModule, "queryWearState")
NativeBluetoothSdkModule.setWearReporting = bindNativeMethod<(enabled: boolean) => Promise<void>>(
nativeWearModule,
"setWearReporting",
)
NativeBluetoothSdkModule.setWearTuning = bindNativeMethod<
(intervalMs: number, count: number, majority: number) => Promise<void>
>(nativeWearModule, "setWearTuning")
NativeBluetoothSdkModule.requestWearTuning = bindNativeMethod<() => Promise<void>>(
nativeWearModule,
"requestWearTuning",
)
NativeBluetoothSdkModule.resetWearTuning = bindNativeMethod<() => Promise<void>>(nativeWearModule, "resetWearTuning")
NativeBluetoothSdkModule.sendBesCrashReported = bindNativeMethod<
(incidentKey: string, reportId: string) => Promise<void>
>(NativeBluetoothSdkModule as unknown as Record<string, unknown>, "sendBesCrashReported")
export default NativeBluetoothSdkModule
export const BluetoothSdk = NativeBluetoothSdkModule as BluetoothSdkInternalModule
|