react-native-asleep 1.2.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +404 -0
- package/README.md +289 -215
- package/android/build.gradle +1 -1
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +274 -77
- package/build/Asleep.types.d.ts +78 -4
- package/build/Asleep.types.d.ts.map +1 -1
- package/build/Asleep.types.js.map +1 -1
- package/build/AsleepStore.d.ts +6 -2
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +236 -29
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js.map +1 -1
- package/docs/INTEGRATION.ko.md +427 -0
- package/docs/INTEGRATION.md +474 -0
- package/ios/Asleep.podspec +1 -1
- package/ios/AsleepModule.swift +310 -19
- package/package.json +5 -3
- package/src/Asleep.types.ts +81 -5
- package/src/AsleepStore.ts +302 -30
- package/src/index.ts +8 -0
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
# React Native Asleep Integration Guide
|
|
2
|
+
|
|
3
|
+
[English](./INTEGRATION.md) | [한국어](./INTEGRATION.ko.md)
|
|
4
|
+
|
|
5
|
+
This guide covers production integration of `react-native-asleep` in React Native and Expo apps. It expands on the [README](../README.md) with restoration, lifecycle ownership, platform differences, recovery, analysis, reports, and release verification.
|
|
6
|
+
|
|
7
|
+
The examples use service-based sleep tracking through `initAsleepConfig()`. ODA (On-Device Analysis) is outside this guide: `setup()` configures a new ODA session and cannot run while a restored session is tracking.
|
|
8
|
+
|
|
9
|
+
## Integration flow
|
|
10
|
+
|
|
11
|
+
```mermaid
|
|
12
|
+
flowchart LR
|
|
13
|
+
A["App starts"] --> B["Mount useAsleep or initialize listeners"]
|
|
14
|
+
B --> C["checkAndRestoreTracking()"]
|
|
15
|
+
C --> D["await initAsleepConfig()"]
|
|
16
|
+
D --> E["checkBatteryOptimization()"]
|
|
17
|
+
E --> F{"Android service restored?"}
|
|
18
|
+
F -- "Yes" --> G["Render restored SDK state"]
|
|
19
|
+
F -- "No" --> H["User starts tracking"]
|
|
20
|
+
H --> I["Check and request permission"]
|
|
21
|
+
I --> J["Recheck Android battery exemption"]
|
|
22
|
+
J --> K["startTracking()"]
|
|
23
|
+
G --> L["Observe state and events"]
|
|
24
|
+
K --> L
|
|
25
|
+
L --> M["stopTracking()"]
|
|
26
|
+
M --> N["Fetch report when ready"]
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Three rules prevent most integration failures:
|
|
30
|
+
|
|
31
|
+
1. Complete the Android service-restoration check before configuration, and always configure afterward—even when it finds a live session.
|
|
32
|
+
2. Request runtime permissions only from a user action. `startTracking()` checks permissions but does not request them.
|
|
33
|
+
3. Treat the SDK state as native facts. Keep product workflow, persistence, timers, retries, UI, and analytics in the app.
|
|
34
|
+
|
|
35
|
+
## 1. Installation and native configuration
|
|
36
|
+
|
|
37
|
+
Follow the [README installation instructions](../README.md#installation) and [native configuration](../README.md#native-configuration).
|
|
38
|
+
|
|
39
|
+
Because the package contains native modules:
|
|
40
|
+
|
|
41
|
+
- rebuild the development or store binary after installation or a version change;
|
|
42
|
+
- do not validate it with Expo Go;
|
|
43
|
+
- do not expect an OTA update alone to install a new native SDK.
|
|
44
|
+
|
|
45
|
+
The app must provide iOS microphone usage text and the audio background mode. Android permissions and the foreground service come from the library manifest.
|
|
46
|
+
|
|
47
|
+
## 2. Own the listener lifecycle
|
|
48
|
+
|
|
49
|
+
### React applications
|
|
50
|
+
|
|
51
|
+
Mount `useAsleep()` in the integration owner that coordinates app-wide sleep tracking. The hook attaches native listeners on mount and releases them on unmount.
|
|
52
|
+
|
|
53
|
+
The listener bridge is ref-counted, so additional components may also use the hook without creating competing SDK stores. Keeping one app-level integration hook is still useful because it gives product workflow a single owner.
|
|
54
|
+
|
|
55
|
+
Importing `react-native-asleep` is side-effect-free; it does not attach listeners.
|
|
56
|
+
|
|
57
|
+
### Non-React code
|
|
58
|
+
|
|
59
|
+
Call `Asleep.initialize()` before relying on state or native events where no mounted hook owns the bridge. Always call the returned cleanup function.
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { Asleep } from "react-native-asleep";
|
|
63
|
+
|
|
64
|
+
const releaseListeners = Asleep.initialize();
|
|
65
|
+
|
|
66
|
+
const unsubscribe = Asleep.subscribe((state) => {
|
|
67
|
+
console.log(state.status);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const removeAnalysisListener = Asleep.addEventListener(
|
|
71
|
+
"onAnalysisResult",
|
|
72
|
+
(result) => {
|
|
73
|
+
console.log(result);
|
|
74
|
+
},
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
// When the owner is disposed:
|
|
78
|
+
removeAnalysisListener();
|
|
79
|
+
unsubscribe();
|
|
80
|
+
releaseListeners();
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`Asleep.initialize()` is also ref-counted, so it can coexist with mounted `useAsleep()` hooks.
|
|
84
|
+
|
|
85
|
+
## 3. Restore, then configure
|
|
86
|
+
|
|
87
|
+
Run this sequence once from the app-level integration owner:
|
|
88
|
+
|
|
89
|
+
```tsx
|
|
90
|
+
import { useCallback } from "react";
|
|
91
|
+
import { useAsleep } from "react-native-asleep";
|
|
92
|
+
|
|
93
|
+
export function useSleepTrackingBootstrap(stableUserId?: string) {
|
|
94
|
+
const asleep = useAsleep();
|
|
95
|
+
|
|
96
|
+
const initialize = useCallback(async () => {
|
|
97
|
+
const restoration = await asleep.checkAndRestoreTracking();
|
|
98
|
+
|
|
99
|
+
const config = {
|
|
100
|
+
apiKey: "YOUR_API_KEY",
|
|
101
|
+
userId: stableUserId,
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
await asleep.initAsleepConfig(config);
|
|
105
|
+
|
|
106
|
+
const battery = await asleep.checkBatteryOptimization();
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
hasActiveSession: restoration.hasActiveSession,
|
|
110
|
+
battery,
|
|
111
|
+
};
|
|
112
|
+
}, [
|
|
113
|
+
asleep.checkAndRestoreTracking,
|
|
114
|
+
asleep.initAsleepConfig,
|
|
115
|
+
asleep.checkBatteryOptimization,
|
|
116
|
+
stableUserId,
|
|
117
|
+
]);
|
|
118
|
+
|
|
119
|
+
return { ...asleep, initialize };
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Why this order is required
|
|
124
|
+
|
|
125
|
+
- `checkAndRestoreTracking()` asks Android native code whether tracking survived the JavaScript process and reconnects the service when needed. On iOS, the method is a required cross-platform prerequisite but returns `{ hasActiveSession: false }`; iOS has no persistent service to reconnect.
|
|
126
|
+
- `initAsleepConfig()` remains required after that check. A restored session does not mean the current JavaScript process has configured the SDK and report APIs.
|
|
127
|
+
- `await initAsleepConfig()` resolves after the native user join has created the tracking and report managers, and rejects when the join fails, on both platforms. Await the action itself rather than `onUserJoined`: the Android restored-service fast path resolves without emitting that event.
|
|
128
|
+
- A second `initAsleepConfig()` while one is in progress rejects with `OPERATION_IN_PROGRESS`. When switching users, let the previous call settle before starting the next. The native SDKs ignore an init, with no callback, while tracking is starting or stopping or while a previous init is still waiting for its response; on iOS the call then rejects with `INITIALIZATION_FAILED` after 60 seconds (a late SDK answer to it is applied and emits `onUserJoined`/`onUserJoinFailed` only if no newer `initAsleepConfig()` has started; otherwise it is ignored and per-user calls stay blocked until the next successful init), and a new call made while the SDK is still busy with the previous one can time out the same way; on Android it stays pending. Avoid calling `initAsleepConfig()` during a start or stop.
|
|
129
|
+
- `checkBatteryOptimization()` marks the required prerequisite as checked. On iOS it resolves with `{ exempted: true, platform: "ios" }`.
|
|
130
|
+
- `startTracking()` rejects with `MISSING_PREREQUISITE` if restoration or the battery check has not run.
|
|
131
|
+
|
|
132
|
+
Do not run restoration and configuration concurrently. Do not skip configuration when `hasActiveSession` is `true`.
|
|
133
|
+
|
|
134
|
+
If initialization fails, keep tracking controls disabled and offer an app-owned retry action. Do not convert the failure into an apparently ready state.
|
|
135
|
+
|
|
136
|
+
Do not commit the API key to source control. Load it through the secret or configuration mechanism used by the app's build environment.
|
|
137
|
+
|
|
138
|
+
Token authentication uses the same actions: pass `{ appId, appSecret }` instead of `{ apiKey }` to `setup()` or `initAsleepConfig()`. The two forms are mutually exclusive (`AsleepCredentials`); neither, both, an incomplete pair, or an empty value rejects with `INVALID_ARGUMENT` before the native call. On Android, the restored-service fast path recognizes the same `appId` and `userId` as the running session, so restore works in token mode as it does with an API key. Treat `appSecret` with the same secret handling as the API key.
|
|
139
|
+
|
|
140
|
+
### Stable user identity
|
|
141
|
+
|
|
142
|
+
If the app supplies `userId`, persist the stable identifier in app storage and reuse it on later initialization. The SDK exposes the current native `userId`, but account mapping and guest-to-member policy belong to the app.
|
|
143
|
+
|
|
144
|
+
Do not reconfigure a live session with a different product identity. Define any identity migration policy outside the SDK.
|
|
145
|
+
|
|
146
|
+
### User metadata
|
|
147
|
+
|
|
148
|
+
`saveUserMetadata(metadata)` and `fetchUserMetadata()` read and write optional profile data (birth date, gender, height, weight) on the configured user. Call them only after the most recent `initAsleepConfig()` has resolved. Earlier calls, calls while a re-init is in progress, and calls after a failed re-init reject with `MISSING_PREREQUISITE`; the previous user's config is never reused. `setup()` also invalidates it, so call `initAsleepConfig()` again after `setup()`.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
await asleep.saveUserMetadata({ birthYear: 1990, birthMonth: 5, birthDay: 17, gender: "female" });
|
|
152
|
+
const metadata = await asleep.fetchUserMetadata(); // null when nothing was saved
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The wrapper validates the native ranges before any bridge call and rejects with `INVALID_ARGUMENT`; see the README for the ranges. The server can still reject a value (for example a future `birthYear`) with `INVALID_ARGUMENT` and `sdkCode` 27400. Other failures arrive as `SAVE_USER_METADATA_FAILED` (`sdkCode` 27000) or `FETCH_USER_METADATA_FAILED` (`sdkCode` 27100). Both native SDKs truncate `height` and `weight` to one decimal place, so a fetched value can differ from the saved input. Whether and when to collect this data, consent, and editing UI are app-owned.
|
|
156
|
+
|
|
157
|
+
### Device registration
|
|
158
|
+
|
|
159
|
+
Hardware products register the device with Asleep by passing `productInfo` to `setup()` (`POST customer/v1/products`); `initAsleepConfig()` does not accept it. Register before `startTracking()`: only sessions created after a successful registration are bound to the product. Behavior below is as of iOS SDK 3.3.3 and Android SDK 3.3.1.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
await asleep.setup({
|
|
163
|
+
appId: "YOUR_APP_ID",
|
|
164
|
+
appSecret: "YOUR_APP_SECRET",
|
|
165
|
+
productInfo: { model: "YOUR_PRODUCT_MODEL", identifierType: "mac_address", identifierValue: deviceMacAddress },
|
|
166
|
+
});
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
| Field | Rule |
|
|
170
|
+
|---|---|
|
|
171
|
+
| `model` | 1-100 characters, not blank |
|
|
172
|
+
| `identifierType` | `"serial"` or `"mac_address"` |
|
|
173
|
+
| `identifierValue` | 1-255 characters, not blank |
|
|
174
|
+
|
|
175
|
+
Values are sent untrimmed. Invalid values and unknown fields reject with `INVALID_ARGUMENT` before any native call; without `productInfo`, `setup()` behaves as before and nothing is registered.
|
|
176
|
+
|
|
177
|
+
- **Idempotent per identifier.** The same `identifierType` and `identifierValue` return the existing product credential. A device that already holds a credential for the same credentials owner and the same `productInfo` makes no network call, so passing the same value on every launch is safe.
|
|
178
|
+
- **The first `model` wins.** The server keeps the model of the first registration for an identifier; the SDK cannot change it.
|
|
179
|
+
- **A new identifier is a new product.** It may be billable. Use real device identifiers and never send placeholder or test values with production credentials.
|
|
180
|
+
- **Changing credentials re-registers.** A different `apiKey` or `appId` drops the stored credential, and the next `setup()` with `productInfo` registers again.
|
|
181
|
+
- **Registration blocks setup.** On failure the whole `setup()` fails with code `SETUP_FAILED` and no `onSetupDidComplete`, and the native SDK is reset so `setup()` can be called again:
|
|
182
|
+
|
|
183
|
+
| `error.sdkCode` | Meaning | Suggested handling |
|
|
184
|
+
|---|---|---|
|
|
185
|
+
| 13400 | Rejected: a 4xx other than 429, or failed input checks | Do not retry unchanged; fix the input or the contract |
|
|
186
|
+
| 13000 | Network failure, 5xx, 429, or an unreadable response. The SDK already retried network failures, 5xx and 429 after 2, 4 and 8 seconds | Retry later with a bounded policy |
|
|
187
|
+
|
|
188
|
+
Offline, a 13000 failure can take about 1.5-3 minutes to arrive; keep tracking controls disabled until setup finishes.
|
|
189
|
+
|
|
190
|
+
On Android, `setup()` resolves after registration and setup complete, and rejects with the failure. On iOS, `setup()` returns once the native call starts and `isSetupComplete` can turn `true` before registration finishes. Register `onSetupDidComplete` and `onSetupDidFail` before calling `setup()` and wait for one of them. Do not call `setup()` again before it arrives: the native SDK ignores a second `setup()` while one is running and sends no callback.
|
|
191
|
+
|
|
192
|
+
## 4. Check prerequisites and start
|
|
193
|
+
|
|
194
|
+
Permission prompts must originate from a user-driven interaction:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
async function startSleepTracking() {
|
|
198
|
+
if (!(await asleep.hasRequiredPermissions())) {
|
|
199
|
+
const granted = await asleep.requestRequiredPermissions();
|
|
200
|
+
if (!granted) return { status: "permissionDenied" as const };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const battery = await asleep.checkBatteryOptimization();
|
|
204
|
+
if (!battery.exempted) {
|
|
205
|
+
await asleep.requestBatteryOptimizationExemption();
|
|
206
|
+
return { status: "batterySettingsOpened" as const };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
await asleep.startTracking({
|
|
210
|
+
android: {
|
|
211
|
+
notification: {
|
|
212
|
+
title: "Sleep tracking",
|
|
213
|
+
text: "Sleep analysis is running.",
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
return { status: "started" as const };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function handleTrackingPress() {
|
|
222
|
+
const shouldStop =
|
|
223
|
+
asleep.isTracking || asleep.error?.category === "recordingDead";
|
|
224
|
+
|
|
225
|
+
if (shouldStop) {
|
|
226
|
+
await asleep.stopTracking();
|
|
227
|
+
return { status: "stopped" as const };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return startSleepTracking();
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
When Android opens battery settings, the result only means the settings flow was requested. Recheck `checkBatteryOptimization()` after the app returns and let the user retry. `startTracking()` performs its own Android exemption check and throws `BATTERY_NOT_EXEMPTED` if the device is still not exempted.
|
|
235
|
+
|
|
236
|
+
Use the same `shouldStop` predicate for the primary button label and action. In the `recordingDead` state, `isTracking` is `false` but the native session is still open, so the app must stop that session instead of starting another one.
|
|
237
|
+
|
|
238
|
+
On Android 13 and later, `requestRequiredPermissions()` also requests notification permission for foreground-service visibility. Its boolean result reflects microphone-side permissions, matching `hasRequiredPermissions()`; notification denial alone does not prevent tracking.
|
|
239
|
+
|
|
240
|
+
The app owns permission-denied screens, settings guidance, retry buttons, and analytics. The library never renders UI.
|
|
241
|
+
|
|
242
|
+
## 5. Separate SDK state from app state
|
|
243
|
+
|
|
244
|
+
| SDK-owned native facts | App-owned product state |
|
|
245
|
+
|---|---|
|
|
246
|
+
| `status`, `isTracking`, `isTrackingPaused` | Bootstrap or screen readiness |
|
|
247
|
+
| `isRecoveryRequired`, `error` | Permission education and retry UI |
|
|
248
|
+
| `sessionId`, `userId` | Persisted identity mapping |
|
|
249
|
+
| `analysisResult`, `isAnalyzing` | Wall-clock tracking start time and duration |
|
|
250
|
+
| `didClose`, `isSetupComplete`, `isODAEnabled` | Alarm, widget, Live Activity, cloud sync |
|
|
251
|
+
| Native event and action transitions | Business retry policy and observability severity |
|
|
252
|
+
|
|
253
|
+
`status` is the lifecycle source:
|
|
254
|
+
|
|
255
|
+
| `status` | Meaning |
|
|
256
|
+
|---|---|
|
|
257
|
+
| `idle` | No projected live tracking session |
|
|
258
|
+
| `tracking` | Tracking is active |
|
|
259
|
+
| `paused` | The live native session is interrupted |
|
|
260
|
+
| `recoveryRequired` | The live iOS session needs an explicit foreground resume |
|
|
261
|
+
|
|
262
|
+
`isTracking` is derived from `status` and is `true` for `tracking`, `paused`, and `recoveryRequired`. Do not store a competing app boolean for the same fact.
|
|
263
|
+
|
|
264
|
+
The SDK does not expose wall-clock tracking duration. Store a start timestamp in the app and compute `now - startedAt`; do not count timer ticks because background suspension makes them inaccurate.
|
|
265
|
+
|
|
266
|
+
## 6. Platform behavior
|
|
267
|
+
|
|
268
|
+
| Concern | Android | iOS |
|
|
269
|
+
|---|---|---|
|
|
270
|
+
| Background operation | Foreground service with a persistent notification | Audio background mode |
|
|
271
|
+
| Cold restoration | `checkAndRestoreTracking()` reconnects the live service | No persistent service; the check returns `false` |
|
|
272
|
+
| Battery prerequisite | Exemption is required and checked again by `startTracking()` | Check resolves as exempted |
|
|
273
|
+
| Runtime permissions | Microphone; notification is also requested on API 33+ | Microphone |
|
|
274
|
+
| Interruption recovery | `resumeTracking()` is unsupported | `resumeTracking()` is available |
|
|
275
|
+
| `requestAnalysis()` promise | Full analysis payload | `{ status: "requested", timestamp }` acknowledgement |
|
|
276
|
+
| Reactive analysis | `onAnalysisResult`, normalized to camelCase | `onAnalysisResult` |
|
|
277
|
+
|
|
278
|
+
### Android foreground behavior
|
|
279
|
+
|
|
280
|
+
Pass notification text to `startTracking()` rather than configuring a separate notification API. The notification is part of the long-running recording service.
|
|
281
|
+
|
|
282
|
+
Test cold restoration by starting tracking, terminating the app process without ending the native session, reopening the app, and verifying that `checkAndRestoreTracking()` reconnects before configuration continues.
|
|
283
|
+
|
|
284
|
+
### iOS interruption recovery
|
|
285
|
+
|
|
286
|
+
A phone call, audio-session conflict, or failed background activation can interrupt recording. When `isRecoveryRequired` is `true`, call `resumeTracking()` after the app enters the foreground.
|
|
287
|
+
|
|
288
|
+
Use an app-owned in-flight guard so repeated foreground events do not issue concurrent resume calls:
|
|
289
|
+
|
|
290
|
+
```tsx
|
|
291
|
+
import { useEffect, useRef } from "react";
|
|
292
|
+
import { AppState } from "react-native";
|
|
293
|
+
import { useAsleep } from "react-native-asleep";
|
|
294
|
+
|
|
295
|
+
export function useAsleepForegroundRecovery() {
|
|
296
|
+
const asleep = useAsleep();
|
|
297
|
+
const resumeInFlight = useRef(false);
|
|
298
|
+
|
|
299
|
+
useEffect(() => {
|
|
300
|
+
const resumeIfNeeded = (appState: string) => {
|
|
301
|
+
if (
|
|
302
|
+
appState !== "active" ||
|
|
303
|
+
!asleep.isRecoveryRequired ||
|
|
304
|
+
resumeInFlight.current
|
|
305
|
+
) {
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
resumeInFlight.current = true;
|
|
310
|
+
void asleep
|
|
311
|
+
.resumeTracking()
|
|
312
|
+
.catch(() => {
|
|
313
|
+
// The classified failure is available reactively as asleep.error.
|
|
314
|
+
})
|
|
315
|
+
.finally(() => {
|
|
316
|
+
resumeInFlight.current = false;
|
|
317
|
+
});
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
resumeIfNeeded(AppState.currentState);
|
|
321
|
+
const subscription = AppState.addEventListener("change", resumeIfNeeded);
|
|
322
|
+
|
|
323
|
+
return () => subscription.remove();
|
|
324
|
+
}, [asleep.isRecoveryRequired, asleep.resumeTracking]);
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
A resolved `resumeTracking()` promise means the resume request was accepted; it does not prove audio upload has recovered. The SDK keeps `status === "recoveryRequired"` until a later successful upload changes it back to `"tracking"`.
|
|
329
|
+
|
|
330
|
+
`resumeTracking()` is iOS-only and throws `UNSUPPORTED_PLATFORM` on Android.
|
|
331
|
+
|
|
332
|
+
## 7. Handle structured errors
|
|
333
|
+
|
|
334
|
+
All actions and queries reject with `AsleepError`. Do not use `null`, an empty array, or parsed message text as a generic error channel.
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
import { AsleepError } from "react-native-asleep";
|
|
338
|
+
|
|
339
|
+
try {
|
|
340
|
+
await asleep.startTracking();
|
|
341
|
+
} catch (cause: unknown) {
|
|
342
|
+
if (!(cause instanceof AsleepError)) throw cause;
|
|
343
|
+
|
|
344
|
+
console.log({
|
|
345
|
+
code: cause.code,
|
|
346
|
+
category: cause.category,
|
|
347
|
+
sdkCode: cause.sdkCode,
|
|
348
|
+
caseName: cause.caseName,
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
Tracking-runtime failures carry an objective recovery classification:
|
|
354
|
+
|
|
355
|
+
| `error.category` | Native state | Required integration behavior |
|
|
356
|
+
|---|---|---|
|
|
357
|
+
| `terminal` | The session is already gone and a separate close event may not follow | Clear app-owned live-session state and allow a new session |
|
|
358
|
+
| `recordingDead` | The recorder stopped, but the native session remains open | Call `stopTracking()` to close it, then start a new session |
|
|
359
|
+
| `recoveryRequired` | The iOS session remains live | Call `resumeTracking()` in the foreground and wait for a successful upload |
|
|
360
|
+
| `transient` | The session survived | Keep tracking and observe later state/events |
|
|
361
|
+
| `unknown` | Not safely classified | Record the error and do not assume tracking is healthy |
|
|
362
|
+
|
|
363
|
+
Only tracking-runtime failures are guaranteed to have `category`; precondition, setup, permission, report, and other action errors may leave it undefined. Use the stable `code` for action-specific behavior.
|
|
364
|
+
|
|
365
|
+
Do not call `stopTracking()` only because `isTracking` became `false`: terminal failures already closed their session. The demonstrated exception is `recordingDead`, where `isTracking` is false but `stopTracking()` is required because native recording stopped without closing the session.
|
|
366
|
+
|
|
367
|
+
Forward the `AsleepError` itself to observability so `cause`, `sdkCode`, and `caseName` remain available. The app decides log severity; the SDK only reports the recovery fact.
|
|
368
|
+
|
|
369
|
+
## 8. Stop tracking and read reports
|
|
370
|
+
|
|
371
|
+
`stopTracking()` closes the active session and marks the public state closed. The final `sessionId` may also arrive through the native close event. Product cleanup—alarms, app timers, cloud state, and navigation—belongs to the app and should occur only after the SDK stop succeeds or a terminal event proves the session is gone.
|
|
372
|
+
|
|
373
|
+
To analyze only part of the recording, pass `stopTracking({ analysisRange: { start, end } })`. The wrapper rejects `INVALID_ARGUMENT` before any native call unless both bounds are valid `Date` objects and `start` is at least one whole second before `end`; the native SDKs would otherwise drop the range and report the failure only after the stop promise resolved. The rest of the stop flow and state handling are identical to a plain stop. A range that passes this check can still be ignored by the server, which then analyzes the full session without notifying the app. Keep the range inside the measured session: a range that starts before the native session start was verified on devices to produce no analyzed data (`missing_data_ratio` 1.0) and later `reanalyze()` then fails with 30410, so do not use an app-side timestamp taken before `startTracking()` resolved. Which window to send (for example, from an in-bed time the user confirmed) is app policy.
|
|
374
|
+
|
|
375
|
+
Report generation may lag behind session close. The wrapper produces `REPORT_NOT_FOUND` when native code resolves without a report payload, but platform SDK failures can arrive under another `AsleepError.code` such as Android `REPORT_ERROR`. Do not blanket-retry every report failure. Until all native not-found codes are normalized by the wrapper, choose retry behavior only for error cases the app has explicitly verified; keep network, authentication, and other failures visible.
|
|
376
|
+
|
|
377
|
+
Report APIs:
|
|
378
|
+
|
|
379
|
+
| Action | Result |
|
|
380
|
+
|---|---|
|
|
381
|
+
| `getReport(sessionId)` | One `AsleepReport`; may throw `REPORT_NOT_FOUND` when native resolves no payload |
|
|
382
|
+
| `getReportList(fromDate, toDate)` | `AsleepSession[]`; an empty array is a valid result |
|
|
383
|
+
| `getAverageReport(fromDate, toDate)` | `AsleepAverageReport`; may throw `REPORT_NOT_FOUND` when native resolves no payload |
|
|
384
|
+
| `deleteSession(sessionId)` | Deletes a session or throws |
|
|
385
|
+
| `reanalyze(sessionId, options?)` | Resolves when the server accepted a reanalysis request; poll `getReport()` for the result |
|
|
386
|
+
|
|
387
|
+
`getReportList()` currently returns at most 100 sessions and has no public pagination API. Pass dates as `YYYY-MM-DD`.
|
|
388
|
+
|
|
389
|
+
### Reanalysis
|
|
390
|
+
|
|
391
|
+
`reanalyze(sessionId)` re-runs server analysis for a closed session; `reanalyze(sessionId, { analysisRange: { start, end } })` restricts it to a window. The promise resolves when the server accepts the request, not when analysis is done. Poll `getReport(sessionId)` until `report.session.state` is `"COMPLETE"`; interval, timeout, and user messaging are app policy.
|
|
392
|
+
|
|
393
|
+
**Reanalyzing without a range replaces any earlier range on the server**, including one set through `stopTracking({ analysisRange })`: the whole session is analyzed and that result overwrites the trimmed one. To keep a window, pass it again.
|
|
394
|
+
|
|
395
|
+
Branch on `error.sdkCode` (code `REANALYZE_FAILED`):
|
|
396
|
+
|
|
397
|
+
| `sdkCode` | Meaning | Suggested handling |
|
|
398
|
+
|---|---|---|
|
|
399
|
+
| 30409 | A reanalysis is already in progress | Poll `getReport()` instead; if retrying, cap attempts with backoff, never loop unboundedly |
|
|
400
|
+
| 30422 | The session is still being tracked | Stop tracking first |
|
|
401
|
+
| 30404 / 30410 | Session not found / data retention expired | Do not retry |
|
|
402
|
+
| 30400 | Server rejected the range | Fix the input |
|
|
403
|
+
| 30401 / 30403 | Unauthorized / not allowed for this customer | Do not retry; check credentials and contract |
|
|
404
|
+
| 30000 / 30500 | Network or server failure | Retry with a bounded policy |
|
|
405
|
+
|
|
406
|
+
Input checks (empty `sessionId`, invalid range) reject with `INVALID_ARGUMENT` before any native call, and calls before the most recent `initAsleepConfig()` has resolved, while a re-init is in progress, or after it failed reject with `MISSING_PREREQUISITE`.
|
|
407
|
+
|
|
408
|
+
## 9. Consume analysis consistently
|
|
409
|
+
|
|
410
|
+
`requestAnalysis()` has different promise results:
|
|
411
|
+
|
|
412
|
+
- Android resolves with the analysis payload and also emits `onAnalysisResult`.
|
|
413
|
+
- iOS resolves with `{ status: "requested", timestamp }`; the result arrives later through `onAnalysisResult`.
|
|
414
|
+
|
|
415
|
+
For cross-platform UI, read `analysisResult` and `isAnalyzing` from `useAsleep()` or subscribe to `onAnalysisResult`. The event transition is the only writer of reactive `analysisResult`, preventing an Android promise and event from updating state twice.
|
|
416
|
+
|
|
417
|
+
```tsx
|
|
418
|
+
import { useAsleep } from "react-native-asleep";
|
|
419
|
+
|
|
420
|
+
export function useLiveSleepAnalysis() {
|
|
421
|
+
const { analysisResult, isAnalyzing, requestAnalysis } = useAsleep();
|
|
422
|
+
|
|
423
|
+
async function refresh() {
|
|
424
|
+
await requestAnalysis();
|
|
425
|
+
// Read `analysisResult`; the promise is not the cross-platform result.
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
return { analysisResult, isAnalyzing, refresh };
|
|
429
|
+
}
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
Android snake_case event payloads are normalized to camelCase before they reach `analysisResult`.
|
|
433
|
+
|
|
434
|
+
## 10. Keep optional product features outside the SDK
|
|
435
|
+
|
|
436
|
+
These concerns are intentionally app-owned:
|
|
437
|
+
|
|
438
|
+
- account authentication and cloud synchronization;
|
|
439
|
+
- alarms, widgets, Live Activities, and notifications unrelated to the Android tracking service;
|
|
440
|
+
- report-derived labels, timeline slots, and product metrics;
|
|
441
|
+
- persistent storage and wall-clock duration;
|
|
442
|
+
- permission-denied UI and retry policy;
|
|
443
|
+
- analytics and observability.
|
|
444
|
+
|
|
445
|
+
Integrate them around SDK state and events. Their failure should not silently skip or replace the SDK's required start, stop, restore, or recovery operations.
|
|
446
|
+
|
|
447
|
+
## Production checklist
|
|
448
|
+
|
|
449
|
+
- [ ] Install an exact package version and create a new native build.
|
|
450
|
+
- [ ] Verify the API key and initialization-failure UI.
|
|
451
|
+
- [ ] Test a cold start with no granted permissions.
|
|
452
|
+
- [ ] Test microphone denial and a later successful request from a user action.
|
|
453
|
+
- [ ] On Android 13+, test both notification grant and denial.
|
|
454
|
+
- [ ] Verify the Android foreground-service notification.
|
|
455
|
+
- [ ] Verify battery exemption, settings return, and the second check.
|
|
456
|
+
- [ ] On Android, start tracking, kill the JavaScript app process, reopen it, and restore the live session.
|
|
457
|
+
- [ ] Verify `initAsleepConfig()` still runs after an Android session is restored.
|
|
458
|
+
- [ ] Keep tracking through background and foreground transitions.
|
|
459
|
+
- [ ] On iOS, trigger an audio interruption and verify foreground recovery through a later upload.
|
|
460
|
+
- [ ] Verify each handled error category against its documented action.
|
|
461
|
+
- [ ] Verify `recordingDead` closes the remaining native session before restart.
|
|
462
|
+
- [ ] Verify a terminal failure does not wait for or synthesize a second close event.
|
|
463
|
+
- [ ] Stop tracking and verify the app distinguishes a pending report from network, authentication, and other failures on both platforms.
|
|
464
|
+
- [ ] Verify analysis UI from `analysisResult` on both platforms.
|
|
465
|
+
- [ ] Run a full-night-length session on representative physical iOS and Android devices.
|
|
466
|
+
|
|
467
|
+
Simulator audio behavior and warm-path testing alone are not sufficient release evidence.
|
|
468
|
+
|
|
469
|
+
## References
|
|
470
|
+
|
|
471
|
+
- [SDK README](../README.md)
|
|
472
|
+
- [Example app](https://github.com/asleep-ai/asleep-sdk-react-native/tree/main/example)
|
|
473
|
+
- [Asleep developer documentation](https://docs.asleep.ai)
|
|
474
|
+
- [GitHub issues](https://github.com/asleep-ai/asleep-sdk-react-native/issues)
|