File size: 15,662 Bytes
f0ccdab | 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 | # Getting Started
For a native Mac app, use the [AppKit/SwiftPM example](../macos/README.md)
or [react-native-macos example](../react-native-macos/README.md). Their
macOS setup, sandbox permissions, and compatible native host versions are
separate from the phone instructions below. An iOS app installed on an Apple
silicon Mac through TestFlight still follows the iOS path.
This guide shows how to add the Mentra Bluetooth SDK to Android, iOS, and React Native apps, then connect to Mentra Live and read glasses status.
Use the latest SDK version published by Mentra. In the standalone Starter Kit, the example apps use the published Maven, SwiftPM, and JavaScript packages. Inside MentraOS (`examples/bluetooth`), the same examples build against the SDK source in that checkout; see each example's README.
## Requirements
- A supported pair of Mentra smart glasses.
- A physical phone for real Bluetooth testing. Simulators and emulators are useful for UI/build checks only.
- Android: min SDK `28` or newer, Java 17, Android Studio or Gradle.
- iOS: deployment target `15.1` or newer, Xcode 15 or newer, Swift Package Manager.
- React Native / Expo: a development build or production native build. Expo Go cannot load the native SDK.
- Bluetooth permissions, and Android location permission where BLE scanning requires it, requested through your app's normal permission flow.
## Package Install
### Android
Depend on the Android artifact from your app module:
```kotlin
// settings.gradle.kts
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven("https://www.jitpack.io")
}
}
```
```kotlin
// app/build.gradle.kts
android {
defaultConfig {
minSdk = 28
}
packaging {
jniLibs {
pickFirsts += "**/libc++_shared.so"
pickFirsts += "**/libonnxruntime.so"
pickFirsts += "**/libonnxruntime4j_jni.so"
}
}
}
dependencies {
implementation("com.mentraglass:bluetooth-sdk:<version>")
}
```
The packaging rules avoid duplicate native library conflicts from the SDK audio and transcription stack.
For unreleased SDK development, build the SDK from a MentraOS checkout through a Gradle composite build instead of a published version. In your app's `settings.gradle.kts`:
```kotlin
includeBuild("/path/to/MentraOS/mobile/modules/bluetooth-sdk/android") {
dependencySubstitution {
substitute(module("com.mentraglass:bluetooth-sdk")).using(project(":"))
}
}
```
Declare the Android Gradle Plugin in your app's root build and install the Android NDK. The native Android example in MentraOS uses this setup.
### iOS
Add the public Swift package in Xcode or `Package.swift`:
```text
https://github.com/Mentra-Community/mentra-bluetooth-sdk-ios.git
```
Use version `0.1.20` or newer, then add the `MentraBluetoothSDK` product to your app target.
For `Package.swift` consumers:
```swift
.package(
url: "https://github.com/Mentra-Community/mentra-bluetooth-sdk-ios.git",
from: "0.1.20"
)
```
For unreleased SDK development, point Xcode at a local Swift package checkout.
```text
/path/to/MentraOS/mobile/modules/bluetooth-sdk
```
Keep local package paths out of committed project files.
### React Native / Expo
Install the package with Bun and configure the Expo plugin:
```bash
bun add @mentra/bluetooth-sdk
bunx expo install expo-build-properties
```
```json
{
"expo": {
"plugins": [
[
"@mentra/bluetooth-sdk",
{
"node": true
}
],
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 28,
"packagingOptions": {
"pickFirst": [
"**/libc++_shared.so",
"**/libonnxruntime.so",
"**/libonnxruntime4j_jni.so"
]
}
}
}
]
]
}
}
```
Then generate and run a native build:
```bash
bunx expo prebuild
bunx expo run:ios
# or
bunx expo run:android
```
The React Native starter example also includes `bun run android:dev`, which starts Metro first, forwards the device's `localhost:8081` over USB, installs the native app, and opens the Expo dev-client URL so the first launch does not land on the blank launcher screen.
For unreleased SDK development, use the examples inside MentraOS (`examples/bluetooth`): the React Native examples are members of the `examples/` Bun workspace, which links `@mentra/bluetooth-sdk` to the SDK source, and the native Android and Apple examples reference the SDK source directly. Each example's README describes the setup.
## Permissions
Android apps should request the platform permissions required by the features they use:
```xml
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
```
Some Android 12+ devices still require runtime location permission and Location services before they deliver BLE scan callbacks, even when Nearby Devices permissions are granted.
iOS apps should include permission copy in `Info.plist`:
```xml
<key>NSBluetoothAlwaysUsageDescription</key>
<string>This app connects to your smart glasses over Bluetooth.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app uses the microphone when you enable audio or transcription features.</string>
<key>NSLocalNetworkUsageDescription</key>
<string>This app connects to local media upload and streaming helpers during development.</string>
```
## Background Operation On iOS
Declare Core Bluetooth background mode in your iOS app's `Info.plist`. Without
it, iOS suspends your app when the phone locks and delivers no Bluetooth events
to it, so the glasses link stops working in the background. A Swift package
cannot declare background modes for your app. The native example declares it in
`ios/MentraExample-Info.plist`.
An upcoming SDK release, tracked in Mentra-Community/MentraOS#4386, also
reconnects in the background after the glasses drop the link, for example while
their Bluetooth chip restarts during a software update, and logs a warning at
startup when the mode is missing. The SDK version these examples pin,
`3.2.1-dev.307`, does not include that yet. See
[Background Operation](https://docs.mentraglass.com/bluetooth-sdk/ios#background-operation).
```xml
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
</array>
```
If your app also keeps microphone capture or an audio session active in the background, add `audio` too:
```xml
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
<string>audio</string>
</array>
```
Configure your audio session before starting continuous microphone or playback work. For Expo / React Native apps, install `expo-audio` if needed and call `setAudioModeAsync` during startup or before enabling the microphone:
```ts
import {setAudioModeAsync} from 'expo-audio';
await setAudioModeAsync({
allowsRecording: true,
allowsBackgroundRecording: true,
shouldPlayInBackground: true,
playsInSilentMode: true,
interruptionMode: 'duckOthers',
});
```
Start continuous microphone capture while the app is foregrounded. iOS background mode lets an active session continue, but the SDK does not start the phone microphone from the background.
This SDK version does not enable terminated-app Core Bluetooth state restoration with `CBCentralManagerOptionRestoreIdentifierKey`. If iOS terminates the app, relaunch the app and reconnect from your normal startup flow.
## Minimal Lifecycle
1. Request OS-level Bluetooth permissions before scanning.
2. Create one SDK instance for the active app session.
3. Subscribe to status and hardware events before connecting.
4. Start a scan for the user's glasses model.
5. Connect by discovered device, or restore your app-persisted default device and call `connectDefault()`.
6. Drive UI from SDK status callbacks and snapshots.
7. Send commands only when the connected device supports the feature.
8. Stop scans, remove listeners/delegates, and call `close()` / `invalidate()` when the app session ends.
## Android Basic Flow
```kotlin
import android.content.Context
import com.mentra.bluetoothsdk.Device
import com.mentra.bluetoothsdk.DeviceModel
import com.mentra.bluetoothsdk.GlassesRuntimeState
import com.mentra.bluetoothsdk.MentraBluetoothSdk
import com.mentra.bluetoothsdk.MentraBluetoothSdkCallback
class GlassesController(context: Context) : MentraBluetoothSdkCallback() {
private val sdk = MentraBluetoothSdk.create(
context = context.applicationContext,
listener = this,
)
private var selectedDevice: Device? = null
fun scan() {
sdk.scan(DeviceModel.MENTRA_LIVE, timeoutMs = 10_000) { devices ->
renderDevicePicker(devices, onSelect = { selectedDevice = it })
}
}
fun connect() {
selectedDevice?.let { sdk.connect(it) }
}
fun refreshStatus() {
val versionInfo = sdk.requestVersionInfo()
val glasses = sdk.getGlasses()
if (glasses is GlassesRuntimeState.Connected) {
val model = glasses.device.deviceModel?.deviceType ?: "glasses"
val battery = glasses.battery.level?.toString() ?: "unknown"
println("Connected to $model, battery=$battery%, build=${versionInfo.buildNumber}")
}
}
override fun onGlassesChanged(glasses: GlassesRuntimeState) {
// Keep app UI derived from SDK status.
println("Glasses changed: $glasses")
}
private fun renderDevicePicker(devices: List<Device>, onSelect: (Device) -> Unit) {
// Render devices in SDK-provided order and call onSelect with the user's choice.
}
fun close() {
sdk.close()
}
}
```
## iOS Basic Flow
```swift
import MentraBluetoothSDK
@MainActor
final class GlassesController: NSObject, MentraBluetoothSDKDelegate {
private let sdk = MentraBluetoothSDK()
private var selectedDevice: Device?
override init() {
super.init()
sdk.delegate = self
}
func scan() throws {
try sdk.scan(model: .mentraLive, timeout: 10) { [weak self] devices in
self?.renderDevicePicker(devices) { device in
self?.selectedDevice = device
}
}
}
func connect() throws {
guard let selectedDevice else { return }
try sdk.connect(to: selectedDevice)
}
func refreshStatus() async throws {
let versionInfo = try await sdk.requestVersionInfo()
let glasses = sdk.glasses
if let device = glasses.device {
let battery = glasses.battery?.level.map(String.init) ?? "unknown"
print("Connected to \(device.deviceModel?.deviceType ?? "glasses"), battery=\(battery)%, build=\(versionInfo.buildNumber)")
}
}
func mentraBluetoothSDK(_ sdk: MentraBluetoothSDK, didUpdateGlasses glasses: GlassesRuntimeState) {
// Keep app UI derived from SDK status.
print("Glasses changed: \(glasses)")
}
private func renderDevicePicker(_ devices: [Device], onSelect: @escaping (Device) -> Void) {
// Render devices in SDK-provided order and call onSelect with the user's choice.
}
deinit {
sdk.invalidate()
}
}
```
## React Native Basic Flow
```ts
import BluetoothSdk, {DeviceModels} from '@mentra/bluetooth-sdk';
import {useMentraBluetooth} from '@mentra/bluetooth-sdk/react';
const devices = await BluetoothSdk.scan(DeviceModels.MentraLive, {
timeoutMs: 10_000,
onResults: (nextDevices) => renderDevicePicker(nextDevices),
});
const device = await chooseDevice(devices);
await BluetoothSdk.connect(device);
const versionInfo = await BluetoothSdk.requestVersionInfo();
console.log('Build:', versionInfo.buildNumber);
function DeviceStatus() {
const mentra = useMentraBluetooth();
console.log('Connection:', mentra.glasses.connection.state);
console.log('Battery:', mentra.glasses.connected ? mentra.glasses.battery.level : null);
}
```
React Native status uses `mentra.glasses.connection.state` for link progress. `fullyBooted` only exists when `state === 'connected'`.
`scan()` has two result paths on purpose: `onResults` is for live picker updates while scanning is still in progress, and the returned `devices` array is the final list after the scan timeout/completion. Use the final list for "pick one and connect" logic. In rooms with multiple pairs of glasses, present an explicit picker instead of auto-connecting to the first nearby device.
Use `Device.id` as the stable app-facing key for scan rows, selected devices, and persisted default devices. Do not parse it for model, name, or address information; use the typed `model`, `name`, `address` / `identifier`, and `rssi` fields instead. Android commonly uses a Bluetooth address when available, iOS commonly uses a CoreBluetooth identifier when available, and the SDK falls back to `model:name` when no platform identifier is available.
`Device.rssi` is optional. A device can appear in scan results before the platform reports RSSI, so picker UI should handle `undefined` and avoid reordering rows just because RSSI metadata arrives later.
React Native apps should persist their own default-device record if they want `connectDefault()` to work after restart:
```ts
const savedDevice = await loadSavedDevice();
if (savedDevice) {
await BluetoothSdk.setDefaultDevice(savedDevice);
await BluetoothSdk.connectDefault();
}
```
## Run The Examples
From a fresh clone of the standalone Starter Kit:
```bash
git clone <starter-kit-repo-url>
cd <starter-kit-directory>
```
Inside MentraOS, run the commands below from `examples/bluetooth`, and install
the React Native examples' dependencies once with `bun install` in `examples/`
instead of in each example; see the
[React Native example README](../react-native/README.md#install).
Run one of:
```bash
cd android
./gradlew installDebug
```
```bash
cd ios
open MentraExample.xcodeproj
```
```bash
cd react-native
bun install
bun run ios:setup
bunx expo prebuild
bunx expo run:ios
# or
bun run android:dev
```
`bun run ios:setup` installs the GStreamer iOS SDK used by the React Native example's direct phone WebRTC preview.
For photo/video upload and RTMP/SRT/WebRTC demos, start the local helper from the Starter Kit root:
```bash
python3 local-demo-cloud/server.py
```
Paste the printed LAN URLs into the example apps. Do not use `localhost`; the glasses and phone need a reachable LAN address.
## Next Steps
- See [API Reference](api-reference.md) for supported commands and events.
- See [Display Guide](display-guide.md) for display examples.
- See [Audio Guide](audio-guide.md) for microphone and local transcription flows.
- See [Hardware Integration Notes](hardware-integration.md) for model capability guidance.
- See [Troubleshooting](troubleshooting.md) if native build or pairing fails.
|