# React Native Hooks Proposal For The Bluetooth SDK This document started as a proposal for making the React Native SDK feel more React-native without hiding the underlying Bluetooth lifecycle. The stable hook set below is now implemented under: ```ts import { useBluetoothEvent, useBluetoothScan, useBluetoothStatus, useGlassesConnection, } from '@mentra/bluetooth-sdk/react'; ``` It is based on the current React Native starter app in the Partner Kit: ```text Mentra-Bluetooth-SDK-Partner-Kit/examples/react-native/src/useMentraSdk.ts ``` The starter app is useful as a complete demo, but it is also evidence that customers will reimplement the same subscription, cleanup, scan, connect, request/response, and timer patterns unless the SDK gives them small React building blocks. ## Current Pain Points - The example app has one large `useMentraSdk()` hook that owns unrelated concerns: SDK status, scan results, default-device persistence, photo upload, streaming, Wi-Fi, hotspot, mic recording, audio playback, RGB LED controls, and console logging. - Every app must currently remember to load initial status with `getGlassesStatus()` and `getBluetoothStatus()`, then separately subscribe to `onGlassesStatus()` and `onBluetoothStatus()`, merge partial updates, and remove listeners on unmount. - Device picker flows need scan state, incremental scan results, selected device tracking, timeout handling, and cleanup. The current `scan(...)` helper is good, but React apps still need lifecycle state around it. - Connection flows need consistent `connecting`, `connected`, `disconnecting`, and `error` state, plus optional default-device persistence. - Photo capture and streaming are request/response lifecycles. Apps need to create request IDs, correlate events, handle timeouts, stop timers, and clean up on unmount. - Microphone recording is easy to start with `setMicState(...)`, but React apps need a safe way to collect PCM frames and stop recording without leaking event listeners. ## Design Principles - Keep the root SDK imperative and language-neutral: `import BluetoothSdk from '@mentra/bluetooth-sdk'`. - Add React helpers under an explicit subpath: `import {useGlassesConnection} from '@mentra/bluetooth-sdk/react'`. - Hooks should be thin lifecycle helpers, not a full application framework. - Hooks should compose. A developer can use only `useBluetoothStatus()` or use a higher-level `useGlassesConnection()` that composes scan and connect state. - Hooks should not own app-specific infrastructure such as local demo servers, MediaMTX reachability, Expo audio playback, app analytics, or cloud auth. - Hooks should make cleanup the default: stop scans, remove listeners, clear timers, and stop keep-alives on unmount when the hook created them. - Hooks should expose SDK-native types. Do not invent a parallel React-only status model unless it removes an impossible state. ## Proposed Package Shape Add a React subpath: ```json { "exports": { ".": { "types": "./build/index.d.ts", "react-native": "./src/index.ts", "default": "./build/index.js" }, "./react": { "types": "./build/react/index.d.ts", "react-native": "./src/react/index.ts", "default": "./build/react/index.js" } } } ``` Implemented source layout: ```text mobile/modules/bluetooth-sdk/src/react/index.ts mobile/modules/bluetooth-sdk/src/react/useBluetoothEvent.ts mobile/modules/bluetooth-sdk/src/react/useBluetoothStatus.ts mobile/modules/bluetooth-sdk/src/react/useBluetoothScan.ts mobile/modules/bluetooth-sdk/src/react/useGlassesConnection.ts ``` The SDK already has `react` as a peer dependency, so the subpath does not add a new conceptual runtime requirement for React Native consumers. ## Proposed Hooks ### `useBluetoothEvent` Low-level typed event subscription with automatic cleanup. ```ts function useBluetoothEvent( eventName: EventName, listener: BluetoothSdkEventListener, options?: {enabled?: boolean}, ): void ``` Example: ```ts useBluetoothEvent('button_press', (event) => { console.log(event.buttonId, event.pressType); }); ``` This removes the repeated `addListener(...); return subscription.remove` pattern without hiding the event system. ### `useBluetoothStatus` Loads initial status, subscribes to partial updates, and returns merged status. ```ts function useBluetoothStatus(options?: { enabled?: boolean; onError?: (error: unknown) => void; }): { glassesStatus: Partial; bluetoothStatus: Partial; connected: boolean; error: unknown | null; loading: boolean; ready: boolean; refresh: () => Promise; } ``` This replaces the repeated combination of: ```ts await BluetoothSdk.getGlassesStatus(); await BluetoothSdk.getBluetoothStatus(); BluetoothSdk.onGlassesStatus(...); BluetoothSdk.onBluetoothStatus(...); ``` It should use `createDisconnectedGlassesStatus()` as the initial glasses state. ### `useBluetoothScan` React lifecycle wrapper around `BluetoothSdk.scan(...)`. ```ts function useBluetoothScan(options?: { model?: DeviceModel; timeoutMs?: number; dedupe?: 'id' | 'name' | ((device: Device) => string); onError?: (error: unknown) => void; }): { devices: Device[]; scanning: boolean; error: unknown | null; model: DeviceModel; setModel: (model: DeviceModel) => void; selectedDevice: Device | null; selectDevice: (device: Device | null) => void; startScan: (model?: DeviceModel) => Promise; stopScan: () => Promise; clearResults: () => void; } ``` Why both a returned `Promise` and live `devices` state: - `devices` updates as scan results arrive, so the UI can show a picker during the scan. - The returned promise resolves with the final scan result list, so submit-style code can do one thing after scanning completes. This is the React version of the lower-level SDK `scan(model, {onResults})` helper rather than a replacement for it. ### `useGlassesConnection` Common connection state and actions, optionally composed with `useBluetoothScan`. ```ts type DefaultDeviceStorage = { load: () => Promise; save: (device: Device | null) => Promise; }; function useGlassesConnection(options?: { scanModel?: DeviceModel; scanTimeoutMs?: number; autoConnectDefault?: boolean; defaultDeviceStorage?: DefaultDeviceStorage; onError?: (error: unknown) => void; }): { glassesStatus: Partial; bluetoothStatus: Partial; connected: boolean; ready: boolean; busy: boolean; action: 'idle' | 'scanning' | 'connecting' | 'disconnecting' | 'forgetting'; error: unknown | null; defaultDevice: Device | null; scan: ReturnType; connect: (device?: Device) => Promise; connectDefault: () => Promise; disconnect: () => Promise; forget: () => Promise; clearDefaultDevice: () => Promise; setDefaultDevice: (device: Device | null) => Promise; } ``` The storage adapter keeps the SDK from choosing AsyncStorage, MMKV, SecureStore, or a filesystem implementation for the customer. The starter app can pass its current file-backed default-device storage, while customer apps can pass their own persistence. Basic customer usage: ```tsx import {DeviceModels} from '@mentra/bluetooth-sdk'; import {useGlassesConnection} from '@mentra/bluetooth-sdk/react'; function DevicePicker() { const glasses = useGlassesConnection({ scanModel: DeviceModels.MentraLive, autoConnectDefault: true, defaultDeviceStorage: myDeviceStorage, }); return ( <>