react-native-asleep 2.0.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 +71 -41
- package/README.md +72 -36
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +174 -10
- package/build/Asleep.types.d.ts +60 -0
- 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 +192 -15
- 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 +72 -40
- package/docs/INTEGRATION.md +73 -41
- package/ios/Asleep.podspec +1 -1
- package/ios/AsleepModule.swift +282 -12
- package/package.json +1 -1
- package/src/Asleep.types.ts +67 -0
- package/src/AsleepStore.ts +237 -18
- package/src/index.ts +7 -0
package/README.ko.md
CHANGED
|
@@ -30,6 +30,7 @@ Asleep의 AI 기술로 기기 마이크의 오디오를 분석하는 React Nativ
|
|
|
30
30
|
|
|
31
31
|
| react-native-asleep | iOS SDK | Android SDK |
|
|
32
32
|
|---|---|---|
|
|
33
|
+
| 2.1.0 | 3.3.3 | 3.3.1 |
|
|
33
34
|
| 2.0.0 | 3.3.2 | 3.3.1 |
|
|
34
35
|
| 1.0.17 – 1.2.0 | 3.2.0 | 3.2.1 |
|
|
35
36
|
| 1.0.15 | 3.2.0 | 3.2.0 |
|
|
@@ -149,7 +150,6 @@ export function SleepTracker() {
|
|
|
149
150
|
error,
|
|
150
151
|
checkAndRestoreTracking,
|
|
151
152
|
initAsleepConfig,
|
|
152
|
-
addEventListener,
|
|
153
153
|
checkBatteryOptimization,
|
|
154
154
|
requestBatteryOptimizationExemption,
|
|
155
155
|
hasRequiredPermissions,
|
|
@@ -168,43 +168,7 @@ export function SleepTracker() {
|
|
|
168
168
|
await checkAndRestoreTracking();
|
|
169
169
|
|
|
170
170
|
const config = { apiKey: "YOUR_API_KEY" };
|
|
171
|
-
|
|
172
|
-
let removeJoined = () => {};
|
|
173
|
-
let removeFailed = () => {};
|
|
174
|
-
const configurationFinished = new Promise<void>(
|
|
175
|
-
(resolve, reject) => {
|
|
176
|
-
removeJoined = addEventListener("onUserJoined", () => resolve());
|
|
177
|
-
removeFailed = addEventListener(
|
|
178
|
-
"onUserJoinFailed",
|
|
179
|
-
(failure) => {
|
|
180
|
-
reject(
|
|
181
|
-
new AsleepError(
|
|
182
|
-
"USER_JOIN_FAILED",
|
|
183
|
-
failure.detail ?? failure.error ?? "사용자 설정 실패",
|
|
184
|
-
{
|
|
185
|
-
sdkCode: failure.sdkCode,
|
|
186
|
-
caseName: failure.caseName,
|
|
187
|
-
cause: failure,
|
|
188
|
-
},
|
|
189
|
-
),
|
|
190
|
-
);
|
|
191
|
-
},
|
|
192
|
-
);
|
|
193
|
-
},
|
|
194
|
-
);
|
|
195
|
-
|
|
196
|
-
try {
|
|
197
|
-
await Promise.all([
|
|
198
|
-
initAsleepConfig(config),
|
|
199
|
-
configurationFinished,
|
|
200
|
-
]);
|
|
201
|
-
} finally {
|
|
202
|
-
removeJoined();
|
|
203
|
-
removeFailed();
|
|
204
|
-
}
|
|
205
|
-
} else {
|
|
206
|
-
await initAsleepConfig(config);
|
|
207
|
-
}
|
|
171
|
+
await initAsleepConfig(config);
|
|
208
172
|
|
|
209
173
|
await checkBatteryOptimization();
|
|
210
174
|
setIsReady(true);
|
|
@@ -215,7 +179,6 @@ export function SleepTracker() {
|
|
|
215
179
|
}, [
|
|
216
180
|
checkAndRestoreTracking,
|
|
217
181
|
initAsleepConfig,
|
|
218
|
-
addEventListener,
|
|
219
182
|
checkBatteryOptimization,
|
|
220
183
|
]);
|
|
221
184
|
|
|
@@ -271,7 +234,7 @@ export function SleepTracker() {
|
|
|
271
234
|
}
|
|
272
235
|
```
|
|
273
236
|
|
|
274
|
-
|
|
237
|
+
두 플랫폼 모두 `await initAsleepConfig()`는 native user join이 끝난 뒤 resolve되고, 실패하면 reject됩니다. Android의 복원된 service 빠른 경로는 `onUserJoined` 없이 resolve되므로 event가 아니라 Promise를 기다리세요. 진행 중인 호출이 있을 때 다시 호출하면 `OPERATION_IN_PROGRESS`로 reject되므로, 사용자를 전환할 때처럼 연속으로 초기화하려면 앞선 호출이 끝난 뒤에 다음 호출을 시작하세요. native SDK는 트래킹이 시작·종료 중이거나 앞선 init이 응답을 기다리는 중이면 init을 콜백 없이 무시합니다. 이때 iOS는 60초 뒤 `INITIALIZATION_FAILED`로 reject됩니다. SDK가 그 호출에 늦게 응답하면, 그 뒤에 새 `initAsleepConfig()`가 시작되지 않았을 때만 반영되고 `onUserJoined`/`onUserJoinFailed`가 전달됩니다. 새 호출이 시작된 뒤라면 무시되며 다음 init이 성공할 때까지 사용자별 기능은 막힌 상태로 남습니다. SDK가 앞선 호출을 처리하는 동안 새로 한 호출도 같은 방식으로 timeout될 수 있습니다. Android는 대기 상태로 남습니다. 시작·종료 중에는 `initAsleepConfig()`를 호출하지 마세요.
|
|
275
238
|
|
|
276
239
|
`recordingDead`도 예외입니다. `isTracking`은 `false`지만 native session은 열려 있으므로 새 측정을 시작하기 전에 `stopTracking()`을 호출해야 합니다.
|
|
277
240
|
|
|
@@ -304,6 +267,31 @@ await asleep.initAsleepConfig({ appId: "YOUR_APP_ID", appSecret: "YOUR_APP_SECRE
|
|
|
304
267
|
|
|
305
268
|
`apiKey`와 `appId`/`appSecret`을 함께 넣으면 타입 오류입니다. 런타임에서 둘 다 없거나, 둘 다 있거나, 한쪽만 있는 쌍이거나, 빈 문자열이면 native 호출 전에 `INVALID_ARGUMENT` 코드의 `AsleepError`로 reject합니다. secret도 API key처럼 소스에 커밋하지 마세요.
|
|
306
269
|
|
|
270
|
+
### 기기 등록
|
|
271
|
+
|
|
272
|
+
`setup()`은 앱이 실행되는 하드웨어 제품을 Asleep에 등록할 수 있습니다(`POST customer/v1/products`). 두 인증 방식 모두에서 `productInfo`를 전달합니다.
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import type { AsleepProductInfo } from "react-native-asleep";
|
|
276
|
+
|
|
277
|
+
const productInfo: AsleepProductInfo = {
|
|
278
|
+
model: "YOUR_PRODUCT_MODEL",
|
|
279
|
+
identifierType: "serial", // 또는 "mac_address"
|
|
280
|
+
identifierValue: deviceSerialNumber,
|
|
281
|
+
};
|
|
282
|
+
await asleep.setup({ apiKey: "YOUR_API_KEY", productInfo });
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
iOS SDK 3.3.3, Android SDK 3.3.1 기준 동작입니다.
|
|
286
|
+
|
|
287
|
+
- `productInfo`는 `setup()`만 받으며 `initAsleepConfig()`는 받지 않습니다. 등록이 성공한 뒤 생성된 session이 제품에 연결되므로 `startTracking()` 전에 등록하세요. `productInfo`를 생략하면 등록을 건너뛰고 기존 `setup()` 동작을 유지합니다.
|
|
288
|
+
- `model`은 1-100자, `identifierValue`는 1-255자이며 둘 다 공백만으로 이루어질 수 없습니다. 값은 trim하지 않고 그대로 전송됩니다. `identifierType`은 `"serial"` 또는 `"mac_address"`입니다. 잘못된 값이나 알 수 없는 필드는 native 호출 전에 `INVALID_ARGUMENT`로 reject됩니다.
|
|
289
|
+
- 등록은 식별자 단위로 멱등입니다. 같은 `identifierType`과 `identifierValue`는 기존 제품 credential을 돌려주며, 같은 인증 주체와 같은 `productInfo`로 이미 credential을 가진 기기는 네트워크 호출을 하지 않습니다. 서버는 식별자에 처음 등록된 `model`을 유지하며, SDK로는 변경할 수 없습니다.
|
|
290
|
+
- 다른 식별자는 서버에 새 제품을 만들고, 이는 과금 대상이 될 수 있습니다. 기기의 실제 시리얼 번호나 MAC 주소를 사용하고, 운영 credential로 placeholder나 테스트 값을 보내지 마세요.
|
|
291
|
+
- `apiKey`나 `appId`를 바꾸면 저장된 credential이 삭제되고, 다음 `productInfo` 포함 `setup()`에서 다시 등록합니다.
|
|
292
|
+
- 등록은 `setup()`을 막는 단계입니다. 실패하면 setup 전체가 `SETUP_FAILED` 코드로 실패하며 `error.sdkCode`는 13400(거부: 429를 제외한 4xx 또는 입력 사전 검사 실패. 입력이나 계약을 수정하세요) 또는 13000(네트워크, 5xx, 429, 응답 해석 실패. 나중에 다시 시도하세요)입니다. SDK는 네트워크 실패, 5xx, 429를 2, 4, 8초 뒤에 재시도한 다음 13000을 보고합니다. 오프라인에서는 실패가 도착하기까지 약 1.5-3분이 걸릴 수 있습니다. 실패 후 native SDK는 설정되지 않은 상태로 돌아가며 `setup()`을 다시 호출할 수 있습니다.
|
|
293
|
+
- Android에서 `setup()`은 등록과 setup이 끝난 뒤 resolve됩니다. iOS에서 `setup()`은 native 호출이 시작되면 반환되고, 등록이 끝나기 전에 `isSetupComplete`가 `true`일 수 있습니다. tracking을 시작하기 전에 `addEventListener()`로 `onSetupDidComplete` 또는 `onSetupDidFail`을 기다리고, 둘 중 하나가 도착하기 전에는 `setup()`을 다시 호출하지 마세요. native SDK는 실행 중인 setup이 있으면 두 번째 `setup()`을 callback 없이 무시합니다.
|
|
294
|
+
|
|
307
295
|
### `useAsleep()`
|
|
308
296
|
|
|
309
297
|
React 컴포넌트에서 상태와 action을 사용하고 네이티브 listener 수명 주기를 관리하는 기본 API입니다.
|
|
@@ -320,7 +308,49 @@ React 컴포넌트에서 상태와 action을 사용하고 네이티브 listener
|
|
|
320
308
|
- 초기화: `checkAndRestoreTracking`, `initAsleepConfig`, `setup`
|
|
321
309
|
- 측정: `startTracking`, `stopTracking`, `resumeTracking`
|
|
322
310
|
- 권한과 배터리: `hasRequiredPermissions`, `requestRequiredPermissions`, `checkBatteryOptimization`, `requestBatteryOptimizationExemption`
|
|
323
|
-
- 데이터: `requestAnalysis`, `getReport`, `getReportList`, `getAverageReport`, `deleteSession`
|
|
311
|
+
- 데이터: `requestAnalysis`, `getReport`, `getReportList`, `getAverageReport`, `deleteSession`, `reanalyze`
|
|
312
|
+
- 사용자 메타데이터: `saveUserMetadata`, `fetchUserMetadata`
|
|
313
|
+
|
|
314
|
+
### 종료 시 분석 구간
|
|
315
|
+
|
|
316
|
+
`stopTracking()`에 녹음 전체 대신 서버가 분석할 구간을 선택적으로 전달할 수 있습니다.
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
await asleep.stopTracking({
|
|
320
|
+
analysisRange: { start: bedtime, end: new Date() },
|
|
321
|
+
});
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
`start`는 `end`보다 최소 1초(초 단위 기준) 앞서야 하고 둘 다 유효한 `Date`여야 합니다. 그렇지 않으면 native 호출 전에 `INVALID_ARGUMENT`로 reject됩니다. 옵션 없이 호출한 `stopTracking()`의 동작은 기존과 같습니다. 서버가 받아들이지 않는 구간은 별도 통지 없이 무시되고 session 전체가 분석될 수 있습니다. session은 정상 종료되며 앱은 구간이 버려졌다는 신호를 받지 못하므로, 구간이 중요하다면 `getReport()`로 결과를 확인하세요. 구간은 측정된 session 안에 있어야 합니다. native session 시작보다 앞선 `start`는 분석된 데이터가 없는 session(`missing_data_ratio` 1.0, `TOO_MANY_DEFECTS_IN_SLEEP_STAGES`)을 만든다는 것을 실기기에서 확인했으므로, 추적 시작 이후임이 확실한 시각을 `start`로 쓰세요.
|
|
325
|
+
|
|
326
|
+
### 재분석
|
|
327
|
+
|
|
328
|
+
`reanalyze(sessionId, options?)`는 종료된 session을 서버가 다시 분석하도록 요청하며, `options.analysisRange`로 구간을 제한할 수 있습니다.
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
await asleep.reanalyze(sessionId, { analysisRange: { start, end } });
|
|
332
|
+
// 분석 완료가 아니라 서버가 요청을 수락했을 때 resolve됩니다.
|
|
333
|
+
// report.session.state가 "COMPLETE"가 될 때까지 getReport(sessionId)를 polling하세요.
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
> **구간 없이 재분석하면 서버에 저장된 이전 구간이 대체됩니다.** `stopTracking({ analysisRange })`로 지정한 구간도 마찬가지입니다. 구간을 유지하려면 다시 전달하세요.
|
|
337
|
+
|
|
338
|
+
빈 `sessionId`나 잘못된 구간은 native 호출 전에 `INVALID_ARGUMENT`로, 가장 최근 `initAsleepConfig()`가 resolve되기 전, 재초기화 진행 중, 재초기화 실패 후의 호출은 `MISSING_PREREQUISITE`로 reject됩니다. 서버 실패는 code `REANALYZE_FAILED`로 reject되며 `error.sdkCode`에 SDK 코드를 유지합니다: 30000(일반/네트워크), 30400, 30401, 30403, 30404, 30409(재분석이 이미 진행 중: 간격을 두고, 무한 재시도하지 마세요), 30410(데이터 보존 기간 만료), 30422(session이 아직 측정 중), 30500.
|
|
339
|
+
|
|
340
|
+
### 사용자 메타데이터
|
|
341
|
+
|
|
342
|
+
`initAsleepConfig()`가 완료된 뒤 서버 분석에 사용되는 선택적 프로필 정보를 저장할 수 있습니다.
|
|
343
|
+
|
|
344
|
+
```ts
|
|
345
|
+
import type { AsleepUserMetadata } from "react-native-asleep";
|
|
346
|
+
|
|
347
|
+
const metadata: AsleepUserMetadata = { birthYear: 1990, gender: "female", height: 165.5 };
|
|
348
|
+
await asleep.saveUserMetadata(metadata);
|
|
349
|
+
|
|
350
|
+
const saved = await asleep.fetchUserMetadata(); // AsleepUserMetadata | null
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
모든 필드는 선택 사항이며 생략한 필드는 전송되지 않습니다. 범위를 벗어난 값은 native 호출 전에 `INVALID_ARGUMENT`로 reject됩니다: `birthYear` 1900-2100, `birthMonth` 1-12, `birthDay` 1-31(정수), `height` 1-500 cm, `weight` 1-1000 kg, `gender`는 `"male"`, `"female"`, `"non_binary"`, `"other"`, `"prefer_not_to_say"` 중 하나. 가장 최근 `initAsleepConfig()`가 resolve된 뒤에 호출하세요. 그 전이나, 재초기화가 진행 중이거나 실패한 상태에서 호출하면 `MISSING_PREREQUISITE`로 reject되므로, 재초기화가 실패해도 이전 사용자의 프로필을 읽거나 덮어쓰지 않습니다. `setup()`도 사용자 설정을 무효화하므로 `setup()` 뒤에는 `initAsleepConfig()`를 다시 호출하세요. native 실패는 `error.sdkCode`에 SDK 코드를 유지합니다: 27400(서버 검증 실패, code `INVALID_ARGUMENT`), 27000(`SAVE_USER_METADATA_FAILED`), 27100(`FETCH_USER_METADATA_FAILED`). 저장된 값이 없으면 `fetchUserMetadata()`는 `null`로 resolve됩니다.
|
|
324
354
|
|
|
325
355
|
### `Asleep`
|
|
326
356
|
|
package/README.md
CHANGED
|
@@ -29,6 +29,7 @@ Bundled native SDK versions. The React Native package follows its own semver; it
|
|
|
29
29
|
|
|
30
30
|
| react-native-asleep | iOS SDK | Android SDK |
|
|
31
31
|
|---|---|---|
|
|
32
|
+
| 2.1.0 | 3.3.3 | 3.3.1 |
|
|
32
33
|
| 2.0.0 | 3.3.2 | 3.3.1 |
|
|
33
34
|
| 1.0.17 – 1.2.0 | 3.2.0 | 3.2.1 |
|
|
34
35
|
| 1.0.15 | 3.2.0 | 3.2.0 |
|
|
@@ -146,7 +147,7 @@ Always call `initAsleepConfig()` after `checkAndRestoreTracking()`, including wh
|
|
|
146
147
|
|
|
147
148
|
```tsx
|
|
148
149
|
import { useEffect, useRef, useState } from "react";
|
|
149
|
-
import { Button,
|
|
150
|
+
import { Button, Text, View } from "react-native";
|
|
150
151
|
import { AsleepError, useAsleep } from "react-native-asleep";
|
|
151
152
|
|
|
152
153
|
export function SleepTracker() {
|
|
@@ -163,38 +164,7 @@ export function SleepTracker() {
|
|
|
163
164
|
await asleep.checkAndRestoreTracking();
|
|
164
165
|
|
|
165
166
|
const config = { apiKey: "YOUR_API_KEY" };
|
|
166
|
-
|
|
167
|
-
let removeJoined = () => {};
|
|
168
|
-
let removeFailed = () => {};
|
|
169
|
-
const configurationFinished = new Promise<void>((resolve, reject) => {
|
|
170
|
-
removeJoined = asleep.addEventListener("onUserJoined", () => resolve());
|
|
171
|
-
removeFailed = asleep.addEventListener("onUserJoinFailed", (failure) => {
|
|
172
|
-
reject(
|
|
173
|
-
new AsleepError(
|
|
174
|
-
"USER_JOIN_FAILED",
|
|
175
|
-
failure.detail ?? failure.error ?? "User join failed.",
|
|
176
|
-
{
|
|
177
|
-
sdkCode: failure.sdkCode,
|
|
178
|
-
caseName: failure.caseName,
|
|
179
|
-
cause: failure,
|
|
180
|
-
},
|
|
181
|
-
),
|
|
182
|
-
);
|
|
183
|
-
});
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
try {
|
|
187
|
-
await Promise.all([
|
|
188
|
-
asleep.initAsleepConfig(config),
|
|
189
|
-
configurationFinished,
|
|
190
|
-
]);
|
|
191
|
-
} finally {
|
|
192
|
-
removeJoined();
|
|
193
|
-
removeFailed();
|
|
194
|
-
}
|
|
195
|
-
} else {
|
|
196
|
-
await asleep.initAsleepConfig(config);
|
|
197
|
-
}
|
|
167
|
+
await asleep.initAsleepConfig(config);
|
|
198
168
|
|
|
199
169
|
await asleep.checkBatteryOptimization();
|
|
200
170
|
setIsReady(true);
|
|
@@ -206,7 +176,6 @@ export function SleepTracker() {
|
|
|
206
176
|
}, [
|
|
207
177
|
asleep.checkAndRestoreTracking,
|
|
208
178
|
asleep.initAsleepConfig,
|
|
209
|
-
asleep.addEventListener,
|
|
210
179
|
asleep.checkBatteryOptimization,
|
|
211
180
|
]);
|
|
212
181
|
|
|
@@ -265,7 +234,7 @@ export function SleepTracker() {
|
|
|
265
234
|
|
|
266
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.
|
|
267
236
|
|
|
268
|
-
|
|
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.
|
|
269
238
|
|
|
270
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.
|
|
271
240
|
|
|
@@ -298,6 +267,31 @@ await asleep.initAsleepConfig({ appId: "YOUR_APP_ID", appSecret: "YOUR_APP_SECRE
|
|
|
298
267
|
|
|
299
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.
|
|
300
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
|
+
|
|
301
295
|
### `useAsleep()`
|
|
302
296
|
|
|
303
297
|
The primary React API. It attaches the ref-counted native listeners while mounted and returns state plus actions from the shared SDK store.
|
|
@@ -322,10 +316,52 @@ Important actions:
|
|
|
322
316
|
| Configuration and restore | `setup`, `initAsleepConfig`, `checkAndRestoreTracking` |
|
|
323
317
|
| Prerequisites | `checkBatteryOptimization`, `requestBatteryOptimizationExemption`, `hasRequiredPermissions`, `requestRequiredPermissions` |
|
|
324
318
|
| Tracking | `startTracking`, `stopTracking`, `resumeTracking` |
|
|
325
|
-
| Reports | `getReport`, `getReportList`, `getAverageReport`, `deleteSession` |
|
|
319
|
+
| Reports | `getReport`, `getReportList`, `getAverageReport`, `deleteSession`, `reanalyze` |
|
|
326
320
|
| Analysis | `requestAnalysis` |
|
|
321
|
+
| User metadata | `saveUserMetadata`, `fetchUserMetadata` |
|
|
327
322
|
| Utilities | `addEventListener`, `enableLog`, `clearError` |
|
|
328
323
|
|
|
324
|
+
### Analysis range at stop
|
|
325
|
+
|
|
326
|
+
`stopTracking()` accepts an optional window that the server analyzes instead of the whole recording:
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
await asleep.stopTracking({
|
|
330
|
+
analysisRange: { start: bedtime, end: new Date() },
|
|
331
|
+
});
|
|
332
|
+
```
|
|
333
|
+
|
|
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.
|
|
335
|
+
|
|
336
|
+
### Reanalysis
|
|
337
|
+
|
|
338
|
+
`reanalyze(sessionId, options?)` asks the server to analyze a closed session again, optionally restricted to `options.analysisRange`:
|
|
339
|
+
|
|
340
|
+
```ts
|
|
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
|
+
```
|
|
345
|
+
|
|
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.
|
|
347
|
+
|
|
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.
|
|
349
|
+
|
|
350
|
+
### User metadata
|
|
351
|
+
|
|
352
|
+
After `initAsleepConfig()` completes, the app can save optional profile data that the server uses for analysis:
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
import type { AsleepUserMetadata } from "react-native-asleep";
|
|
356
|
+
|
|
357
|
+
const metadata: AsleepUserMetadata = { birthYear: 1990, gender: "female", height: 165.5 };
|
|
358
|
+
await asleep.saveUserMetadata(metadata);
|
|
359
|
+
|
|
360
|
+
const saved = await asleep.fetchUserMetadata(); // AsleepUserMetadata | null
|
|
361
|
+
```
|
|
362
|
+
|
|
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.
|
|
364
|
+
|
|
329
365
|
### `Asleep`
|
|
330
366
|
|
|
331
367
|
Use the imperative escape hatch where React hooks are unavailable:
|
|
@@ -2,6 +2,10 @@ package ai.asleep.reactnative
|
|
|
2
2
|
|
|
3
3
|
import ai.asleep.asleepsdk.Asleep
|
|
4
4
|
import ai.asleep.asleepsdk.data.AsleepConfig
|
|
5
|
+
import ai.asleep.asleepsdk.data.Gender
|
|
6
|
+
import ai.asleep.asleepsdk.data.ProductInfo
|
|
7
|
+
import ai.asleep.asleepsdk.data.UserInfo
|
|
8
|
+
import ai.asleep.asleepsdk.data.UserMetadata
|
|
5
9
|
import ai.asleep.asleepsdk.data.Report
|
|
6
10
|
import ai.asleep.asleepsdk.data.SleepSession
|
|
7
11
|
import ai.asleep.asleepsdk.tracking.Reports
|
|
@@ -11,6 +15,8 @@ import com.google.gson.reflect.TypeToken
|
|
|
11
15
|
import expo.modules.kotlin.exception.CodedException
|
|
12
16
|
import expo.modules.kotlin.modules.Module
|
|
13
17
|
import expo.modules.kotlin.modules.ModuleDefinition
|
|
18
|
+
import expo.modules.kotlin.records.Field
|
|
19
|
+
import expo.modules.kotlin.records.Record
|
|
14
20
|
import expo.modules.kotlin.Promise
|
|
15
21
|
import android.Manifest
|
|
16
22
|
import android.app.Activity
|
|
@@ -42,6 +48,7 @@ import android.util.Log
|
|
|
42
48
|
import android.os.PowerManager
|
|
43
49
|
import android.provider.Settings
|
|
44
50
|
import android.net.Uri
|
|
51
|
+
import java.util.Date
|
|
45
52
|
|
|
46
53
|
class AsleepModule : Module() {
|
|
47
54
|
private val gson = Gson()
|
|
@@ -148,8 +155,28 @@ class AsleepModule : Module() {
|
|
|
148
155
|
"onUserJoined", "onUserJoinFailed", "onUserDeleted", "onDebugLog",
|
|
149
156
|
"onSetupDidComplete", "onSetupDidFail", "onSetupInProgress", "onAnalysisResult")
|
|
150
157
|
|
|
151
|
-
// JS validates
|
|
152
|
-
|
|
158
|
+
// JS validates the credential form and productInfo. Credentials travel as one record
|
|
159
|
+
// because AsyncFunction accepts at most eight parameters including the promise.
|
|
160
|
+
// A null productInfo skips product registration.
|
|
161
|
+
AsyncFunction("setup") { credentials: SetupCredentialsRecord, baseUrl: String?, callbackUrl: String?, service: String?, enableODA: Boolean?, productInfo: ProductInfoRecord?, promise: Promise ->
|
|
162
|
+
// setup() may switch credentials; drop the previous user config until the
|
|
163
|
+
// next initAsleepConfig() succeeds so per-user calls never run as the previous user.
|
|
164
|
+
_asleepConfig = null
|
|
165
|
+
_reportManager = null
|
|
166
|
+
val apiKey = credentials.apiKey
|
|
167
|
+
val appId = credentials.appId
|
|
168
|
+
val appSecret = credentials.appSecret
|
|
169
|
+
val product = productInfo?.let { record ->
|
|
170
|
+
val identifierType = when (record.identifierType) {
|
|
171
|
+
"serial" -> Asleep.ProductIdentifierType.SERIAL
|
|
172
|
+
"mac_address" -> Asleep.ProductIdentifierType.MAC_ADDRESS
|
|
173
|
+
else -> {
|
|
174
|
+
promise.reject("INVALID_ARGUMENT", "Unknown productInfo.identifierType: ${record.identifierType}", null)
|
|
175
|
+
return@AsyncFunction
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
ProductInfo(record.model, identifierType, record.identifierValue)
|
|
179
|
+
}
|
|
153
180
|
try {
|
|
154
181
|
val context = appContext.reactContext!!.applicationContext as Application
|
|
155
182
|
val setupListener = object : Asleep.AsleepSetupListener {
|
|
@@ -166,7 +193,7 @@ class AsleepModule : Module() {
|
|
|
166
193
|
override fun onFail(errorCode: Int, detail: String) {
|
|
167
194
|
sendEvent("onSetupDidFail", mapOf("error" to detail, "sdkCode" to errorCode))
|
|
168
195
|
sendEvent("onDebugLog", mapOf("message" to "Setup failed: $errorCode - $detail"))
|
|
169
|
-
promise
|
|
196
|
+
rejectWithSdkCode(promise, "SETUP_FAILED", errorCode, "Setup failed: $errorCode - $detail")
|
|
170
197
|
}
|
|
171
198
|
}
|
|
172
199
|
|
|
@@ -179,7 +206,8 @@ class AsleepModule : Module() {
|
|
|
179
206
|
callbackUrl = callbackUrl,
|
|
180
207
|
service = service ?: "SleepTracking",
|
|
181
208
|
enableODA = enableODA,
|
|
182
|
-
asleepSetupListener = setupListener
|
|
209
|
+
asleepSetupListener = setupListener,
|
|
210
|
+
productInfo = product
|
|
183
211
|
)
|
|
184
212
|
} else {
|
|
185
213
|
Asleep.setup(
|
|
@@ -189,7 +217,8 @@ class AsleepModule : Module() {
|
|
|
189
217
|
callbackUrl = callbackUrl,
|
|
190
218
|
service = service ?: "SleepTracking",
|
|
191
219
|
enableODA = enableODA,
|
|
192
|
-
asleepSetupListener = setupListener
|
|
220
|
+
asleepSetupListener = setupListener,
|
|
221
|
+
productInfo = product
|
|
193
222
|
)
|
|
194
223
|
}
|
|
195
224
|
} catch (e: Exception) {
|
|
@@ -204,17 +233,24 @@ class AsleepModule : Module() {
|
|
|
204
233
|
val useToken = appId != null && appSecret != null
|
|
205
234
|
val credentialId = if (useToken) "appId:$appId" else "apiKey:$apiKey"
|
|
206
235
|
|
|
207
|
-
|
|
236
|
+
// Only a live config from a previous successful init may take the shortcut;
|
|
237
|
+
// after a failed re-init the config is null and init must run again.
|
|
238
|
+
if (isTracking && _asleepConfig != null && savedCredentialId == credentialId && savedUserId == userId) {
|
|
208
239
|
promise.resolve(mapOf("userId" to (savedUserId ?: "")))
|
|
209
240
|
sendEvent("onDebugLog", mapOf("message" to "Service reconnected"))
|
|
210
241
|
return@AsyncFunction
|
|
211
242
|
}
|
|
212
243
|
|
|
213
|
-
//
|
|
214
|
-
|
|
244
|
+
// Drop the previous user's config until onSuccess delivers the new one,
|
|
245
|
+
// so metadata and report calls never run as the previous user. On
|
|
246
|
+
// onFail both stay null.
|
|
247
|
+
_asleepConfig = null
|
|
248
|
+
_reportManager = null
|
|
215
249
|
|
|
216
250
|
val configListener = object : Asleep.AsleepConfigListener {
|
|
217
251
|
override fun onSuccess(userId: String?, asleepConfig: AsleepConfig?) {
|
|
252
|
+
// Record the credential identity only once this init succeeded.
|
|
253
|
+
savedCredentialId = credentialId
|
|
218
254
|
if (userId != null) {
|
|
219
255
|
sendEvent("onDebugLog", mapOf("message" to "UserId is not null"))
|
|
220
256
|
// Store userId in memory instead of preferences
|
|
@@ -375,8 +411,13 @@ class AsleepModule : Module() {
|
|
|
375
411
|
return@Function isTracking
|
|
376
412
|
}
|
|
377
413
|
|
|
378
|
-
|
|
379
|
-
|
|
414
|
+
// Range bounds are epoch milliseconds; JS validates start < end before calling.
|
|
415
|
+
AsyncFunction("stopTracking") { analysisStartMs: Double?, analysisEndMs: Double?, promise: Promise ->
|
|
416
|
+
if (analysisStartMs != null && analysisEndMs != null) {
|
|
417
|
+
Asleep.endSleepTracking(Date(analysisStartMs.toLong()), Date(analysisEndMs.toLong()))
|
|
418
|
+
} else {
|
|
419
|
+
Asleep.endSleepTracking()
|
|
420
|
+
}
|
|
380
421
|
isTracking = false
|
|
381
422
|
promise.resolve(null)
|
|
382
423
|
}
|
|
@@ -490,6 +531,102 @@ class AsleepModule : Module() {
|
|
|
490
531
|
}
|
|
491
532
|
}
|
|
492
533
|
|
|
534
|
+
// Resolves when the server accepts the request. Range bounds are epoch
|
|
535
|
+
// milliseconds and are always passed explicitly (null when absent).
|
|
536
|
+
AsyncFunction("reanalyze") { sessionId: String, analysisStartMs: Double?, analysisEndMs: Double?, promise: Promise ->
|
|
537
|
+
val reportManager = _reportManager
|
|
538
|
+
if (reportManager == null) {
|
|
539
|
+
promise.reject("MISSING_PREREQUISITE", "Report manager is not initialized", null)
|
|
540
|
+
return@AsyncFunction
|
|
541
|
+
}
|
|
542
|
+
val listener = object : Reports.ReanalyzeListener {
|
|
543
|
+
override fun onSuccess(sessionId: String) {
|
|
544
|
+
sendEvent("onDebugLog", mapOf("message" to "reanalyze accepted: $sessionId"))
|
|
545
|
+
promise.resolve(null)
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
override fun onFail(errorCode: Int, detail: String) {
|
|
549
|
+
sendEvent("onDebugLog", mapOf("message" to "reanalyze failed: $errorCode - $detail"))
|
|
550
|
+
// 11009 ERR_INVALID_PARAMETER: start >= end (JS validates this first).
|
|
551
|
+
val code = if (errorCode == 11009) "INVALID_ARGUMENT" else "REANALYZE_FAILED"
|
|
552
|
+
rejectWithSdkCode(promise, code, errorCode, detail)
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
try {
|
|
556
|
+
if (analysisStartMs != null && analysisEndMs != null) {
|
|
557
|
+
reportManager.reanalyze(sessionId, Date(analysisStartMs.toLong()), Date(analysisEndMs.toLong()), listener)
|
|
558
|
+
} else {
|
|
559
|
+
reportManager.reanalyze(sessionId, listener)
|
|
560
|
+
}
|
|
561
|
+
} catch (e: Exception) {
|
|
562
|
+
rejectWithSdkCode(promise, "REANALYZE_FAILED", 30000, e.message ?: "Failed to request reanalysis")
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
AsyncFunction("saveUserMetadata") { metadata: UserMetadataRecord, promise: Promise ->
|
|
567
|
+
val config = _asleepConfig
|
|
568
|
+
if (config == null) {
|
|
569
|
+
promise.reject("MISSING_PREREQUISITE", "AsleepConfig is not initialized", null)
|
|
570
|
+
return@AsyncFunction
|
|
571
|
+
}
|
|
572
|
+
val model = try {
|
|
573
|
+
val gender = metadata.gender?.let { raw ->
|
|
574
|
+
Gender.values().firstOrNull { it.value == raw }
|
|
575
|
+
?: throw IllegalArgumentException("Unknown gender: $raw")
|
|
576
|
+
}
|
|
577
|
+
// The UserMetadata constructor throws IllegalArgumentException for out-of-range values.
|
|
578
|
+
UserMetadata(
|
|
579
|
+
birthYear = metadata.birthYear,
|
|
580
|
+
birthMonth = metadata.birthMonth,
|
|
581
|
+
birthDay = metadata.birthDay,
|
|
582
|
+
gender = gender,
|
|
583
|
+
height = metadata.height?.toFloat(),
|
|
584
|
+
weight = metadata.weight?.toFloat()
|
|
585
|
+
)
|
|
586
|
+
} catch (e: IllegalArgumentException) {
|
|
587
|
+
rejectWithSdkCode(promise, "INVALID_ARGUMENT", 27400, e.message ?: "Invalid user metadata")
|
|
588
|
+
return@AsyncFunction
|
|
589
|
+
}
|
|
590
|
+
try {
|
|
591
|
+
config.saveUserMetadata(model, object : Asleep.SaveUserMetadataListener {
|
|
592
|
+
override fun onSuccess(userInfo: UserInfo) {
|
|
593
|
+
sendEvent("onDebugLog", mapOf("message" to "saveUserMetadata completed"))
|
|
594
|
+
promise.resolve(null)
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
override fun onFail(errorCode: Int, detail: String) {
|
|
598
|
+
sendEvent("onDebugLog", mapOf("message" to "saveUserMetadata failed: $errorCode - $detail"))
|
|
599
|
+
val code = if (errorCode == 27400) "INVALID_ARGUMENT" else "SAVE_USER_METADATA_FAILED"
|
|
600
|
+
rejectWithSdkCode(promise, code, errorCode, detail)
|
|
601
|
+
}
|
|
602
|
+
})
|
|
603
|
+
} catch (e: Exception) {
|
|
604
|
+
rejectWithSdkCode(promise, "SAVE_USER_METADATA_FAILED", 27000, e.message ?: "Failed to save user metadata")
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
AsyncFunction("fetchUserMetadata") { promise: Promise ->
|
|
609
|
+
val config = _asleepConfig
|
|
610
|
+
if (config == null) {
|
|
611
|
+
promise.reject("MISSING_PREREQUISITE", "AsleepConfig is not initialized", null)
|
|
612
|
+
return@AsyncFunction
|
|
613
|
+
}
|
|
614
|
+
try {
|
|
615
|
+
config.fetchUserMetadata(object : Asleep.FetchUserMetadataListener {
|
|
616
|
+
override fun onSuccess(metadata: UserMetadata?) {
|
|
617
|
+
promise.resolve(metadata?.serializeToMap())
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
override fun onFail(errorCode: Int, detail: String) {
|
|
621
|
+
sendEvent("onDebugLog", mapOf("message" to "fetchUserMetadata failed: $errorCode - $detail"))
|
|
622
|
+
rejectWithSdkCode(promise, "FETCH_USER_METADATA_FAILED", errorCode, detail)
|
|
623
|
+
}
|
|
624
|
+
})
|
|
625
|
+
} catch (e: Exception) {
|
|
626
|
+
rejectWithSdkCode(promise, "FETCH_USER_METADATA_FAILED", 27100, e.message ?: "Failed to fetch user metadata")
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
493
630
|
AsyncFunction("hasRequiredPermissions") { promise: Promise ->
|
|
494
631
|
promise.resolve(hasRequiredPermissions())
|
|
495
632
|
}
|
|
@@ -674,6 +811,12 @@ class AsleepModule : Module() {
|
|
|
674
811
|
}
|
|
675
812
|
}
|
|
676
813
|
|
|
814
|
+
// Expo rejections carry only a code string and a message. JS normalizeError
|
|
815
|
+
// splits "<CODE>:<sdkCode>" back into AsleepError.code and AsleepError.sdkCode.
|
|
816
|
+
private fun rejectWithSdkCode(promise: Promise, code: String, sdkCode: Int, message: String) {
|
|
817
|
+
promise.reject("$code:$sdkCode", message, null)
|
|
818
|
+
}
|
|
819
|
+
|
|
677
820
|
private fun <T> T.serializeToMap(): Map<String, Any> {
|
|
678
821
|
return convert()
|
|
679
822
|
}
|
|
@@ -717,3 +860,24 @@ class AsleepModule : Module() {
|
|
|
717
860
|
}
|
|
718
861
|
}
|
|
719
862
|
}
|
|
863
|
+
|
|
864
|
+
class SetupCredentialsRecord : Record {
|
|
865
|
+
@Field val apiKey: String? = null
|
|
866
|
+
@Field val appId: String? = null
|
|
867
|
+
@Field val appSecret: String? = null
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
class ProductInfoRecord : Record {
|
|
871
|
+
@Field val model: String = ""
|
|
872
|
+
@Field val identifierType: String = ""
|
|
873
|
+
@Field val identifierValue: String = ""
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
class UserMetadataRecord : Record {
|
|
877
|
+
@Field val birthYear: Int? = null
|
|
878
|
+
@Field val birthMonth: Int? = null
|
|
879
|
+
@Field val birthDay: Int? = null
|
|
880
|
+
@Field val gender: String? = null
|
|
881
|
+
@Field val height: Double? = null
|
|
882
|
+
@Field val weight: Double? = null
|
|
883
|
+
}
|