@mojro/react-native-gnss-tracking-health 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,369 @@
1
- # Temporary Holding Version
1
+ # react-native-gnss-tracking-health
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Device fitness, GNSS satellite coverage, system health, and tracking-quality alerts for React Native.
4
+
5
+ - **Peer dependency:** [`react-native-gnss-status-checker`](https://www.npmjs.com/package/react-native-gnss-status-checker) (Android GNSS)
6
+ - **Location traces:** feed from **any** tracking library (BGGeolocation, expo-location, etc.) via `ingestLocation`
7
+ - **Independent modules:** device fitness, system health, time/timezone validation
8
+ - **Alerts + in-app notifications:** via `configure({ showNotification })`
9
+ - **Hooks** for a tracking-quality screen
10
+
11
+ This package was extracted from the Mojro driver-app Tracking Quality POC. The app code is unchanged — wire this library when ready.
12
+
13
+ ---
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ yarn add react-native-gnss-tracking-health react-native-gnss-status-checker
19
+ # optional
20
+ yarn add react-native-device-info @notifee/react-native
21
+ ```
22
+
23
+ Link / rebuild native for `react-native-gnss-status-checker`.
24
+
25
+ Local path (development):
26
+
27
+ ```bash
28
+ yarn add file:../react-native-gnss-tracking-health
29
+ # or
30
+ yarn add /Users/you/Desktop/react-native-gnss-tracking-health
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Quick start
36
+
37
+ ```js
38
+ import BackgroundGeolocation from "react-native-background-geolocation";
39
+ import {
40
+ configure,
41
+ useTrackingQuality,
42
+ validateTimeAndTimezone,
43
+ getThresholds,
44
+ } from "react-native-gnss-tracking-health";
45
+ import { showNotification } from "./utils/notifeeUtil"; // your app
46
+
47
+ // Once at app boot — thresholds optional; library defaults apply
48
+ configure({
49
+ getPowerSaveMode: () => BackgroundGeolocation.isPowerSaveMode(),
50
+ isIgnoringBatteryOptimizations: () =>
51
+ BackgroundGeolocation.deviceSettings.isIgnoringBatteryOptimizations(),
52
+ showNotification: (title, message) =>
53
+ showNotification(title, message, { debounce: true }),
54
+ persistAlert: (alert) => {
55
+ // saveLog / analytics
56
+ },
57
+ thresholds: {
58
+ minSatellitesForGoodFix: 8,
59
+ tripStartSatWindowMs: 45_000,
60
+ poorAccuracyThresholdM: 40,
61
+ },
62
+ // apiLevelThresholds: { MIN_ACCEPTABLE_FOR_TRACKING: 26 },
63
+ });
64
+ // getThresholds() → merged defaults + overrides
65
+
66
+ // Feed traces from your tracker (BGGeolocation example)
67
+ BackgroundGeolocation.onLocation((location) => {
68
+ // import { trackingQualityMonitor } from 'react-native-gnss-tracking-health'
69
+ trackingQualityMonitor.ingestLocation(location);
70
+ });
71
+
72
+ // Gate session validations (accuracy / throttle / teleport) on tracking active
73
+ BackgroundGeolocation.onEnabledChange((enabled) => {
74
+ trackingQualityMonitor.setLocationTrackingActive(!!enabled);
75
+ });
76
+
77
+ // Once at login / session restore (independent of tracking)
78
+ trackingQualityMonitor.evaluateDeviceFitnessOnLogin();
79
+ ```
80
+
81
+ **Session rules** (poor accuracy, throttle, teleport, mock) run only while `setLocationTrackingActive(true)`.
82
+
83
+ **Poor-accuracy timer:** starts when accuracy is poor (default > 50m) or sats are low; **resets immediately** when a fix arrives with good accuracy (≤ 50m).
84
+
85
+ **Throttle:** while tracking is active, if time since last ingested fix ≥ `max(throttleMinGapMs, expectedTraceIntervalMs × throttleGapMultiplier)` (default **3 minutes**), raises `LOCATION_THROTTLING`.
86
+
87
+ ### Screen hooks
88
+
89
+ Use `useTrackingMonitor` for a POC-equivalent surface (status + alerts + throttled live log + controls).
90
+ `useTrackingQuality` is a lighter status/control hook without the live log buffer.
91
+
92
+ ```jsx
93
+ import React from "react";
94
+ import { View, Text, Button, FlatList } from "react-native";
95
+ import { useTrackingMonitor } from "react-native-gnss-tracking-health";
96
+
97
+ export function TrackingQualityScreen() {
98
+ const {
99
+ status,
100
+ deviceFitness,
101
+ latestGnss,
102
+ latestSystem,
103
+ recentAlerts,
104
+ logs,
105
+ locationTrackingActive,
106
+ start,
107
+ stop,
108
+ onTripStarted,
109
+ evaluateDeviceFitness,
110
+ setLocationTrackingActive,
111
+ } = useTrackingMonitor();
112
+
113
+ return (
114
+ <View>
115
+ <Text>Running: {String(status.running)}</Text>
116
+ <Text>Tracking active: {String(locationTrackingActive)}</Text>
117
+ <Text>Fitness: {deviceFitness?.fitness}</Text>
118
+ <Text>
119
+ Sats: {latestGnss?.satellitesVisible}/{latestGnss?.satellitesUsedInFix}
120
+ </Text>
121
+ <Text>Battery: {latestSystem?.batteryLevel}%</Text>
122
+ <Button
123
+ title="Start"
124
+ onPress={() => {
125
+ setLocationTrackingActive(true);
126
+ start({ tripId: `trip-${Date.now()}`, notifyDriver: true });
127
+ }}
128
+ />
129
+ <Button title="Trip start" onPress={() => onTripStarted(`trip-${Date.now()}`)} />
130
+ <Button title="Fitness" onPress={() => evaluateDeviceFitness()} />
131
+ <Button
132
+ title="Stop"
133
+ onPress={() => {
134
+ setLocationTrackingActive(false);
135
+ stop();
136
+ }}
137
+ />
138
+ {recentAlerts.map((a) => (
139
+ <Text key={`${a.type}-${a.at}`}>{a.type}: {a.message}</Text>
140
+ ))}
141
+ <FlatList
142
+ data={logs}
143
+ keyExtractor={(item) => item.id}
144
+ renderItem={({ item }) => (
145
+ <Text>
146
+ [{item.level}] {item.message}
147
+ </Text>
148
+ )}
149
+ />
150
+ </View>
151
+ );
152
+ }
153
+ ```
154
+
155
+ Event names match the driver app (`TrackingQualityMonitor:alert|status|gnss|action`) so existing listeners keep working.
156
+
157
+ ---
158
+
159
+ ## Independent APIs
160
+
161
+ ### Device fitness
162
+
163
+ ```js
164
+ import { assessDeviceFitness, useDeviceFitness } from "react-native-gnss-tracking-health";
165
+
166
+ const { fitness, evaluate, capableForTracking } = useDeviceFitness();
167
+ ```
168
+
169
+ Uses API level + GNSS capability flags + settings — **not** live satellite counts.
170
+
171
+ ### System health
172
+
173
+ ```js
174
+ import { collectSystemHealth, useSystemHealth } from "react-native-gnss-tracking-health";
175
+
176
+ const health = await collectSystemHealth();
177
+ ```
178
+
179
+ ### Background restrictions (battery optimization + Samsung "Never sleeping apps")
180
+
181
+ Android only. The library ships a small native module (autolinked; rebuild the app after installing). It reports **two different settings separately**:
182
+
183
+ | Setting | Detectable? | How |
184
+ |---------|-------------|-----|
185
+ | Android "Ignore battery optimizations" (Doze) | **Yes** | `PowerManager.isIgnoringBatteryOptimizations()` |
186
+ | Samsung "Never sleeping apps" list | **No** | Samsung documents an intent to *open* the list but no public API to *read* it |
187
+
188
+ Because Samsung offers no way to read the list, the library never reports it as verified. `neverSleepingApps.verifiable` is always `false`; `userConfirmed` only reflects what the driver told you via `setNeverSleepingAppsConfirmed()` (persisted natively).
189
+
190
+ ```js
191
+ import {
192
+ getBackgroundSettingsStatus,
193
+ openNeverSleepingApps,
194
+ openBatteryOptimizationSettings,
195
+ setNeverSleepingAppsConfirmed,
196
+ NEVER_SLEEPING_STATE,
197
+ } from "react-native-gnss-tracking-health";
198
+
199
+ const s = await getBackgroundSettingsStatus();
200
+ // s.ignoringBatteryOptimizations -> true | false (verified) | null
201
+ // s.isSamsung, s.manufacturer, s.model
202
+ // s.neverSleepingApps = {
203
+ // applicable, verifiable: false,
204
+ // state: "not_applicable" | "unverified" | "user_confirmed" | "user_reported_missing",
205
+ // userConfirmed: true | false | null,
206
+ // settingsScreenAvailable
207
+ // }
208
+
209
+ if (s.isSamsung && s.neverSleepingApps.state !== NEVER_SLEEPING_STATE.USER_CONFIRMED) {
210
+ const opened = await openNeverSleepingApps(); // deep link to the exact screen
211
+ if (!opened) await openBatteryOptimizationSettings(); // fallback
212
+ // When the driver returns, ask them, then:
213
+ await setNeverSleepingAppsConfirmed(true); // or false / null to clear
214
+ }
215
+ ```
216
+
217
+ `collectSystemHealth()` also includes `manufacturer`, `isSamsung` and `neverSleepingApps`. These are diagnostic only and do **not** affect device fitness. If `configure({ isIgnoringBatteryOptimizations })` is not set, the native PowerManager check is used.
218
+
219
+ The Samsung screen is `com.samsung.android.sm.ACTION_OPEN_CHECKABLE_LISTACTIVITY` (package `com.samsung.android.lool`, `activity_type=2`). OEM screens can change between One UI versions, so `openNeverSleepingApps()` resolves `false` instead of throwing; test on the One UI versions you support. The library manifest adds the `<queries>` entry needed on Android 11+.
220
+
221
+ #### Open the right background screen on any Android device
222
+
223
+ ```js
224
+ import { openBackgroundRestrictionSettings } from "react-native-gnss-tracking-health";
225
+
226
+ const r = await openBackgroundRestrictionSettings();
227
+ // { opened: true, target: "xiaomi_autostart", isOemScreen: true, manufacturer: "Xiaomi" }
228
+ ```
229
+
230
+ Tries, in order: the manufacturer's own screen (Samsung Never sleeping apps, Xiaomi Autostart, Huawei/Honor Startup manager, Oppo/Realme/OnePlus Startup manager, Vivo/iQOO Background startup, Asus, Nokia, Letv), then Android's "Optimize battery usage" list, then this app's "App info" page. It never rejects. `target` tells you which one opened (`isOemScreen: false` means a universal fallback). OEM screens are undocumented and vary by model and OS version, so test on the devices you support. No manufacturer lets an app read whether it was added to these lists, so this only navigates; it cannot verify.
231
+
232
+ ### Time / timezone (standalone)
233
+
234
+ Android auto date/time + timezone lives in its **own native package** (not mixed with battery-settings code), matching the driver-app layout:
235
+
236
+ ```
237
+ android/src/main/java/com/gnsstrackinghealth/
238
+ GnssTrackingHealthSettingsModule.java # battery / Samsung only
239
+ autodatetime/
240
+ AutoDateTimeModule.java # AUTO_TIME + AUTO_TIME_ZONE
241
+ AutoDateTimePackage.java
242
+ ```
243
+
244
+ Clock skew uses HTTP `Date` headers (JS, both platforms) with the **same rule as the driver app**: skewed only when **all three** sources respond and all are beyond the threshold; otherwise `null` (inconclusive) or `false` (OK). Host apps only consume the flags:
245
+
246
+ ```js
247
+ import {
248
+ validateTimeAndTimezone,
249
+ isClockSkewed,
250
+ isAutomaticDateTimeEnabled,
251
+ openDateTimeSettings,
252
+ useTimeValidation,
253
+ } from "react-native-gnss-tracking-health";
254
+
255
+ const result = await validateTimeAndTimezone();
256
+ // {
257
+ // autoDateTimeEnabled, // Android: true|false ; iOS: null
258
+ // clockSkewed,
259
+ // badTimeOrTimezone,
260
+ // ...
261
+ // }
262
+
263
+ if (result.autoDateTimeEnabled === false) {
264
+ await openDateTimeSettings();
265
+ }
266
+ ```
267
+
268
+ Optional override: `configure({ isAutomaticDateTimeEnabled: () => ... })`.
269
+
270
+ ---
271
+
272
+ ## Location adapter
273
+
274
+ Any shape is accepted; normalize helpers understand BGGeolocation and common GPS objects:
275
+
276
+ ```js
277
+ ingestLocation(bgLocation);
278
+ ingestLocation({ latitude, longitude, accuracy, mocked, timestamp });
279
+ ingestLocation({ coords: { latitude, longitude, accuracy }, mock: false });
280
+ ```
281
+
282
+ ---
283
+
284
+ ## Alerts
285
+
286
+ | Type | Meaning |
287
+ |------|---------|
288
+ | `LOCATION_MOCKED` | Mock GPS |
289
+ | `LOW_SATELLITE_AFTER_TRIP_START` | &lt; 6 sats in first 30s |
290
+ | `POOR_TRACKING_SUSTAINED` | Poor accuracy/sats &gt; 10 min |
291
+ | `ABNORMAL_TRACE` | Teleport jump |
292
+ | `BATTERY_OPTIMIZATION_ENABLED` | Android batt opt |
293
+ | `LOW_POWER_MODE` | Power saver |
294
+ | `LOCATION_THROTTLING` | Sparse traces |
295
+ | `BACKGROUND_TRACKING_RESTRICTED` | BG restriction proxy |
296
+ | `BAD_TIME_TIMEZONE` | Auto time off / clock skew |
297
+
298
+ Notifications fire only when `configure({ showNotification })` is set and `start({ notify: true })` (default).
299
+
300
+ ---
301
+
302
+ ## Configurable thresholds
303
+
304
+ All numeric defaults live in `DEFAULT_THRESHOLDS` / `DEFAULT_API_LEVEL_THRESHOLDS`.
305
+ Pass partial overrides via `configure({ thresholds, apiLevelThresholds })`.
306
+ Read the merged result with `getThresholds()` / `getApiLevelThresholds()`.
307
+
308
+ | Key | Default | Meaning |
309
+ |-----|---------|---------|
310
+ | `tripStartSatWindowMs` | 30000 | Trip-start sat window |
311
+ | `minSatellitesForGoodFix` | 6 | Min sats for “good” |
312
+ | `poorTrackingDurationMs` | 600000 | Sustained poor tracking |
313
+ | `poorAccuracyThresholdM` | 50 | Poor accuracy (m) |
314
+ | `teleportImpliedSpeedKmh` | 200 | Teleport speed |
315
+ | `teleportMinJumpMeters` | 500 | Teleport distance |
316
+ | `expectedTraceIntervalMs` | 60000 | Expected fix interval |
317
+ | `throttleGapMultiplier` | 3 | Throttle gap × expected |
318
+ | `throttleMinGapMs` | 180000 | Min throttle gap |
319
+ | `systemCheckIntervalMs` | 60000 | System health poll |
320
+ | `alertCooldownMs` | 300000 | Per-alert-type cooldown |
321
+ | `timeSkewThresholdMinutes` | 2 | Clock skew |
322
+ | `lowBatteryFraction` | 0.15 | Low battery (0..1) |
323
+
324
+ ## GNSS interval note
325
+
326
+ GNSS uses Android `GnssStatus.Callback` (typically ~1 Hz). The trip-start rule uses `tripStartSatWindowMs` (default **30s**). System health re-checks every `systemCheckIntervalMs` (default **60s**). There is no fixed app timer for GNSS polling.
327
+
328
+ ---
329
+
330
+ ## Example app
331
+
332
+ A full React Native **0.88.1** demo lives in [`example/`](./example). It mirrors the driver-app Tracking Quality POC UI (fitness, GNSS, system health, alerts, live log) and uses **BGGeolocation Start / Stop** instead of a real trip:
333
+
334
+ ```bash
335
+ cd example
336
+ # set LICENSE_KEY in src/setupTracking.js
337
+ yarn install
338
+ yarn android # or yarn ios
339
+ ```
340
+
341
+ See [`example/README.md`](./example/README.md) for controls, patches, and demo thresholds.
342
+
343
+ ---
344
+
345
+ ## Project layout
346
+
347
+ ```
348
+ src/
349
+ TrackingQualityMonitor.js # orchestrator + singleton
350
+ gnssMonitor.js # peer: react-native-gnss-status-checker
351
+ deviceFitness.js
352
+ systemHealth.js
353
+ backgroundSettings.js # battery optimization + Samsung Never sleeping apps
354
+ timeValidation.js # standalone time/tz
355
+ traceAnalyzer.js
356
+ adapters/normalizeLocation.js
357
+ hooks/
358
+ constants.js
359
+ config.js
360
+ index.js
361
+ android/ # native module (Java): settings status + deep links
362
+ example/ # RN demo with BGGeolocation start/stop
363
+ ```
364
+
365
+ ---
366
+
367
+ ## License
368
+
369
+ MIT
@@ -0,0 +1,31 @@
1
+ apply plugin: 'com.android.library'
2
+
3
+ def safeExtGet(prop, fallback) {
4
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
5
+ }
6
+
7
+ android {
8
+ namespace "com.gnsstrackinghealth"
9
+
10
+ compileSdkVersion safeExtGet('compileSdkVersion', 35)
11
+
12
+ defaultConfig {
13
+ minSdkVersion safeExtGet('minSdkVersion', 24)
14
+ targetSdkVersion safeExtGet('targetSdkVersion', 35)
15
+ }
16
+
17
+ compileOptions {
18
+ sourceCompatibility JavaVersion.VERSION_17
19
+ targetCompatibility JavaVersion.VERSION_17
20
+ }
21
+ }
22
+
23
+ repositories {
24
+ google()
25
+ mavenCentral()
26
+ }
27
+
28
+ dependencies {
29
+ // Version is supplied by the host app's React Native Gradle plugin.
30
+ implementation "com.facebook.react:react-android"
31
+ }
@@ -0,0 +1,24 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+
3
+ <!--
4
+ Package visibility (Android 11+): lets the library resolve the OEM
5
+ system-manager apps that host the "Never sleeping apps" / autostart /
6
+ background-startup screens opened by openBackgroundRestrictionSettings().
7
+ Merged into the host app's manifest automatically.
8
+ -->
9
+ <queries>
10
+ <package android:name="com.samsung.android.lool" />
11
+ <package android:name="com.miui.securitycenter" />
12
+ <package android:name="com.miui.powerkeeper" />
13
+ <package android:name="com.huawei.systemmanager" />
14
+ <package android:name="com.coloros.safecenter" />
15
+ <package android:name="com.oppo.safe" />
16
+ <package android:name="com.oneplus.security" />
17
+ <package android:name="com.vivo.permissionmanager" />
18
+ <package android:name="com.iqoo.secure" />
19
+ <package android:name="com.asus.mobilemanager" />
20
+ <package android:name="com.evenwell.powersaving.g3" />
21
+ <package android:name="com.letv.android.letvsafe" />
22
+ </queries>
23
+
24
+ </manifest>
@@ -0,0 +1,31 @@
1
+ package com.gnsstrackinghealth;
2
+
3
+ import com.facebook.react.ReactPackage;
4
+ import com.facebook.react.bridge.NativeModule;
5
+ import com.facebook.react.bridge.ReactApplicationContext;
6
+ import com.facebook.react.uimanager.ViewManager;
7
+ import com.gnsstrackinghealth.autodatetime.AutoDateTimeModule;
8
+
9
+ import java.util.Arrays;
10
+ import java.util.Collections;
11
+ import java.util.List;
12
+
13
+ /**
14
+ * Autolinked package: battery / Samsung settings + AutoDateTime module.
15
+ * AutoDateTime lives in {@code com.gnsstrackinghealth.autodatetime} (own folder),
16
+ * not inside the settings module.
17
+ */
18
+ public class GnssTrackingHealthPackage implements ReactPackage {
19
+
20
+ @Override
21
+ public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
22
+ return Arrays.<NativeModule>asList(
23
+ new GnssTrackingHealthSettingsModule(reactContext),
24
+ new AutoDateTimeModule(reactContext));
25
+ }
26
+
27
+ @Override
28
+ public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
29
+ return Collections.<ViewManager>emptyList();
30
+ }
31
+ }