react-native-asleep 1.0.18 → 1.2.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.md +164 -282
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +52 -23
- package/build/Asleep.types.d.ts +46 -0
- package/build/Asleep.types.d.ts.map +1 -1
- package/build/Asleep.types.js +24 -1
- package/build/Asleep.types.js.map +1 -1
- package/build/AsleepStore.d.ts +45 -41
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +518 -531
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts +11 -108
- package/build/index.d.ts.map +1 -1
- package/build/index.js +18 -183
- package/build/index.js.map +1 -1
- package/build/store/createStore.d.ts +14 -0
- package/build/store/createStore.d.ts.map +1 -0
- package/build/store/createStore.js +63 -0
- package/build/store/createStore.js.map +1 -0
- package/ios/AsleepModule.swift +64 -4
- package/package.json +3 -5
- package/src/Asleep.types.ts +71 -1
- package/src/AsleepStore.ts +733 -740
- package/src/index.ts +37 -281
- package/src/store/createStore.ts +84 -0
package/README.md
CHANGED
|
@@ -4,20 +4,11 @@ Advanced sleep tracking SDK for React Native applications, powered by Asleep's A
|
|
|
4
4
|
|
|
5
5
|
## Status
|
|
6
6
|
|
|
7
|
-
This SDK is under active development.
|
|
7
|
+
This SDK is under active development. v2 has a deliberately small public surface; pin to exact versions and review the [CHANGELOG](./CHANGELOG.md) before upgrading.
|
|
8
8
|
|
|
9
9
|
## Overview
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
### Key Features
|
|
14
|
-
|
|
15
|
-
- **Non-invasive Sleep Tracking**: Uses device microphone for sleep analysis
|
|
16
|
-
- **Real-time Monitoring**: Live tracking status and progress updates
|
|
17
|
-
- **Detailed Sleep Reports**: Comprehensive sleep analysis and metrics
|
|
18
|
-
- **Zustand State Management**: Singleton pattern for consistent state across your app
|
|
19
|
-
- **Cross-platform Support**: Works on both iOS and Android
|
|
20
|
-
- **Event-driven Architecture**: Real-time callbacks for tracking events
|
|
11
|
+
Non-invasive sleep tracking via the device microphone — no wearables required. Detects sleep stages and produces detailed reports. Works on iOS and Android, exposes a single React hook plus typed data models.
|
|
21
12
|
|
|
22
13
|
## Installation
|
|
23
14
|
|
|
@@ -42,13 +33,11 @@ This library uses the Expo Modules API. Bare RN projects need Expo modules insta
|
|
|
42
33
|
2. **Install the package** (`npm install` / `pnpm add` / `yarn add`):
|
|
43
34
|
|
|
44
35
|
```bash
|
|
45
|
-
npm install react-native-asleep
|
|
36
|
+
npm install react-native-asleep
|
|
46
37
|
```
|
|
47
38
|
|
|
48
39
|
3. **iOS**: in `ios/`, run `bundle install` (once) then `bundle exec pod install`. The project's `Gemfile` avoids host Ruby/CocoaPods conflicts. **Android**: no extra step.
|
|
49
40
|
|
|
50
|
-
For permissions, see [Permissions](#2-permissions) below.
|
|
51
|
-
|
|
52
41
|
#### Static framework note
|
|
53
42
|
|
|
54
43
|
The iOS podspec sets `s.static_framework = true`. **Do not add `use_frameworks!` to your `Podfile`.** If your project already requires it, pin to static linkage:
|
|
@@ -87,6 +76,13 @@ The [example app](./example) is the reference setup. Adjacent versions are expec
|
|
|
87
76
|
| Android `compileSdkVersion` | 34 |
|
|
88
77
|
| Android `targetSdkVersion` | 34 |
|
|
89
78
|
|
|
79
|
+
#### Bundled native SDK versions
|
|
80
|
+
|
|
81
|
+
| Platform | Native SDK version |
|
|
82
|
+
|---|---|
|
|
83
|
+
| iOS | 3.2.0 |
|
|
84
|
+
| Android | 3.2.1 |
|
|
85
|
+
|
|
90
86
|
## Setup
|
|
91
87
|
|
|
92
88
|
### 1. Get API Key
|
|
@@ -142,355 +138,241 @@ The library declares its own permissions; the manifest merger combines them into
|
|
|
142
138
|
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
|
|
143
139
|
```
|
|
144
140
|
|
|
145
|
-
`RECORD_AUDIO` and `POST_NOTIFICATIONS` are runtime permissions —
|
|
146
|
-
|
|
147
|
-
## Usage
|
|
141
|
+
`RECORD_AUDIO` and `POST_NOTIFICATIONS` are runtime permissions — request them via `useAsleep().requestRequiredPermissions()` (or `PermissionsAndroid`) before starting tracking.
|
|
148
142
|
|
|
149
|
-
|
|
143
|
+
## Quick Start
|
|
150
144
|
|
|
151
|
-
```
|
|
152
|
-
import
|
|
153
|
-
import {
|
|
154
|
-
import {
|
|
145
|
+
```tsx
|
|
146
|
+
import { useEffect } from "react";
|
|
147
|
+
import { Button, Text, View } from "react-native";
|
|
148
|
+
import { AsleepError, useAsleep } from "react-native-asleep";
|
|
155
149
|
|
|
156
|
-
|
|
150
|
+
function SleepTracker() {
|
|
157
151
|
const {
|
|
158
|
-
|
|
159
|
-
sessionId,
|
|
152
|
+
status,
|
|
160
153
|
isTracking,
|
|
161
154
|
error,
|
|
162
155
|
initAsleepConfig,
|
|
156
|
+
checkAndRestoreTracking,
|
|
157
|
+
checkBatteryOptimization,
|
|
158
|
+
hasRequiredPermissions,
|
|
159
|
+
requestRequiredPermissions,
|
|
163
160
|
startTracking,
|
|
164
161
|
stopTracking,
|
|
165
|
-
getReport,
|
|
166
|
-
enableLog,
|
|
167
162
|
} = useAsleep();
|
|
168
163
|
|
|
164
|
+
// Required order before startTracking: configure -> restore any in-progress session -> battery check
|
|
169
165
|
useEffect(() => {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
// Initialize SDK with your API key
|
|
176
|
-
await initAsleepConfig({
|
|
177
|
-
apiKey: "YOUR_API_KEY",
|
|
178
|
-
userId: "optional-user-id", // Optional: SDK generates one if not provided
|
|
179
|
-
});
|
|
180
|
-
|
|
181
|
-
console.log("SDK initialized successfully");
|
|
182
|
-
} catch (error) {
|
|
183
|
-
console.error("Failed to initialize SDK:", error);
|
|
184
|
-
}
|
|
185
|
-
};
|
|
186
|
-
|
|
187
|
-
initSDK();
|
|
166
|
+
(async () => {
|
|
167
|
+
await initAsleepConfig({ apiKey: "YOUR_API_KEY" });
|
|
168
|
+
await checkAndRestoreTracking();
|
|
169
|
+
await checkBatteryOptimization();
|
|
170
|
+
})();
|
|
188
171
|
}, []);
|
|
189
172
|
|
|
190
|
-
const
|
|
173
|
+
const handleStart = async () => {
|
|
191
174
|
try {
|
|
192
|
-
await
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
|
-
|
|
199
|
-
const handleStopTracking = async () => {
|
|
200
|
-
try {
|
|
201
|
-
await stopTracking();
|
|
202
|
-
console.log("Sleep tracking stopped");
|
|
203
|
-
} catch (error) {
|
|
204
|
-
console.error("Failed to stop tracking:", error);
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
|
|
208
|
-
const handleGetReport = async () => {
|
|
209
|
-
if (!sessionId) return;
|
|
175
|
+
if (!(await hasRequiredPermissions())) {
|
|
176
|
+
const granted = await requestRequiredPermissions();
|
|
177
|
+
if (!granted) return;
|
|
178
|
+
}
|
|
210
179
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
} catch (
|
|
215
|
-
|
|
180
|
+
await startTracking({
|
|
181
|
+
android: { notification: { title: "Sleep tracking", text: "Recording..." } },
|
|
182
|
+
});
|
|
183
|
+
} catch (cause) {
|
|
184
|
+
if (!(cause instanceof AsleepError)) throw cause;
|
|
185
|
+
// `error` is also updated reactively and rendered below.
|
|
216
186
|
}
|
|
217
187
|
};
|
|
218
188
|
|
|
219
189
|
return (
|
|
220
190
|
<View>
|
|
221
|
-
<Text>
|
|
222
|
-
<Text>
|
|
223
|
-
<
|
|
224
|
-
|
|
225
|
-
<Button
|
|
226
|
-
title="Start Tracking"
|
|
227
|
-
onPress={handleStartTracking}
|
|
228
|
-
disabled={isTracking}
|
|
229
|
-
/>
|
|
230
|
-
<Button
|
|
231
|
-
title="Stop Tracking"
|
|
232
|
-
onPress={handleStopTracking}
|
|
233
|
-
disabled={!isTracking}
|
|
234
|
-
/>
|
|
235
|
-
<Button
|
|
236
|
-
title="Get Report"
|
|
237
|
-
onPress={handleGetReport}
|
|
238
|
-
disabled={!sessionId}
|
|
239
|
-
/>
|
|
191
|
+
<Text>Status: {status}</Text>
|
|
192
|
+
{error ? <Text>{error.message}</Text> : null}
|
|
193
|
+
<Button title={isTracking ? "Stop" : "Start"} onPress={isTracking ? stopTracking : handleStart} />
|
|
240
194
|
</View>
|
|
241
195
|
);
|
|
242
|
-
};
|
|
243
|
-
```
|
|
244
|
-
|
|
245
|
-
### Advanced Usage
|
|
246
|
-
|
|
247
|
-
#### Using AsleepSDK for Non-React Components
|
|
248
|
-
|
|
249
|
-
For use outside React components or for singleton access:
|
|
250
|
-
|
|
251
|
-
```typescript
|
|
252
|
-
import { AsleepSDK } from "react-native-asleep";
|
|
253
|
-
|
|
254
|
-
class SleepManager {
|
|
255
|
-
async initializeSDK() {
|
|
256
|
-
try {
|
|
257
|
-
await AsleepSDK.initAsleepConfig({
|
|
258
|
-
apiKey: "YOUR_API_KEY",
|
|
259
|
-
});
|
|
260
|
-
|
|
261
|
-
// Initialize event listeners
|
|
262
|
-
AsleepSDK.initialize();
|
|
263
|
-
|
|
264
|
-
console.log("SDK initialized");
|
|
265
|
-
} catch (error) {
|
|
266
|
-
console.error("SDK initialization failed:", error);
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
async startSleepTracking() {
|
|
271
|
-
await AsleepSDK.startTracking();
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
async stopSleepTracking() {
|
|
275
|
-
return await AsleepSDK.stopTracking();
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
getCurrentStatus() {
|
|
279
|
-
return {
|
|
280
|
-
isTracking: AsleepSDK.isTracking(),
|
|
281
|
-
userId: AsleepSDK.getUserId(),
|
|
282
|
-
sessionId: AsleepSDK.getSessionId(),
|
|
283
|
-
};
|
|
284
|
-
}
|
|
285
196
|
}
|
|
286
197
|
```
|
|
287
198
|
|
|
288
|
-
|
|
199
|
+
For ODA (On-Device Analysis) mode, call `setup()` instead of `initAsleepConfig()`. See [`example/App.tsx`](./example/App.tsx) for the full flow including report fetch and event-driven state.
|
|
289
200
|
|
|
290
|
-
|
|
291
|
-
import { useAsleepStore } from "react-native-asleep";
|
|
201
|
+
## API surface
|
|
292
202
|
|
|
293
|
-
|
|
294
|
-
const currentState = useAsleepStore.getState();
|
|
203
|
+
The v2 API has one reactive hook, one thin imperative escape hatch, and named value/type exports:
|
|
295
204
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
205
|
+
```ts
|
|
206
|
+
import {
|
|
207
|
+
Asleep,
|
|
208
|
+
AsleepError,
|
|
209
|
+
useAsleep,
|
|
210
|
+
type AsleepAverageReport,
|
|
211
|
+
type AsleepReport,
|
|
212
|
+
type AsleepSession,
|
|
213
|
+
type TrackingStatus,
|
|
214
|
+
} from "react-native-asleep";
|
|
303
215
|
```
|
|
304
216
|
|
|
305
|
-
|
|
217
|
+
`useAsleep()` attaches the native listeners while mounted and returns the public state plus bound actions.
|
|
306
218
|
|
|
307
|
-
###
|
|
219
|
+
### Public state
|
|
308
220
|
|
|
309
|
-
|
|
221
|
+
The store keeps native facts internally and derives the public booleans from `status`:
|
|
310
222
|
|
|
311
|
-
|
|
223
|
+
| Field | Meaning |
|
|
224
|
+
|---|---|
|
|
225
|
+
| `status` | `"idle"`, `"tracking"`, `"paused"`, or `"recoveryRequired"` |
|
|
226
|
+
| `isTracking` | `true` for every status except `"idle"`; recovery-required sessions are still live |
|
|
227
|
+
| `isTrackingPaused` | `true` only while `status` is `"paused"` |
|
|
228
|
+
| `isRecoveryRequired` | `true` only while `status` is `"recoveryRequired"` |
|
|
229
|
+
| `isSetupInProgress` / `isSetupComplete` | Derived setup lifecycle |
|
|
230
|
+
| `sessionId` / `userId` | Current native identifiers |
|
|
231
|
+
| `error` | Last `AsleepError`, or `null` |
|
|
232
|
+
| `analysisResult` / `isAnalyzing` | Latest analysis event and request state |
|
|
233
|
+
| `didClose` / `isODAEnabled` / `log` | Session history, mode, and opt-in debug log |
|
|
312
234
|
|
|
313
|
-
|
|
314
|
-
- `sessionId: string | null` - Current session ID
|
|
315
|
-
- `isTracking: boolean` - Whether tracking is active
|
|
316
|
-
- `error: string | null` - Last error message
|
|
317
|
-
- `didClose: boolean` - Whether the last session was closed
|
|
318
|
-
- `log: string` - Latest log message
|
|
235
|
+
`trackingStartTime`, listener bookkeeping, and mutable setters are internal implementation details.
|
|
319
236
|
|
|
320
|
-
|
|
237
|
+
### Actions
|
|
321
238
|
|
|
322
|
-
|
|
323
|
-
- `startTracking(): Promise<void>` - Start sleep tracking
|
|
324
|
-
- `stopTracking(): Promise<void>` - Stop sleep tracking
|
|
325
|
-
- `getReport(sessionId: string): Promise<AsleepReport | null>` - Get sleep report
|
|
326
|
-
- `getReportList(fromDate: string, toDate: string): Promise<AsleepSession[]>` - Get list of reports
|
|
327
|
-
- `enableLog(enabled: boolean): void` - Enable/disable debug logging
|
|
328
|
-
- `setCustomNotification(title: string, text: string): Promise<void>` - Set custom notification (Android only)
|
|
239
|
+
The hook exposes:
|
|
329
240
|
|
|
330
|
-
|
|
241
|
+
- Setup and restore: `setup`, `initAsleepConfig`, `checkAndRestoreTracking`
|
|
242
|
+
- Tracking: `startTracking`, `stopTracking`, `resumeTracking`
|
|
243
|
+
- Reports: `getReport`, `getReportList`, `getAverageReport`, `deleteSession`, `requestAnalysis`
|
|
244
|
+
- Prerequisites: `checkBatteryOptimization`, `requestBatteryOptimizationExemption`, `hasRequiredPermissions`, `requestRequiredPermissions`
|
|
245
|
+
- Utilities: `enableLog`, `clearError`, `addEventListener`, and the deprecated no-op `setCustomNotification`
|
|
331
246
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
```typescript
|
|
335
|
-
interface AsleepConfig {
|
|
336
|
-
apiKey: string; // Required: Your API key
|
|
337
|
-
userId?: string; // Optional: User identifier
|
|
338
|
-
baseUrl?: string; // Optional: Custom API base URL
|
|
339
|
-
callbackUrl?: string; // Optional: Webhook callback URL
|
|
340
|
-
}
|
|
341
|
-
```
|
|
247
|
+
`requestAnalysis()` returns the Android analysis result or the iOS `{ status: "requested", timestamp }` acknowledgement. On both platforms, `onAnalysisResult` is the only writer of reactive `analysisResult`.
|
|
342
248
|
|
|
343
|
-
###
|
|
344
|
-
|
|
345
|
-
Sleep analysis report structure:
|
|
346
|
-
|
|
347
|
-
```typescript
|
|
348
|
-
interface AsleepReport {
|
|
349
|
-
sessionId: string;
|
|
350
|
-
sleepEfficiency: number;
|
|
351
|
-
sleepLatency: number;
|
|
352
|
-
sleepTime: number;
|
|
353
|
-
wakeTime: number;
|
|
354
|
-
lightSleepTime: number;
|
|
355
|
-
deepSleepTime: number;
|
|
356
|
-
remSleepTime: number;
|
|
357
|
-
// ... additional metrics
|
|
358
|
-
}
|
|
359
|
-
```
|
|
249
|
+
### Non-React contexts
|
|
360
250
|
|
|
361
|
-
|
|
251
|
+
Use `Asleep` for background callbacks and other code where hooks are unavailable:
|
|
362
252
|
|
|
363
|
-
|
|
253
|
+
```ts
|
|
254
|
+
import { Asleep } from "react-native-asleep";
|
|
364
255
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
sessionId: string;
|
|
368
|
-
startTime: string;
|
|
369
|
-
endTime: string;
|
|
370
|
-
state: string;
|
|
371
|
-
// ... additional session data
|
|
372
|
-
}
|
|
373
|
-
```
|
|
256
|
+
// Required when no mounted useAsleep() hook owns the native listener lifecycle.
|
|
257
|
+
const teardown = Asleep.initialize();
|
|
374
258
|
|
|
375
|
-
|
|
259
|
+
const unsubscribe = Asleep.subscribe(({ status, error }) => {
|
|
260
|
+
console.log(status, error?.code);
|
|
261
|
+
});
|
|
376
262
|
|
|
377
|
-
|
|
263
|
+
const offAnalysis = Asleep.addEventListener("onAnalysisResult", (result) => {
|
|
264
|
+
console.log(result);
|
|
265
|
+
});
|
|
378
266
|
|
|
379
|
-
|
|
380
|
-
const { userId, sessionId, isTracking, error } = useAsleep();
|
|
267
|
+
await Asleep.getState().stopTracking();
|
|
381
268
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
}, [error]);
|
|
387
|
-
|
|
388
|
-
useEffect(() => {
|
|
389
|
-
if (sessionId) {
|
|
390
|
-
console.log("New session created:", sessionId);
|
|
391
|
-
}
|
|
392
|
-
}, [sessionId]);
|
|
269
|
+
offAnalysis();
|
|
270
|
+
unsubscribe();
|
|
271
|
+
teardown();
|
|
393
272
|
```
|
|
394
273
|
|
|
395
|
-
|
|
274
|
+
`initialize()` is ref-counted, so it is safe to use alongside mounted hooks. Importing the package alone does not attach native listeners.
|
|
396
275
|
|
|
397
|
-
|
|
276
|
+
On iOS, `isRecoveryRequired` becomes `true` when recording cannot resume while the app is in the background. After the app returns to the foreground, call `resumeTracking()`. The flag clears only after the next successful audio upload. `resumeTracking()` is iOS-only and rejects with `UNSUPPORTED_PLATFORM` on Android.
|
|
398
277
|
|
|
399
|
-
|
|
400
|
-
- Handle initialization errors gracefully
|
|
401
|
-
- Store API key securely (use environment variables)
|
|
278
|
+
## Tracking lifecycle and platform compensations
|
|
402
279
|
|
|
403
|
-
|
|
280
|
+
The library handles a number of platform quirks internally so JS sees a consistent event model:
|
|
404
281
|
|
|
405
|
-
-
|
|
406
|
-
-
|
|
407
|
-
-
|
|
282
|
+
- iOS 3.2.1 `closeSessionSilently()` on 403/429 tears down a session without firing `didClose` — the wrapper detects terminal error codes and resets `isTracking` / `isAnalyzing` itself.
|
|
283
|
+
- Android SDK 3.2.x emits both `onFail` and `onFinish` for fatal codes — the wrapper suppresses the spurious `onTrackingClosed` so JS doesn't misread a fatal error as a clean close.
|
|
284
|
+
- iOS interruption recovery may emit duplicate `didResume` events — the wrapper deduplicates while still clearing `error`.
|
|
285
|
+
- iOS audio initialization failure stops recording without closing the native session — stop and restart the session; `resumeTracking()` cannot recover it.
|
|
408
286
|
|
|
409
|
-
|
|
287
|
+
See [AGENTS.md](./AGENTS.md#native-behavior-compensations) for the full table including upstream SDK versions and rationale.
|
|
410
288
|
|
|
411
|
-
|
|
289
|
+
## Error classification
|
|
412
290
|
|
|
413
|
-
|
|
291
|
+
Every failed action and native failure event produces an `AsleepError`, which extends `Error`:
|
|
414
292
|
|
|
415
|
-
|
|
293
|
+
```ts
|
|
294
|
+
class AsleepError extends Error {
|
|
295
|
+
readonly code: string;
|
|
296
|
+
readonly category?: "terminal" | "recordingDead" | "recoveryRequired" | "transient" | "unknown";
|
|
297
|
+
readonly sdkCode?: number;
|
|
298
|
+
readonly caseName?: string;
|
|
299
|
+
readonly cause?: unknown;
|
|
300
|
+
}
|
|
301
|
+
```
|
|
416
302
|
|
|
417
|
-
|
|
418
|
-
import { AsleepSDK } from 'react-native-asleep';
|
|
303
|
+
Branch on the stable `code`, render `message`, and forward the error itself to observability tooling. Tracking failures also carry the library's objective recovery classification in `category`; the app decides what severity to record:
|
|
419
304
|
|
|
420
|
-
|
|
421
|
-
|
|
305
|
+
| `category` | Meaning | Suggested app-side severity |
|
|
306
|
+
|---|---|---|
|
|
307
|
+
| `terminal` | Native session is gone; no `onTrackingClosed` will follow. Start a new session. | error |
|
|
308
|
+
| `recordingDead` | Recorder torn down but the session is still open; `stopTracking()` then start again. | error |
|
|
309
|
+
| `recoveryRequired` | Tracking is alive; call `resumeTracking()` in the foreground (`isRecoveryRequired` is also set). | warning |
|
|
310
|
+
| `transient` | The native session survived (e.g. one upload window failed after internal retries); later uploads continue. | warning |
|
|
311
|
+
| `unknown` | Unclassified code — do not assume it is benign. | error |
|
|
422
312
|
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
Alert.alert(
|
|
426
|
-
'Battery Optimization Required',
|
|
427
|
-
'Sleep tracking requires battery optimization to be disabled for uninterrupted 6-8 hour sessions.',
|
|
428
|
-
[
|
|
429
|
-
{ text: 'Cancel', style: 'cancel' },
|
|
430
|
-
{
|
|
431
|
-
text: 'Open Settings',
|
|
432
|
-
onPress: async () => {
|
|
433
|
-
await AsleepSDK.requestBatteryOptimizationExemption();
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
]
|
|
437
|
-
);
|
|
438
|
-
}
|
|
313
|
+
```ts
|
|
314
|
+
const { error } = useAsleep();
|
|
439
315
|
|
|
440
|
-
|
|
441
|
-
|
|
316
|
+
useEffect(() => {
|
|
317
|
+
if (!error) return;
|
|
318
|
+
if (error.category === "recoveryRequired" || error.category === "transient") {
|
|
319
|
+
analytics.track("asleep_recoverable_error", {
|
|
320
|
+
code: error.code,
|
|
321
|
+
sdkCode: error.sdkCode,
|
|
322
|
+
category: error.category,
|
|
323
|
+
});
|
|
324
|
+
} else {
|
|
325
|
+
Sentry.captureException(error);
|
|
326
|
+
}
|
|
327
|
+
}, [error]);
|
|
442
328
|
```
|
|
443
329
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
- **Android**: Battery optimization can interrupt long-running sleep tracking sessions
|
|
447
|
-
- **iOS**: While not technically needed, the check ensures consistent cross-platform code
|
|
448
|
-
- **Developer Experience**: iOS developers testing only on iOS might miss Android requirements
|
|
449
|
-
- **User Experience**: Prevents tracking failures for Android users of iOS-developed apps
|
|
330
|
+
`sdkCode` is the numeric code documented by the native Asleep SDKs. The legacy `errorCode` event-payload field remains for wire compatibility but is deprecated: on iOS it is a Swift enum ordinal from NSError bridging, not the documented code.
|
|
450
331
|
|
|
451
|
-
|
|
332
|
+
All actions, including report queries, throw `AsleepError` on failure. Queries no longer return `null` or `[]` as failure sentinels. Successful actions clear only the error that was present when the native call began; a classified failure event arriving during the await is preserved.
|
|
452
333
|
|
|
453
|
-
|
|
454
|
-
- Monitor the error state for real-time error updates
|
|
455
|
-
- Provide user-friendly error messages
|
|
334
|
+
## Best practices
|
|
456
335
|
|
|
457
|
-
|
|
336
|
+
- **Permission flow**: use `hasRequiredPermissions()` for a non-interactive check, then call `requestRequiredPermissions()` from a user-initiated flow. `startTracking()` never opens a permission dialog and throws `PERMISSION_DENIED` when permission is missing.
|
|
337
|
+
- **Battery optimization (Android, required)**: long sessions get killed without an exemption. Call `checkBatteryOptimization()` before `startTracking()`; if not exempted, call `requestBatteryOptimizationExemption()` and follow the system prompt. iOS's no-op call keeps cross-platform code uniform.
|
|
338
|
+
- **Error handling**: gate log severity on `useAsleep().error?.category` and switch on `error.code` for category-specific UI rather than parsing message text.
|
|
339
|
+
- **Non-React lifecycle**: pair every `Asleep.initialize()` with its returned teardown function.
|
|
458
340
|
|
|
459
|
-
|
|
460
|
-
- Subscribe to specific state changes when needed
|
|
461
|
-
- Avoid unnecessary re-renders by selecting specific state slices
|
|
341
|
+
## Migrating from 1.x
|
|
462
342
|
|
|
463
|
-
|
|
343
|
+
v2 deliberately removes the parallel and mutable v1 surfaces:
|
|
464
344
|
|
|
465
|
-
|
|
345
|
+
1. `error: string | null` is now `AsleepError | null`. Render `error?.message` and branch on `error?.code`.
|
|
346
|
+
2. `errorInfo` is removed. Read `error.category`, `error.sdkCode`, and `error.caseName`.
|
|
347
|
+
3. Report and analysis queries throw `AsleepError` on failure instead of returning `null` or `[]`. A session that has no report surfaces as code `REPORT_NOT_FOUND`; an empty report list still resolves to `[]`.
|
|
348
|
+
4. Public state setters are removed. Native events and SDK actions are the sole state writers; `clearError()` remains public.
|
|
349
|
+
5. `getTrackingDurationMinutes()` is removed and `trackingStartTime` is internal. Apps own wall-clock duration.
|
|
350
|
+
6. `requestMicrophonePermission()` is removed. Use `requestRequiredPermissions()`.
|
|
351
|
+
7. `startTracking()` no longer requests permission. Check with `hasRequiredPermissions()`, explicitly request if needed, then start.
|
|
352
|
+
8. The default export, `Asleep` class, `AsleepSDK`, and raw `asleepStore` export are removed. Use `useAsleep()` or the named `Asleep` escape hatch.
|
|
353
|
+
9. `zustand` is no longer a dependency. Remove it from your app if nothing else uses it.
|
|
354
|
+
10. Use the additive `status: TrackingStatus` field when a single lifecycle value is clearer than multiple derived booleans.
|
|
355
|
+
11. Android 13+: `requestRequiredPermissions()` still requests `POST_NOTIFICATIONS` (so the foreground-service notification stays visible), but its return value now reflects only what tracking needs to run — microphone-side permissions, matching `hasRequiredPermissions()`. In 1.x a denied notification permission made it return `false` even though tracking could start.
|
|
466
356
|
|
|
467
357
|
## Troubleshooting
|
|
468
358
|
|
|
469
|
-
|
|
359
|
+
- **`PERMISSION_DENIED` from `startTracking`**: check and request microphone permission from a user-initiated flow, then retry.
|
|
360
|
+
- **`MISSING_PREREQUISITE` from `startTracking`**: call `checkAndRestoreTracking()` and `checkBatteryOptimization()` before `startTracking()`.
|
|
361
|
+
- **Tracking ends unexpectedly on Android**: battery optimization is on; call `checkBatteryOptimization()` and follow the prompt.
|
|
362
|
+
- **Network errors**: verify API key and connectivity.
|
|
470
363
|
|
|
471
|
-
|
|
472
|
-
2. **SDK Not Initialized**: Call `initAsleepConfig` before other methods
|
|
473
|
-
3. **Network Errors**: Check internet connection and API key validity
|
|
474
|
-
4. **Battery Optimization Error**: Call `checkBatteryOptimization()` before `startTracking()` on all platforms
|
|
475
|
-
5. **Android Tracking Interrupted**: Ensure battery optimization is disabled via system settings
|
|
364
|
+
Enable debug logs with `useAsleep().enableLog(true)`.
|
|
476
365
|
|
|
477
|
-
|
|
366
|
+
## Example app
|
|
478
367
|
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
```typescript
|
|
482
|
-
const { enableLog } = useAsleep();
|
|
483
|
-
enableLog(true);
|
|
484
|
-
```
|
|
368
|
+
See [`example/`](./example) for a full implementation.
|
|
485
369
|
|
|
486
370
|
## License
|
|
487
371
|
|
|
488
|
-
|
|
372
|
+
MIT.
|
|
489
373
|
|
|
490
374
|
## Support
|
|
491
375
|
|
|
492
|
-
For issues and support:
|
|
493
|
-
|
|
494
376
|
- [GitHub Issues](https://github.com/asleep-ai/asleep-sdk-react-native/issues)
|
|
495
377
|
- [Asleep Documentation](https://docs.asleep.ai)
|
|
496
378
|
- [Asleep Dashboard](https://dashboard.asleep.ai)
|