react-native-asleep 1.0.6 → 1.0.8

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.
@@ -1,7 +1,7 @@
1
1
  import { create } from "zustand";
2
2
  import { subscribeWithSelector } from "zustand/middleware";
3
3
  import { EventEmitter } from "expo-modules-core";
4
- import { Alert, Platform } from "react-native";
4
+ import { Platform, PermissionsAndroid } from "react-native";
5
5
  import {
6
6
  AsleepConfig,
7
7
  AsleepSetupConfig,
@@ -9,6 +9,7 @@ import {
9
9
  AsleepReport,
10
10
  AsleepSession,
11
11
  AsleepAnalysisResult,
12
+ TrackingConfig,
12
13
  } from "./Asleep.types";
13
14
  import AsleepModule from "./AsleepModule";
14
15
 
@@ -31,15 +32,25 @@ export interface AsleepState {
31
32
  isSetupInProgress: boolean;
32
33
  isSetupComplete: boolean;
33
34
 
35
+ // Service status tracking
36
+ hasCheckedStatus: boolean;
37
+
38
+ // Battery optimization tracking
39
+ hasCheckedBatteryOptimization: boolean;
40
+
34
41
  // actions
35
42
  setup: (config: AsleepSetupConfig) => Promise<void>;
36
43
  initAsleepConfig: (config: AsleepConfig) => Promise<void>;
37
- startTracking: () => Promise<void>;
44
+ checkAndRestoreTracking: () => Promise<{ hasActiveSession: boolean }>;
45
+ checkBatteryOptimization: () => Promise<{ exempted: boolean; platform: string; message?: string }>;
46
+ requestBatteryOptimizationExemption: () => Promise<boolean>;
47
+ startTracking: (config?: TrackingConfig) => Promise<void>;
38
48
  stopTracking: () => Promise<void>;
39
49
  getReport: (sessionId: string) => Promise<AsleepReport | null>;
40
50
  getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
41
51
  deleteSession: (sessionId: string) => Promise<void>;
42
- requestMicrophonePermission: () => Promise<boolean>;
52
+ requestMicrophonePermission: () => Promise<boolean>; // deprecated
53
+ requestRequiredPermissions: () => Promise<boolean>;
43
54
  setCustomNotification: (title: string, text: string) => Promise<void>;
44
55
  enableLog: (print: boolean) => void;
45
56
  requestAnalysis: () => Promise<AsleepAnalysisResult | null>;
@@ -62,6 +73,8 @@ export interface AsleepState {
62
73
  setIsInitialized: (initialized: boolean) => void;
63
74
  setIsSetupInProgress: (inProgress: boolean) => void;
64
75
  setIsSetupComplete: (complete: boolean) => void;
76
+ setHasCheckedStatus: (checked: boolean) => void;
77
+ setHasCheckedBatteryOptimization: (checked: boolean) => void;
65
78
  addLog: (log: string) => void;
66
79
  }
67
80
 
@@ -97,6 +110,12 @@ export const useAsleepStore = create<AsleepState>()(
97
110
  isSetupInProgress: false,
98
111
  isSetupComplete: false,
99
112
 
113
+ // Service status state
114
+ hasCheckedStatus: false,
115
+
116
+ // Battery optimization state
117
+ hasCheckedBatteryOptimization: false,
118
+
100
119
  // actions
101
120
  setup: async (config: AsleepSetupConfig) => {
102
121
  try {
@@ -166,15 +185,105 @@ export const useAsleepStore = create<AsleepState>()(
166
185
  }
167
186
  },
168
187
 
169
- startTracking: async () => {
188
+ checkAndRestoreTracking: async () => {
189
+ try {
190
+ const { addLog } = get();
191
+ addLog("[checkAndRestoreTracking] Start");
192
+
193
+ // Check if sleep tracking service is alive
194
+ const isAlive = await AsleepModule.isSleepTrackingAlive();
195
+
196
+ set({
197
+ hasCheckedStatus: true
198
+ });
199
+
200
+ // If service is alive on Android, restore connection to it
201
+ if (isAlive && Platform.OS === "android") {
202
+ addLog("[checkAndRestoreTracking] Service is alive, restoring connection...");
203
+ const isConnected = await AsleepModule.connectSleepTracking();
204
+
205
+ if (isConnected) {
206
+ set({ isTracking: true });
207
+ addLog("[checkAndRestoreTracking] Successfully restored connection to existing service");
208
+ } else {
209
+ addLog("[checkAndRestoreTracking] Failed to restore connection to existing service");
210
+ }
211
+ }
212
+
213
+ addLog(`[checkAndRestoreTracking] Complete - hasActiveSession: ${isAlive}`);
214
+ return {
215
+ hasActiveSession: isAlive
216
+ };
217
+ } catch (error: any) {
218
+ console.error("checkAndRestoreTracking error:", error);
219
+ set({ error: error.message });
220
+ throw error;
221
+ }
222
+ },
223
+
224
+ checkBatteryOptimization: async () => {
225
+ const { addLog } = get();
226
+
227
+ addLog("[checkBatteryOptimization] Checking battery optimization status...");
228
+
229
+ // Mark that check was performed (required for startTracking)
230
+ set({ hasCheckedBatteryOptimization: true });
231
+
232
+ if (Platform.OS === 'ios') {
233
+ addLog("[checkBatteryOptimization] iOS - not applicable");
234
+ return { exempted: true, platform: 'ios' };
235
+ }
236
+
237
+ // Android: Check current status
238
+ const exempted = await AsleepModule.isBatteryOptimizationExempted();
239
+ addLog(`[checkBatteryOptimization] Exempted: ${exempted}`);
240
+
241
+ return {
242
+ exempted,
243
+ platform: 'android',
244
+ message: exempted ?
245
+ "Battery optimization disabled - ready for tracking" :
246
+ "Battery optimization must be disabled for reliable tracking"
247
+ };
248
+ },
249
+
250
+ requestBatteryOptimizationExemption: async () => {
251
+ const { addLog } = get();
252
+
253
+ if (Platform.OS === 'ios') {
254
+ addLog("[requestBatteryOptimizationExemption] iOS - not applicable");
255
+ return true; // Not applicable on iOS
256
+ }
257
+
258
+ addLog("[requestBatteryOptimizationExemption] Opening battery settings...");
259
+
260
+ // This just opens settings, doesn't wait
261
+ // Returns true if already exempted, false if settings opened
262
+ return await AsleepModule.requestBatteryOptimizationExemption();
263
+ },
264
+
265
+ startTracking: async (config?: TrackingConfig) => {
170
266
  try {
171
267
  const {
172
- requestMicrophonePermission,
268
+ requestRequiredPermissions,
173
269
  addLog,
174
270
  isODAEnabled,
175
271
  isSetupInProgress,
272
+ hasCheckedStatus,
176
273
  } = get();
177
274
 
275
+ // Enforce that checkAndRestoreTracking must be called first
276
+ if (!hasCheckedStatus) {
277
+ addLog("[startTracking] Must call checkAndRestoreTracking() at app startup");
278
+ throw new Error("Must call checkAndRestoreTracking() at app startup before starting tracking");
279
+ }
280
+
281
+ // Enforce battery optimization was checked (developer awareness)
282
+ if (Platform.OS === 'android' && !get().hasCheckedBatteryOptimization) {
283
+ addLog("[startTracking] ERROR: Must check battery optimization first");
284
+ throw new Error("Must call checkBatteryOptimization() before starting tracking on Android");
285
+ }
286
+
178
287
  // Block startTracking execution if setup is in progress
179
288
  if (isSetupInProgress) {
180
289
  addLog(
@@ -191,10 +300,27 @@ export const useAsleepStore = create<AsleepState>()(
191
300
 
192
301
  addLog("[startTracking] Start");
193
302
 
194
- const permission = await requestMicrophonePermission();
303
+ const permission = await requestRequiredPermissions();
195
304
  if (!permission) {
196
- Alert.alert("Microphone permission denied");
197
- throw new Error("Microphone permission denied");
305
+ // SDK shouldn't show UI directly - throw specific error message
306
+ if (Platform.OS === 'android' && Platform.Version >= 33) {
307
+ throw new Error("Microphone and notification permissions are required for sleep tracking");
308
+ } else {
309
+ throw new Error("Microphone permission is required for sleep tracking");
310
+ }
311
+ }
312
+
313
+ // Always verify CURRENT exemption status
314
+ if (Platform.OS === 'android') {
315
+ const batteryExempted = await AsleepModule.isBatteryOptimizationExempted();
316
+ if (!batteryExempted) {
317
+ addLog("[startTracking] ERROR: Battery optimization not disabled");
318
+ throw new Error(
319
+ "Battery optimization must be disabled for reliable sleep tracking. " +
320
+ "Call requestBatteryOptimizationExemption() to guide user to settings."
321
+ );
322
+ }
323
+ addLog("[startTracking] Battery optimization exempted - OK");
198
324
  }
199
325
 
200
326
  set({
@@ -203,7 +329,7 @@ export const useAsleepStore = create<AsleepState>()(
203
329
  isAnalyzing: false,
204
330
  trackingStartTime: new Date(),
205
331
  });
206
- await AsleepModule.startTracking();
332
+ await AsleepModule.startTracking(config);
207
333
 
208
334
  if (isODAEnabled) {
209
335
  addLog(
@@ -257,7 +383,7 @@ export const useAsleepStore = create<AsleepState>()(
257
383
  const convertedReport = convertKeysToCamelCase(report);
258
384
 
259
385
  addLog("[getReport] Success");
260
-
386
+
261
387
  // Ensure the report has the expected AsleepReport structure
262
388
  // Handle cases where native modules might return data in different formats
263
389
  if (convertedReport && !convertedReport.session && convertedReport.sessionId) {
@@ -281,7 +407,7 @@ export const useAsleepStore = create<AsleepState>()(
281
407
  };
282
408
  return normalizedReport;
283
409
  }
284
-
410
+
285
411
  return convertedReport as AsleepReport;
286
412
  } catch (error: any) {
287
413
  console.error("getReport error:", error);
@@ -322,8 +448,47 @@ export const useAsleepStore = create<AsleepState>()(
322
448
  }
323
449
  },
324
450
 
451
+ /**
452
+ * @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
453
+ */
325
454
  requestMicrophonePermission: async () => {
326
- return AsleepModule.requestMicrophonePermission();
455
+ console.warn(
456
+ '[AsleepSDK] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.'
457
+ );
458
+ return get().requestRequiredPermissions();
459
+ },
460
+
461
+ requestRequiredPermissions: async () => {
462
+ if (Platform.OS === 'android') {
463
+ try {
464
+ // Prepare permissions array with RECORD_AUDIO
465
+ const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO];
466
+
467
+ // Add POST_NOTIFICATIONS for Android 13+ (API level 33)
468
+ if (Platform.Version >= 33) {
469
+ permissions.push(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
470
+ }
471
+
472
+ // Request all permissions together for better UX (single dialog)
473
+ const results = await PermissionsAndroid.requestMultiple(permissions);
474
+
475
+ // Check if all required permissions are granted
476
+ const audioGranted = results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] ===
477
+ PermissionsAndroid.RESULTS.GRANTED;
478
+
479
+ const notificationGranted = Platform.Version >= 33 ?
480
+ results[PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS] ===
481
+ PermissionsAndroid.RESULTS.GRANTED : true;
482
+
483
+ // Both must be granted for tracking to work properly
484
+ return audioGranted && notificationGranted;
485
+ } catch (err) {
486
+ console.warn('Permission request error:', err);
487
+ return false;
488
+ }
489
+ }
490
+ // iOS uses native implementation
491
+ return AsleepModule.requestRequiredPermissions();
327
492
  },
328
493
 
329
494
  setCustomNotification: async (title: string, text: string) => {
@@ -356,7 +521,7 @@ export const useAsleepStore = create<AsleepState>()(
356
521
  set({ analysisResult: convertedResult, isAnalyzing: false });
357
522
  }
358
523
  // For iOS, isAnalyzing will be set to false when onAnalysisResult event fires
359
-
524
+
360
525
  addLog(
361
526
  `[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`
362
527
  );
@@ -399,6 +564,8 @@ export const useAsleepStore = create<AsleepState>()(
399
564
  setIsSetupInProgress: (inProgress) =>
400
565
  set({ isSetupInProgress: inProgress }),
401
566
  setIsSetupComplete: (complete) => set({ isSetupComplete: complete }),
567
+ setHasCheckedStatus: (checked) => set({ hasCheckedStatus: checked }),
568
+ setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
402
569
 
403
570
  addLog: (log: string) => {
404
571
  const { showDebugLog } = get();
@@ -466,8 +633,7 @@ export const initializeAsleepListeners = () => {
466
633
  setSessionId(data.sessionId);
467
634
  }
468
635
  addLog(
469
- `[onTrackingCreated]${
470
- data?.sessionId ? ` sessionId: ${data.sessionId}` : ""
636
+ `[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""
471
637
  }`
472
638
  );
473
639
  },
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  AsleepEventType,
8
8
  AsleepReport,
9
9
  AsleepSession,
10
+ TrackingConfig,
10
11
  } from "./Asleep.types";
11
12
  import AsleepModule from "./AsleepModule";
12
13
  import { useAsleepStore, initializeAsleepListeners } from "./AsleepStore";
@@ -48,14 +49,14 @@ class Asleep {
48
49
  }
49
50
  };
50
51
 
51
- startTracking = async (): Promise<void> => {
52
- const permission = await this.requestMicrophonePermission();
52
+ startTracking = async (config?: TrackingConfig): Promise<void> => {
53
+ const permission = await this.requestRequiredPermissions();
53
54
  if (!permission) {
54
55
  Alert.alert("Microphone permission denied");
55
56
  throw new Error("Microphone permission denied");
56
57
  }
57
58
 
58
- return AsleepModule.startTracking();
59
+ return AsleepModule.startTracking(config);
59
60
  };
60
61
 
61
62
  stopTracking = async (): Promise<string> => {
@@ -83,8 +84,18 @@ class Asleep {
83
84
  return AsleepModule.deleteSession(sessionId);
84
85
  };
85
86
 
87
+ /**
88
+ * @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
89
+ */
86
90
  requestMicrophonePermission = async (): Promise<boolean> => {
87
- return AsleepModule.requestMicrophonePermission();
91
+ console.warn(
92
+ '[AsleepSDK] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.'
93
+ );
94
+ return this.requestRequiredPermissions();
95
+ };
96
+
97
+ requestRequiredPermissions = async (): Promise<boolean> => {
98
+ return AsleepModule.requestRequiredPermissions();
88
99
  };
89
100
 
90
101
  setCustomNotification = async (
@@ -143,6 +154,9 @@ export const useAsleep = () => {
143
154
  log,
144
155
  setup,
145
156
  initAsleepConfig,
157
+ checkAndRestoreTracking,
158
+ checkBatteryOptimization,
159
+ requestBatteryOptimizationExemption,
146
160
  startTracking,
147
161
  stopTracking,
148
162
  getReport,
@@ -150,6 +164,8 @@ export const useAsleep = () => {
150
164
  deleteSession,
151
165
  enableLog,
152
166
  setCustomNotification,
167
+ requestMicrophonePermission,
168
+ requestRequiredPermissions,
153
169
  requestAnalysis,
154
170
  isODAEnabled,
155
171
  analysisResult,
@@ -159,6 +175,8 @@ export const useAsleep = () => {
159
175
  isInitialized,
160
176
  isSetupInProgress,
161
177
  isSetupComplete,
178
+ hasCheckedStatus,
179
+ hasCheckedBatteryOptimization,
162
180
  } = useAsleepStore();
163
181
 
164
182
  useEffect(() => {
@@ -177,11 +195,16 @@ export const useAsleep = () => {
177
195
  setCustomNotification,
178
196
  setup,
179
197
  initAsleepConfig,
198
+ checkAndRestoreTracking,
199
+ checkBatteryOptimization,
200
+ requestBatteryOptimizationExemption,
180
201
  startTracking,
181
202
  stopTracking,
182
203
  getReport,
183
204
  getReportList,
184
205
  deleteSession,
206
+ requestMicrophonePermission,
207
+ requestRequiredPermissions,
185
208
  requestAnalysis,
186
209
  isODAEnabled,
187
210
  analysisResult,
@@ -191,6 +214,8 @@ export const useAsleep = () => {
191
214
  isInitialized,
192
215
  isSetupInProgress,
193
216
  isSetupComplete,
217
+ hasCheckedStatus,
218
+ hasCheckedBatteryOptimization,
194
219
  };
195
220
  };
196
221
 
@@ -202,7 +227,13 @@ export const AsleepSDK = {
202
227
  initAsleepConfig: (config: AsleepConfig) =>
203
228
  useAsleepStore.getState().initAsleepConfig(config),
204
229
 
205
- startTracking: () => useAsleepStore.getState().startTracking(),
230
+ checkAndRestoreTracking: () => useAsleepStore.getState().checkAndRestoreTracking(),
231
+
232
+ checkBatteryOptimization: () => useAsleepStore.getState().checkBatteryOptimization(),
233
+
234
+ requestBatteryOptimizationExemption: () => useAsleepStore.getState().requestBatteryOptimizationExemption(),
235
+
236
+ startTracking: (config?: TrackingConfig) => useAsleepStore.getState().startTracking(config),
206
237
 
207
238
  stopTracking: () => useAsleepStore.getState().stopTracking(),
208
239
 
@@ -215,6 +246,12 @@ export const AsleepSDK = {
215
246
  deleteSession: (sessionId: string) =>
216
247
  useAsleepStore.getState().deleteSession(sessionId),
217
248
 
249
+ requestMicrophonePermission: () =>
250
+ useAsleepStore.getState().requestMicrophonePermission(),
251
+
252
+ requestRequiredPermissions: () =>
253
+ useAsleepStore.getState().requestRequiredPermissions(),
254
+
218
255
  requestAnalysis: () => useAsleepStore.getState().requestAnalysis(),
219
256
 
220
257
  isTracking: () => useAsleepStore.getState().isTracking,
@@ -225,6 +262,10 @@ export const AsleepSDK = {
225
262
 
226
263
  isSetupComplete: () => useAsleepStore.getState().isSetupComplete,
227
264
 
265
+ hasCheckedStatus: () => useAsleepStore.getState().hasCheckedStatus,
266
+
267
+ hasCheckedBatteryOptimization: () => useAsleepStore.getState().hasCheckedBatteryOptimization,
268
+
228
269
  getUserId: () => useAsleepStore.getState().userId,
229
270
 
230
271
  getSessionId: () => useAsleepStore.getState().sessionId,
@@ -250,4 +291,5 @@ export type {
250
291
  AsleepSession,
251
292
  AsleepStat,
252
293
  AsleepAnalysisResult,
294
+ TrackingConfig,
253
295
  } from "./Asleep.types";