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
package/README.md
CHANGED
|
@@ -1,56 +1,85 @@
|
|
|
1
1
|
# react-native-asleep
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[English](./README.md) | [한국어](./README.ko.md)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Sleep tracking for React Native and Expo apps, powered by Asleep's AI technology. The SDK uses the device microphone, requires no wearable, and exposes one React hook plus typed data models for iOS and Android.
|
|
6
6
|
|
|
7
|
-
This SDK is under active development. v2 has a deliberately small public surface
|
|
7
|
+
> This SDK is under active development. v2 has a deliberately small public surface. Pin exact versions and review the [changelog](./CHANGELOG.md) before upgrading.
|
|
8
8
|
|
|
9
|
-
##
|
|
9
|
+
## What is included
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
- Microphone-based sleep tracking and Android service restoration
|
|
12
|
+
- Sleep reports, session lists, average reports, and in-progress analysis
|
|
13
|
+
- A shared state model across iOS and Android
|
|
14
|
+
- Structured `AsleepError` values with recovery categories
|
|
15
|
+
- `useAsleep()` for React and a small `Asleep` API for non-React code
|
|
16
|
+
|
|
17
|
+
## Requirements
|
|
18
|
+
|
|
19
|
+
| Component | Minimum |
|
|
20
|
+
|---|---|
|
|
21
|
+
| React Native | 0.74 |
|
|
22
|
+
| React | 18.2 |
|
|
23
|
+
| iOS deployment target | 14.0 |
|
|
24
|
+
| Android `minSdkVersion` | 24 |
|
|
25
|
+
|
|
26
|
+
The example app is currently verified with React Native 0.79.2, Expo 53, React 19.0.0, and Android compile/target SDK 34.
|
|
27
|
+
|
|
28
|
+
Bundled native SDK versions. The React Native package follows its own semver; its version number does not mirror the native SDKs.
|
|
29
|
+
|
|
30
|
+
| react-native-asleep | iOS SDK | Android SDK |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| 2.1.0 | 3.3.3 | 3.3.1 |
|
|
33
|
+
| 2.0.0 | 3.3.2 | 3.3.1 |
|
|
34
|
+
| 1.0.17 – 1.2.0 | 3.2.0 | 3.2.1 |
|
|
35
|
+
| 1.0.15 | 3.2.0 | 3.2.0 |
|
|
36
|
+
| 1.0.14 | 3.1.8 | 3.1.5 |
|
|
37
|
+
| 1.0.13 | 3.1.6 | 3.1.4 |
|
|
38
|
+
|
|
39
|
+
1.2.0 already contained the breaking v2 API; 2.0.0 is the semver-correct release of that API.
|
|
12
40
|
|
|
13
41
|
## Installation
|
|
14
42
|
|
|
15
|
-
###
|
|
43
|
+
### Expo projects
|
|
16
44
|
|
|
17
45
|
```bash
|
|
18
46
|
expo install react-native-asleep
|
|
19
47
|
```
|
|
20
48
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
This library uses the Expo Modules API. Bare RN projects need Expo modules installed once; after that, autolinking handles the rest — no `react-native.config.js` or manual native linking.
|
|
49
|
+
This package contains native modules, so create a new development or store build after installing or upgrading it. It does not run in Expo Go and cannot be upgraded through an OTA update alone.
|
|
24
50
|
|
|
25
|
-
|
|
51
|
+
### Bare React Native projects
|
|
26
52
|
|
|
27
|
-
|
|
28
|
-
npx install-expo-modules@latest
|
|
29
|
-
```
|
|
53
|
+
This library uses the Expo Modules API. Install Expo modules once if the app does not already use them:
|
|
30
54
|
|
|
31
|
-
|
|
55
|
+
```bash
|
|
56
|
+
npx install-expo-modules@latest
|
|
57
|
+
npm install react-native-asleep
|
|
58
|
+
```
|
|
32
59
|
|
|
33
|
-
|
|
60
|
+
Then install iOS pods:
|
|
34
61
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
62
|
+
```bash
|
|
63
|
+
cd ios
|
|
64
|
+
bundle install
|
|
65
|
+
bundle exec pod install
|
|
66
|
+
```
|
|
38
67
|
|
|
39
|
-
|
|
68
|
+
Android needs no additional linking step.
|
|
40
69
|
|
|
41
|
-
#### Static
|
|
70
|
+
#### Static frameworks
|
|
42
71
|
|
|
43
|
-
The iOS
|
|
72
|
+
The iOS pod is a static framework. Do not add `use_frameworks!` only for this package. If the app already requires it, use static linkage:
|
|
44
73
|
|
|
45
74
|
```ruby
|
|
46
75
|
use_frameworks! :linkage => :static
|
|
47
76
|
```
|
|
48
77
|
|
|
49
|
-
|
|
78
|
+
Dynamic linkage is known to break Expo SDK 55 builds; see [expo/expo#44487](https://github.com/expo/expo/issues/44487) and [expo/expo#41556](https://github.com/expo/expo/issues/41556).
|
|
50
79
|
|
|
51
|
-
####
|
|
80
|
+
#### Monorepos and workspaces
|
|
52
81
|
|
|
53
|
-
If `react-native-asleep` is hoisted to a parent `node_modules`, configure autolinking in
|
|
82
|
+
If `react-native-asleep` is hoisted to a parent `node_modules`, configure Expo autolinking in the app's `package.json`:
|
|
54
83
|
|
|
55
84
|
```json
|
|
56
85
|
{
|
|
@@ -62,49 +91,22 @@ If `react-native-asleep` is hoisted to a parent `node_modules`, configure autoli
|
|
|
62
91
|
}
|
|
63
92
|
```
|
|
64
93
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
The [example app](./example) is the reference setup. Adjacent versions are expected to work but aren't verified.
|
|
94
|
+
## Native configuration
|
|
68
95
|
|
|
69
|
-
|
|
70
|
-
| --------------------------- | -------- |
|
|
71
|
-
| React Native | 0.79.2 |
|
|
72
|
-
| Expo | 53 |
|
|
73
|
-
| React | 19.0.0 |
|
|
74
|
-
| iOS deployment target | 14.0 |
|
|
75
|
-
| Android `minSdkVersion` | 24 |
|
|
76
|
-
| Android `compileSdkVersion` | 34 |
|
|
77
|
-
| Android `targetSdkVersion` | 34 |
|
|
78
|
-
|
|
79
|
-
#### Bundled native SDK versions
|
|
80
|
-
|
|
81
|
-
| Platform | Native SDK version |
|
|
82
|
-
|---|---|
|
|
83
|
-
| iOS | 3.2.0 |
|
|
84
|
-
| Android | 3.2.1 |
|
|
96
|
+
Create an API key in the [Asleep Dashboard](https://dashboard.asleep.ai).
|
|
85
97
|
|
|
86
|
-
|
|
98
|
+
### iOS
|
|
87
99
|
|
|
88
|
-
|
|
100
|
+
Your app must declare microphone usage and background audio.
|
|
89
101
|
|
|
90
|
-
|
|
91
|
-
2. Create an account and generate your API key
|
|
92
|
-
3. Note your API key for configuration
|
|
93
|
-
|
|
94
|
-
### 2. Permissions
|
|
95
|
-
|
|
96
|
-
#### iOS — declared by your app
|
|
97
|
-
|
|
98
|
-
Add the microphone usage description and audio background mode.
|
|
99
|
-
|
|
100
|
-
**For Expo Managed Projects (app.json):**
|
|
102
|
+
For Expo projects:
|
|
101
103
|
|
|
102
104
|
```json
|
|
103
105
|
{
|
|
104
106
|
"expo": {
|
|
105
107
|
"ios": {
|
|
106
108
|
"infoPlist": {
|
|
107
|
-
"NSMicrophoneUsageDescription": "This app
|
|
109
|
+
"NSMicrophoneUsageDescription": "This app uses the microphone for sleep tracking.",
|
|
108
110
|
"UIBackgroundModes": ["audio"]
|
|
109
111
|
}
|
|
110
112
|
}
|
|
@@ -112,264 +114,336 @@ Add the microphone usage description and audio background mode.
|
|
|
112
114
|
}
|
|
113
115
|
```
|
|
114
116
|
|
|
115
|
-
|
|
117
|
+
For bare React Native projects, add the equivalent entries to the app's `Info.plist`:
|
|
116
118
|
|
|
117
119
|
```xml
|
|
118
120
|
<key>NSMicrophoneUsageDescription</key>
|
|
119
|
-
<string>This app
|
|
121
|
+
<string>This app uses the microphone for sleep tracking.</string>
|
|
120
122
|
<key>UIBackgroundModes</key>
|
|
121
123
|
<array>
|
|
122
124
|
<string>audio</string>
|
|
123
125
|
</array>
|
|
124
126
|
```
|
|
125
127
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
The library declares its own permissions; the manifest merger combines them into your app. No `<uses-permission>` entries are needed in your `AndroidManifest.xml`. For reference, the library declares:
|
|
128
|
+
### Android
|
|
129
129
|
|
|
130
|
-
|
|
131
|
-
<uses-permission android:name="android.permission.INTERNET" />
|
|
132
|
-
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
|
133
|
-
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
|
134
|
-
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
|
135
|
-
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
|
136
|
-
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
|
137
|
-
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
|
138
|
-
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
|
|
139
|
-
```
|
|
130
|
+
The library declares its required permissions and foreground service in its manifest. The manifest merger adds them to the app, so do not duplicate them only for this SDK.
|
|
140
131
|
|
|
141
|
-
`RECORD_AUDIO`
|
|
132
|
+
`RECORD_AUDIO` is required at runtime. On Android 13 and later, `requestRequiredPermissions()` also requests `POST_NOTIFICATIONS` so the foreground-service notification can remain visible, but notification denial does not make its return value `false`.
|
|
142
133
|
|
|
143
134
|
## Quick Start
|
|
144
135
|
|
|
136
|
+
The required startup order is:
|
|
137
|
+
|
|
138
|
+
```text
|
|
139
|
+
check for an existing Android tracking service
|
|
140
|
+
→ initialize the SDK configuration
|
|
141
|
+
→ check battery optimization
|
|
142
|
+
→ request permissions from a user action
|
|
143
|
+
→ start tracking
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Always call `initAsleepConfig()` after `checkAndRestoreTracking()`, including when an Android service session was restored. On iOS, the restoration check is a required cross-platform prerequisite but reports no persistent service.
|
|
147
|
+
|
|
145
148
|
```tsx
|
|
146
|
-
import { useEffect } from "react";
|
|
149
|
+
import { useEffect, useRef, useState } from "react";
|
|
147
150
|
import { Button, Text, View } from "react-native";
|
|
148
151
|
import { AsleepError, useAsleep } from "react-native-asleep";
|
|
149
152
|
|
|
150
|
-
function SleepTracker() {
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
checkAndRestoreTracking,
|
|
157
|
-
checkBatteryOptimization,
|
|
158
|
-
hasRequiredPermissions,
|
|
159
|
-
requestRequiredPermissions,
|
|
160
|
-
startTracking,
|
|
161
|
-
stopTracking,
|
|
162
|
-
} = useAsleep();
|
|
163
|
-
|
|
164
|
-
// Required order before startTracking: configure -> restore any in-progress session -> battery check
|
|
153
|
+
export function SleepTracker() {
|
|
154
|
+
const asleep = useAsleep();
|
|
155
|
+
const hasBootstrapped = useRef(false);
|
|
156
|
+
const [isReady, setIsReady] = useState(false);
|
|
157
|
+
const [bootstrapMessage, setBootstrapMessage] = useState<string | null>(null);
|
|
158
|
+
|
|
165
159
|
useEffect(() => {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
160
|
+
if (hasBootstrapped.current) return;
|
|
161
|
+
hasBootstrapped.current = true;
|
|
162
|
+
|
|
163
|
+
async function bootstrap() {
|
|
164
|
+
await asleep.checkAndRestoreTracking();
|
|
165
|
+
|
|
166
|
+
const config = { apiKey: "YOUR_API_KEY" };
|
|
167
|
+
await asleep.initAsleepConfig(config);
|
|
168
|
+
|
|
169
|
+
await asleep.checkBatteryOptimization();
|
|
170
|
+
setIsReady(true);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
void bootstrap().catch((cause: unknown) => {
|
|
174
|
+
setBootstrapMessage(cause instanceof Error ? cause.message : String(cause));
|
|
175
|
+
});
|
|
176
|
+
}, [
|
|
177
|
+
asleep.checkAndRestoreTracking,
|
|
178
|
+
asleep.initAsleepConfig,
|
|
179
|
+
asleep.checkBatteryOptimization,
|
|
180
|
+
]);
|
|
181
|
+
|
|
182
|
+
async function start() {
|
|
174
183
|
try {
|
|
175
|
-
if (!(await hasRequiredPermissions())) {
|
|
176
|
-
const granted = await requestRequiredPermissions();
|
|
184
|
+
if (!(await asleep.hasRequiredPermissions())) {
|
|
185
|
+
const granted = await asleep.requestRequiredPermissions();
|
|
177
186
|
if (!granted) return;
|
|
178
187
|
}
|
|
179
188
|
|
|
180
|
-
await
|
|
181
|
-
|
|
189
|
+
const battery = await asleep.checkBatteryOptimization();
|
|
190
|
+
if (!battery.exempted) {
|
|
191
|
+
await asleep.requestBatteryOptimizationExemption();
|
|
192
|
+
return; // Check again after the user returns from Android settings.
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
await asleep.startTracking({
|
|
196
|
+
android: {
|
|
197
|
+
notification: {
|
|
198
|
+
title: "Sleep tracking",
|
|
199
|
+
text: "Sleep analysis is running.",
|
|
200
|
+
},
|
|
201
|
+
},
|
|
182
202
|
});
|
|
183
|
-
} catch (cause) {
|
|
203
|
+
} catch (cause: unknown) {
|
|
184
204
|
if (!(cause instanceof AsleepError)) throw cause;
|
|
185
|
-
//
|
|
205
|
+
// The same AsleepError is also available reactively as asleep.error.
|
|
186
206
|
}
|
|
187
|
-
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function stop() {
|
|
210
|
+
try {
|
|
211
|
+
await asleep.stopTracking();
|
|
212
|
+
} catch (cause: unknown) {
|
|
213
|
+
if (!(cause instanceof AsleepError)) throw cause;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const shouldStop =
|
|
218
|
+
asleep.isTracking || asleep.error?.category === "recordingDead";
|
|
188
219
|
|
|
189
220
|
return (
|
|
190
221
|
<View>
|
|
191
|
-
<Text>Status: {status}</Text>
|
|
192
|
-
{
|
|
193
|
-
|
|
222
|
+
<Text>Status: {asleep.status}</Text>
|
|
223
|
+
{bootstrapMessage ? <Text>{bootstrapMessage}</Text> : null}
|
|
224
|
+
{asleep.error ? <Text>{asleep.error.message}</Text> : null}
|
|
225
|
+
<Button
|
|
226
|
+
title={shouldStop ? "Stop tracking" : "Start tracking"}
|
|
227
|
+
disabled={!isReady}
|
|
228
|
+
onPress={shouldStop ? stop : start}
|
|
229
|
+
/>
|
|
194
230
|
</View>
|
|
195
231
|
);
|
|
196
232
|
}
|
|
197
233
|
```
|
|
198
234
|
|
|
199
|
-
|
|
235
|
+
Call `requestRequiredPermissions()` from a user-driven interaction. `startTracking()` checks permission but never opens a permission dialog. On Android, return from the battery settings screen and call `checkBatteryOptimization()` again before retrying.
|
|
236
|
+
|
|
237
|
+
`await initAsleepConfig()` resolves after the native user join completes and rejects when it fails, on both platforms. Await the action rather than `onUserJoined`: the Android restored-service fast path resolves without emitting that event. A second call while one is still in progress rejects with `OPERATION_IN_PROGRESS`, so finish (or fail) one init before starting another, for example when switching users. 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.
|
|
238
|
+
|
|
239
|
+
The `recordingDead` category is another deliberate exception: `isTracking` is `false`, but the native session remains open, so the action must still call `stopTracking()` before starting a new session.
|
|
200
240
|
|
|
201
|
-
|
|
241
|
+
For ODA (On-Device Analysis), `setup()` is the configuration entry point for a new ODA session. This Quick Start documents service mode; `setup()` cannot run while a restored session is tracking.
|
|
202
242
|
|
|
203
|
-
|
|
243
|
+
## Core API
|
|
204
244
|
|
|
205
245
|
```ts
|
|
206
246
|
import {
|
|
207
247
|
Asleep,
|
|
208
248
|
AsleepError,
|
|
209
249
|
useAsleep,
|
|
210
|
-
type AsleepAverageReport,
|
|
211
250
|
type AsleepReport,
|
|
212
251
|
type AsleepSession,
|
|
213
252
|
type TrackingStatus,
|
|
214
253
|
} from "react-native-asleep";
|
|
215
254
|
```
|
|
216
255
|
|
|
217
|
-
|
|
256
|
+
### Credentials
|
|
257
|
+
|
|
258
|
+
`setup()` and `initAsleepConfig()` accept exactly one credential form, typed as `AsleepCredentials`:
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
const asleep = useAsleep();
|
|
262
|
+
|
|
263
|
+
await asleep.initAsleepConfig({ apiKey: "YOUR_API_KEY", userId });
|
|
264
|
+
// or token authentication
|
|
265
|
+
await asleep.initAsleepConfig({ appId: "YOUR_APP_ID", appSecret: "YOUR_APP_SECRET", userId });
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
Mixing `apiKey` with `appId`/`appSecret` is a type error. At runtime, passing neither form, both forms, an incomplete pair, or an empty string rejects with `AsleepError` code `INVALID_ARGUMENT` before any native call. Keep the secret out of source control like the API key.
|
|
269
|
+
|
|
270
|
+
### Device registration
|
|
271
|
+
|
|
272
|
+
`setup()` can register the hardware product the app runs on with Asleep (`POST customer/v1/products`). Pass `productInfo` with either credential form:
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import type { AsleepProductInfo } from "react-native-asleep";
|
|
276
|
+
|
|
277
|
+
const productInfo: AsleepProductInfo = {
|
|
278
|
+
model: "YOUR_PRODUCT_MODEL",
|
|
279
|
+
identifierType: "serial", // or "mac_address"
|
|
280
|
+
identifierValue: deviceSerialNumber,
|
|
281
|
+
};
|
|
282
|
+
await asleep.setup({ apiKey: "YOUR_API_KEY", productInfo });
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Behavior as of iOS SDK 3.3.3 and Android SDK 3.3.1:
|
|
286
|
+
|
|
287
|
+
- Only `setup()` accepts `productInfo`; `initAsleepConfig()` does not. Sessions created after a successful registration are bound to the product, so register before `startTracking()`. Omitting `productInfo` skips registration and keeps the previous `setup()` behavior.
|
|
288
|
+
- `model` is 1-100 characters and `identifierValue` 1-255 characters; neither may be blank, and values are sent untrimmed. `identifierType` is `"serial"` or `"mac_address"`. Invalid or unknown fields reject with `INVALID_ARGUMENT` before any native call.
|
|
289
|
+
- Registration is idempotent per identifier: the same `identifierType` and `identifierValue` return the existing product credential, and a device that already holds a credential for the same credentials owner and the same `productInfo` makes no network call. The server keeps the first `model` registered for an identifier; it cannot be changed through the SDK.
|
|
290
|
+
- A different identifier creates a new product on the server, which may be billable. Use the device's real serial number or MAC address, and never send placeholder or test values with production credentials.
|
|
291
|
+
- Changing the `apiKey` or `appId` drops the stored credential, and the next `setup()` with `productInfo` registers again.
|
|
292
|
+
- Registration blocks `setup()`. A failure fails the whole setup with code `SETUP_FAILED` and `error.sdkCode` 13400 (rejected: a 4xx other than 429, or failed input checks; fix the input or the contract) or 13000 (network, 5xx, 429, or an unreadable response; retry later). The SDK retries network failures, 5xx and 429 after 2, 4 and 8 seconds before reporting 13000. Offline, the failure can take about 1.5-3 minutes to arrive. After a failure the native SDK is left unconfigured and `setup()` can be called again.
|
|
293
|
+
- On Android, `setup()` resolves after registration and setup complete. On iOS, `setup()` returns once the native call starts, and `isSetupComplete` can be `true` before registration finishes. Wait for `onSetupDidComplete` or `onSetupDidFail` through `addEventListener()` before starting tracking, and do not call `setup()` again until one arrives: the native SDK ignores a second `setup()` while one is running, without a callback.
|
|
294
|
+
|
|
295
|
+
### `useAsleep()`
|
|
218
296
|
|
|
219
|
-
|
|
297
|
+
The primary React API. It attaches the ref-counted native listeners while mounted and returns state plus actions from the shared SDK store.
|
|
220
298
|
|
|
221
|
-
|
|
299
|
+
Important state:
|
|
222
300
|
|
|
223
301
|
| Field | Meaning |
|
|
224
302
|
|---|---|
|
|
225
303
|
| `status` | `"idle"`, `"tracking"`, `"paused"`, or `"recoveryRequired"` |
|
|
226
|
-
| `isTracking` | `true` for every status except `"idle"
|
|
227
|
-
| `isTrackingPaused` |
|
|
228
|
-
| `isRecoveryRequired` |
|
|
229
|
-
| `
|
|
230
|
-
| `sessionId
|
|
231
|
-
| `
|
|
232
|
-
| `
|
|
233
|
-
| `didClose` / `isODAEnabled` / `log` | Session history, mode, and opt-in debug log |
|
|
304
|
+
| `isTracking` | `true` for every status except `"idle"` |
|
|
305
|
+
| `isTrackingPaused` | The native session is temporarily interrupted |
|
|
306
|
+
| `isRecoveryRequired` | iOS needs an explicit foreground `resumeTracking()` |
|
|
307
|
+
| `isSetupComplete` | SDK configuration completed |
|
|
308
|
+
| `sessionId`, `userId` | Current native identifiers |
|
|
309
|
+
| `analysisResult`, `isAnalyzing` | Latest analysis event and request state |
|
|
310
|
+
| `error` | The latest `AsleepError`, or `null` |
|
|
234
311
|
|
|
235
|
-
|
|
312
|
+
Important actions:
|
|
236
313
|
|
|
237
|
-
|
|
314
|
+
| Area | Actions |
|
|
315
|
+
|---|---|
|
|
316
|
+
| Configuration and restore | `setup`, `initAsleepConfig`, `checkAndRestoreTracking` |
|
|
317
|
+
| Prerequisites | `checkBatteryOptimization`, `requestBatteryOptimizationExemption`, `hasRequiredPermissions`, `requestRequiredPermissions` |
|
|
318
|
+
| Tracking | `startTracking`, `stopTracking`, `resumeTracking` |
|
|
319
|
+
| Reports | `getReport`, `getReportList`, `getAverageReport`, `deleteSession`, `reanalyze` |
|
|
320
|
+
| Analysis | `requestAnalysis` |
|
|
321
|
+
| User metadata | `saveUserMetadata`, `fetchUserMetadata` |
|
|
322
|
+
| Utilities | `addEventListener`, `enableLog`, `clearError` |
|
|
323
|
+
|
|
324
|
+
### Analysis range at stop
|
|
238
325
|
|
|
239
|
-
|
|
326
|
+
`stopTracking()` accepts an optional window that the server analyzes instead of the whole recording:
|
|
240
327
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
328
|
+
```ts
|
|
329
|
+
await asleep.stopTracking({
|
|
330
|
+
analysisRange: { start: bedtime, end: new Date() },
|
|
331
|
+
});
|
|
332
|
+
```
|
|
246
333
|
|
|
247
|
-
`
|
|
334
|
+
`start` must be at least one whole second before `end`, and both must be valid `Date` objects; otherwise the call rejects with `INVALID_ARGUMENT` before any native call. Without options, `stopTracking()` behaves exactly as before. The server may silently ignore a range it does not accept and analyze the full session; the session still closes normally and the app receives no signal that the range was dropped, so verify the result with `getReport()` when the window matters. Keep the range inside the measured session: a range that starts before the native session start was verified on devices to produce a session with no analyzed data (`missing_data_ratio` 1.0, `TOO_MANY_DEFECTS_IN_SLEEP_STAGES`), so derive `start` from a time you know is after tracking began rather than from an earlier app-side timestamp.
|
|
248
335
|
|
|
249
|
-
###
|
|
336
|
+
### Reanalysis
|
|
250
337
|
|
|
251
|
-
|
|
338
|
+
`reanalyze(sessionId, options?)` asks the server to analyze a closed session again, optionally restricted to `options.analysisRange`:
|
|
252
339
|
|
|
253
340
|
```ts
|
|
254
|
-
|
|
341
|
+
await asleep.reanalyze(sessionId, { analysisRange: { start, end } });
|
|
342
|
+
// Resolves when the server accepted the request, not when analysis finished.
|
|
343
|
+
// Poll getReport(sessionId) until report.session.state is "COMPLETE".
|
|
344
|
+
```
|
|
255
345
|
|
|
256
|
-
|
|
257
|
-
const teardown = Asleep.initialize();
|
|
346
|
+
> **Reanalyzing without a range replaces any earlier range on the server**, including one passed to `stopTracking({ analysisRange })`. Pass the range again to keep it.
|
|
258
347
|
|
|
259
|
-
|
|
260
|
-
console.log(status, error?.code);
|
|
261
|
-
});
|
|
348
|
+
An empty `sessionId` or an invalid range rejects with `INVALID_ARGUMENT` before any native call, and calling before the most recent `initAsleepConfig()` has resolved, while a re-init is in progress, or after it failed rejects with `MISSING_PREREQUISITE`. Server failures reject with code `REANALYZE_FAILED` and keep the SDK code in `error.sdkCode`: 30000 (generic/network), 30400, 30401, 30403, 30404, 30409 (reanalysis already in progress: back off, do not retry unboundedly), 30410 (data retention expired), 30422 (the session is still tracking), 30500.
|
|
262
349
|
|
|
263
|
-
|
|
264
|
-
console.log(result);
|
|
265
|
-
});
|
|
350
|
+
### User metadata
|
|
266
351
|
|
|
267
|
-
|
|
352
|
+
After `initAsleepConfig()` completes, the app can save optional profile data that the server uses for analysis:
|
|
268
353
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
teardown();
|
|
272
|
-
```
|
|
354
|
+
```ts
|
|
355
|
+
import type { AsleepUserMetadata } from "react-native-asleep";
|
|
273
356
|
|
|
274
|
-
|
|
357
|
+
const metadata: AsleepUserMetadata = { birthYear: 1990, gender: "female", height: 165.5 };
|
|
358
|
+
await asleep.saveUserMetadata(metadata);
|
|
275
359
|
|
|
276
|
-
|
|
360
|
+
const saved = await asleep.fetchUserMetadata(); // AsleepUserMetadata | null
|
|
361
|
+
```
|
|
277
362
|
|
|
278
|
-
|
|
363
|
+
Every field is optional and omitted fields are not sent. Out-of-range values reject with `INVALID_ARGUMENT` before any native call: `birthYear` 1900-2100, `birthMonth` 1-12, `birthDay` 1-31 (integers), `height` 1-500 cm, `weight` 1-1000 kg, and `gender` one of `"male"`, `"female"`, `"non_binary"`, `"other"`, `"prefer_not_to_say"`. Call them after the most recent `initAsleepConfig()` has resolved. Calling them before that, while a re-init is in progress, or after it failed rejects with `MISSING_PREREQUISITE`, so a failed re-init never reads or writes the previous user's profile. `setup()` also invalidates the user config: call `initAsleepConfig()` again after it. Native failures keep the SDK code in `error.sdkCode`: 27400 (server validation, code `INVALID_ARGUMENT`), 27000 (`SAVE_USER_METADATA_FAILED`), 27100 (`FETCH_USER_METADATA_FAILED`). `fetchUserMetadata()` resolves `null` when nothing has been saved.
|
|
279
364
|
|
|
280
|
-
|
|
365
|
+
### `Asleep`
|
|
281
366
|
|
|
282
|
-
|
|
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.
|
|
367
|
+
Use the imperative escape hatch where React hooks are unavailable:
|
|
286
368
|
|
|
287
|
-
|
|
369
|
+
```ts
|
|
370
|
+
import { Asleep } from "react-native-asleep";
|
|
288
371
|
|
|
289
|
-
|
|
372
|
+
const releaseListeners = Asleep.initialize();
|
|
373
|
+
const unsubscribe = Asleep.subscribe((state) => {
|
|
374
|
+
console.log(state.status, state.error?.code);
|
|
375
|
+
});
|
|
290
376
|
|
|
291
|
-
|
|
377
|
+
console.log(Asleep.getState().status);
|
|
292
378
|
|
|
293
|
-
|
|
294
|
-
|
|
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
|
-
}
|
|
379
|
+
unsubscribe();
|
|
380
|
+
releaseListeners();
|
|
301
381
|
```
|
|
302
382
|
|
|
303
|
-
|
|
383
|
+
`Asleep.initialize()` is ref-counted and must be paired with its returned cleanup function. Importing the package alone does not attach native listeners.
|
|
304
384
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
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 |
|
|
385
|
+
### Errors
|
|
386
|
+
|
|
387
|
+
Every failed action throws `AsleepError`; the same error is stored in `useAsleep().error` when applicable.
|
|
312
388
|
|
|
313
389
|
```ts
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
if (
|
|
318
|
-
|
|
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);
|
|
390
|
+
try {
|
|
391
|
+
await asleep.startTracking();
|
|
392
|
+
} catch (cause: unknown) {
|
|
393
|
+
if (cause instanceof AsleepError) {
|
|
394
|
+
console.log(cause.code, cause.category, cause.sdkCode);
|
|
326
395
|
}
|
|
327
|
-
}
|
|
396
|
+
}
|
|
328
397
|
```
|
|
329
398
|
|
|
330
|
-
`
|
|
399
|
+
Use `code` for stable machine branching and `message` for display. Runtime tracking failures can also have one of these recovery categories:
|
|
331
400
|
|
|
332
|
-
|
|
401
|
+
| Category | Meaning |
|
|
402
|
+
|---|---|
|
|
403
|
+
| `terminal` | The native session is already gone |
|
|
404
|
+
| `recordingDead` | Recording stopped but the native session remains open |
|
|
405
|
+
| `recoveryRequired` | The live iOS session needs a foreground resume |
|
|
406
|
+
| `transient` | The native session survived the failure |
|
|
407
|
+
| `unknown` | The failure is not classified; do not assume it is recoverable |
|
|
333
408
|
|
|
334
|
-
|
|
409
|
+
See the integration guide for the required action for each category.
|
|
335
410
|
|
|
336
|
-
|
|
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.
|
|
411
|
+
## Production integration
|
|
340
412
|
|
|
341
|
-
|
|
413
|
+
The README covers installation and the first successful tracking flow. Before shipping, read the [Integration Guide](./docs/INTEGRATION.md) for:
|
|
342
414
|
|
|
343
|
-
|
|
415
|
+
- cold-start restoration and listener ownership
|
|
416
|
+
- app-owned versus SDK-owned state
|
|
417
|
+
- Android foreground-service and battery behavior
|
|
418
|
+
- iOS interruption recovery
|
|
419
|
+
- recovery-category handling
|
|
420
|
+
- analysis and report timing
|
|
421
|
+
- real-device release checks
|
|
344
422
|
|
|
345
|
-
|
|
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.
|
|
423
|
+
## Migrating from 1.x
|
|
356
424
|
|
|
357
|
-
|
|
425
|
+
v2 removes the parallel and mutable v1 surfaces:
|
|
358
426
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
427
|
+
| 1.x | v2 |
|
|
428
|
+
|---|---|
|
|
429
|
+
| `error: string \| null` and `errorInfo` | One `AsleepError`; use `message`, `code`, `category`, and `sdkCode` |
|
|
430
|
+
| Report failures returned `null` or `[]` | Report APIs throw `AsleepError`; an empty report list remains a valid result |
|
|
431
|
+
| Public state setters and raw store | Native events and SDK actions are the only writers |
|
|
432
|
+
| `getTrackingDurationMinutes()` | Store a wall-clock start time in the app |
|
|
433
|
+
| `requestMicrophonePermission()` | `requestRequiredPermissions()` |
|
|
434
|
+
| `startTracking()` requested permission | Check and request permission explicitly before starting |
|
|
435
|
+
| Default export, `AsleepSDK`, and `Asleep` class | `useAsleep()` and the named thin `Asleep` escape hatch |
|
|
436
|
+
| Required `zustand` dependency | No external state-library dependency |
|
|
363
437
|
|
|
364
|
-
|
|
438
|
+
Android 13 and later still request notification permission, but `requestRequiredPermissions()` now returns the microphone-side result that determines whether tracking can start. Pin the new version, update all imports and error branches, and test cold-start permissions before release.
|
|
365
439
|
|
|
366
440
|
## Example app
|
|
367
441
|
|
|
368
|
-
See [
|
|
442
|
+
See the [example app on GitHub](https://github.com/asleep-ai/asleep-sdk-react-native/tree/main/example) for a runnable implementation.
|
|
369
443
|
|
|
370
444
|
## License
|
|
371
445
|
|
|
372
|
-
|
|
446
|
+
See [LICENSE.md](./LICENSE.md).
|
|
373
447
|
|
|
374
448
|
## Support
|
|
375
449
|
|