@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.
@@ -0,0 +1,257 @@
1
+ import { NativeModules, Platform } from "react-native";
2
+ import { getLogger } from "./utils/logger";
3
+
4
+ /**
5
+ * Background-restriction diagnostics (Android).
6
+ *
7
+ * Two separate settings, reported separately:
8
+ *
9
+ * - Android "Ignore battery optimizations" -> VERIFIED via PowerManager.
10
+ * - Samsung "Never sleeping apps" list -> NOT verifiable. Samsung
11
+ * documents an intent to open the screen but no public API to read
12
+ * whether this app is on the list. We report `verifiable: false` and
13
+ * only surface what the user has told us (`userConfirmed`).
14
+ */
15
+
16
+ export const NEVER_SLEEPING_STATE = {
17
+ /** Not a Samsung Android device — the list does not exist. */
18
+ NOT_APPLICABLE: "not_applicable",
19
+ /** Samsung device, nothing known (cannot be read from the OS). */
20
+ UNVERIFIED: "unverified",
21
+ /** User said the app is on the list (self-reported, not verified). */
22
+ USER_CONFIRMED: "user_confirmed",
23
+ /** User said the app is NOT on the list (self-reported). */
24
+ USER_REPORTED_MISSING: "user_reported_missing",
25
+ };
26
+
27
+ const NEVER_SLEEPING_NOTE =
28
+ "Samsung exposes no public API to verify the Never sleeping apps list. " +
29
+ "This value is only what the user reported.";
30
+
31
+ function getNative() {
32
+ if (Platform.OS !== "android") {
33
+ return null;
34
+ }
35
+ return NativeModules.GnssTrackingHealthSettings || null;
36
+ }
37
+
38
+ function jsManufacturer() {
39
+ if (Platform.OS !== "android") {
40
+ return null;
41
+ }
42
+ return Platform.constants?.Manufacturer || null;
43
+ }
44
+
45
+ function buildNeverSleeping({
46
+ isSamsung,
47
+ userConfirmed,
48
+ settingsScreenAvailable,
49
+ }) {
50
+ let state = NEVER_SLEEPING_STATE.NOT_APPLICABLE;
51
+ if (isSamsung) {
52
+ if (userConfirmed === true) {
53
+ state = NEVER_SLEEPING_STATE.USER_CONFIRMED;
54
+ } else if (userConfirmed === false) {
55
+ state = NEVER_SLEEPING_STATE.USER_REPORTED_MISSING;
56
+ } else {
57
+ state = NEVER_SLEEPING_STATE.UNVERIFIED;
58
+ }
59
+ }
60
+ return {
61
+ applicable: !!isSamsung,
62
+ verifiable: false,
63
+ state,
64
+ userConfirmed: isSamsung ? userConfirmed ?? null : null,
65
+ settingsScreenAvailable: !!settingsScreenAvailable,
66
+ note: NEVER_SLEEPING_NOTE,
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Collect both background-restriction statuses.
72
+ * Never rejects: falls back to a best-effort JS-only result when the native
73
+ * module is not linked.
74
+ */
75
+ export async function getBackgroundSettingsStatus() {
76
+ const native = getNative();
77
+ const checkedAt = Date.now();
78
+
79
+ if (!native?.getBackgroundSettingsStatus) {
80
+ if (Platform.OS === "android") {
81
+ getLogger().warn(
82
+ "GnssTrackingHealthSettings native module missing — rebuild the Android app"
83
+ );
84
+ }
85
+ const manufacturer = jsManufacturer();
86
+ const isSamsung = String(manufacturer || "").toLowerCase() === "samsung";
87
+ return {
88
+ platform: Platform.OS,
89
+ nativeModuleAvailable: false,
90
+ manufacturer,
91
+ brand: Platform.constants?.Brand || null,
92
+ model: Platform.constants?.Model || null,
93
+ sdkInt: null,
94
+ isSamsung,
95
+ ignoringBatteryOptimizations: null,
96
+ neverSleepingApps: buildNeverSleeping({
97
+ isSamsung,
98
+ userConfirmed: null,
99
+ settingsScreenAvailable: false,
100
+ }),
101
+ checkedAt,
102
+ };
103
+ }
104
+
105
+ try {
106
+ const raw = await native.getBackgroundSettingsStatus();
107
+ return {
108
+ platform: Platform.OS,
109
+ nativeModuleAvailable: true,
110
+ manufacturer: raw.manufacturer,
111
+ brand: raw.brand,
112
+ model: raw.model,
113
+ sdkInt: raw.sdkInt,
114
+ isSamsung: !!raw.isSamsung,
115
+ ignoringBatteryOptimizations: !!raw.ignoringBatteryOptimizations,
116
+ neverSleepingApps: buildNeverSleeping({
117
+ isSamsung: !!raw.isSamsung,
118
+ userConfirmed: raw.neverSleepingUserConfirmed ?? null,
119
+ settingsScreenAvailable: !!raw.neverSleepingScreenAvailable,
120
+ }),
121
+ checkedAt,
122
+ };
123
+ } catch (error) {
124
+ getLogger().warn("getBackgroundSettingsStatus failed:", error?.message);
125
+ return {
126
+ platform: Platform.OS,
127
+ nativeModuleAvailable: true,
128
+ manufacturer: jsManufacturer(),
129
+ isSamsung: false,
130
+ ignoringBatteryOptimizations: null,
131
+ neverSleepingApps: buildNeverSleeping({
132
+ isSamsung: false,
133
+ userConfirmed: null,
134
+ settingsScreenAvailable: false,
135
+ }),
136
+ error: error?.message || "getBackgroundSettingsStatus failed",
137
+ checkedAt,
138
+ };
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Android "Ignore battery optimizations" (verified).
144
+ * Resolves null when it cannot be determined (iOS / native module missing).
145
+ */
146
+ export async function isIgnoringBatteryOptimizations() {
147
+ const native = getNative();
148
+ if (!native?.isIgnoringBatteryOptimizations) {
149
+ return null;
150
+ }
151
+ try {
152
+ return !!(await native.isIgnoringBatteryOptimizations());
153
+ } catch (error) {
154
+ getLogger().warn("isIgnoringBatteryOptimizations failed:", error?.message);
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Open Samsung's "Never sleeping apps" screen.
161
+ * Resolves false when the device is not Samsung or the screen is unavailable
162
+ * (callers can then fall back to openBatteryOptimizationSettings()).
163
+ */
164
+ export async function openNeverSleepingApps() {
165
+ const native = getNative();
166
+ if (!native?.openNeverSleepingApps) {
167
+ return false;
168
+ }
169
+ try {
170
+ return !!(await native.openNeverSleepingApps());
171
+ } catch (error) {
172
+ getLogger().warn("openNeverSleepingApps failed:", error?.message);
173
+ return false;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Open the best "background / autostart / never sleeping" screen for THIS
179
+ * device — works on every Android device, not just Samsung.
180
+ *
181
+ * Order tried natively: manufacturer-specific screen (Samsung, Xiaomi, Huawei /
182
+ * Honor, Oppo / Realme / OnePlus, Vivo / iQOO, Asus, Nokia, Letv) ->
183
+ * Android "Optimize battery usage" list -> this app's "App info" page.
184
+ *
185
+ * OEM screens are undocumented and vary by model / OS version, so they are
186
+ * best-effort. Nothing here can verify the app was added to any list.
187
+ *
188
+ * Never rejects. Resolves:
189
+ * { opened, target, isOemScreen, manufacturer }
190
+ * `target` is e.g. "samsung_never_sleeping", "xiaomi_autostart",
191
+ * "battery_optimization", "app_details", or "none".
192
+ */
193
+ export async function openBackgroundRestrictionSettings() {
194
+ const fallback = {
195
+ opened: false,
196
+ target: "none",
197
+ isOemScreen: false,
198
+ manufacturer: jsManufacturer(),
199
+ };
200
+ const native = getNative();
201
+ if (!native?.openBackgroundRestrictionSettings) {
202
+ if (Platform.OS === "android") {
203
+ getLogger().warn(
204
+ "openBackgroundRestrictionSettings unavailable — rebuild the Android app"
205
+ );
206
+ }
207
+ return fallback;
208
+ }
209
+ try {
210
+ const raw = await native.openBackgroundRestrictionSettings();
211
+ return {
212
+ opened: !!raw?.opened,
213
+ target: raw?.target || "none",
214
+ isOemScreen: !!raw?.isOemScreen,
215
+ manufacturer: raw?.manufacturer || fallback.manufacturer,
216
+ };
217
+ } catch (error) {
218
+ getLogger().warn("openBackgroundRestrictionSettings failed:", error?.message);
219
+ return fallback;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Open Android's "Optimize battery usage" list. Resolves false on failure.
225
+ */
226
+ export async function openBatteryOptimizationSettings() {
227
+ const native = getNative();
228
+ if (!native?.openBatteryOptimizationSettings) {
229
+ return false;
230
+ }
231
+ try {
232
+ return !!(await native.openBatteryOptimizationSettings());
233
+ } catch (error) {
234
+ getLogger().warn("openBatteryOptimizationSettings failed:", error?.message);
235
+ return false;
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Record what the user says about the Never sleeping apps list
241
+ * (persisted natively). Pass `null` to clear. This does NOT verify anything.
242
+ */
243
+ export async function setNeverSleepingAppsConfirmed(confirmed) {
244
+ const native = getNative();
245
+ if (!native) {
246
+ return false;
247
+ }
248
+ try {
249
+ if (confirmed === null || confirmed === undefined) {
250
+ return !!(await native.clearNeverSleepingAppsConfirmation());
251
+ }
252
+ return !!(await native.setNeverSleepingAppsConfirmed(!!confirmed));
253
+ } catch (error) {
254
+ getLogger().warn("setNeverSleepingAppsConfirmed failed:", error?.message);
255
+ return false;
256
+ }
257
+ }
package/src/config.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Host-app injection point + runtime threshold overrides.
3
+ */
4
+
5
+ import {
6
+ DEFAULT_API_LEVEL_THRESHOLDS,
7
+ DEFAULT_THRESHOLDS,
8
+ } from "./constants";
9
+
10
+ const defaultConfig = {
11
+ getPowerSaveMode: null,
12
+ isIgnoringBatteryOptimizations: null,
13
+ getPowerState: null,
14
+ getBatteryLevel: null,
15
+ isAutomaticDateTimeEnabled: null,
16
+ showNotification: null,
17
+ persistAlert: null,
18
+ logger: null,
19
+ /** Partial override of DEFAULT_THRESHOLDS */
20
+ thresholds: {},
21
+ /** Partial override of DEFAULT_API_LEVEL_THRESHOLDS */
22
+ apiLevelThresholds: {},
23
+ };
24
+
25
+ let config = {
26
+ ...defaultConfig,
27
+ thresholds: {},
28
+ apiLevelThresholds: {},
29
+ };
30
+
31
+ export function configure(partial = {}) {
32
+ const nextThresholds = {
33
+ ...(config.thresholds || {}),
34
+ ...(partial.thresholds || {}),
35
+ };
36
+ const nextApiLevel = {
37
+ ...(config.apiLevelThresholds || {}),
38
+ ...(partial.apiLevelThresholds || {}),
39
+ };
40
+
41
+ const { thresholds: _t, apiLevelThresholds: _a, ...rest } = partial;
42
+
43
+ config = {
44
+ ...config,
45
+ ...rest,
46
+ thresholds: nextThresholds,
47
+ apiLevelThresholds: nextApiLevel,
48
+ };
49
+
50
+ if (partial.logger) {
51
+ // eslint-disable-next-line global-require
52
+ const { setLogger } = require("./utils/logger");
53
+ setLogger(partial.logger);
54
+ }
55
+
56
+ return getConfig();
57
+ }
58
+
59
+ export function getConfig() {
60
+ return {
61
+ ...config,
62
+ thresholds: getThresholds(),
63
+ apiLevelThresholds: getApiLevelThresholds(),
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Effective runtime thresholds = library defaults merged with user overrides.
69
+ */
70
+ export function getThresholds() {
71
+ return {
72
+ ...DEFAULT_THRESHOLDS,
73
+ ...(config.thresholds || {}),
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Effective Android API floors for device fitness scoring.
79
+ */
80
+ export function getApiLevelThresholds() {
81
+ return {
82
+ ...DEFAULT_API_LEVEL_THRESHOLDS,
83
+ ...(config.apiLevelThresholds || {}),
84
+ };
85
+ }
86
+
87
+ export function resetConfig() {
88
+ config = {
89
+ ...defaultConfig,
90
+ thresholds: {},
91
+ apiLevelThresholds: {},
92
+ };
93
+ // eslint-disable-next-line global-require
94
+ const { setLogger } = require("./utils/logger");
95
+ setLogger(null);
96
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Defaults + enums for react-native-gnss-tracking-health.
3
+ * Numeric thresholds are overridable via configure({ thresholds, apiLevelThresholds }).
4
+ */
5
+
6
+ export const ALERT_TYPES = {
7
+ LOCATION_MOCKED: "LOCATION_MOCKED",
8
+ LOW_SATELLITE_AFTER_TRIP_START: "LOW_SATELLITE_AFTER_TRIP_START",
9
+ POOR_TRACKING_SUSTAINED: "POOR_TRACKING_SUSTAINED",
10
+ ABNORMAL_TRACE: "ABNORMAL_TRACE",
11
+ BATTERY_OPTIMIZATION_ENABLED: "BATTERY_OPTIMIZATION_ENABLED",
12
+ LOW_POWER_MODE: "LOW_POWER_MODE",
13
+ LOCATION_THROTTLING: "LOCATION_THROTTLING",
14
+ BACKGROUND_TRACKING_RESTRICTED: "BACKGROUND_TRACKING_RESTRICTED",
15
+ BAD_TIME_TIMEZONE: "BAD_TIME_TIMEZONE",
16
+ };
17
+
18
+ export const ALERT_SEVERITY = {
19
+ BLOCKER: "blocker",
20
+ WARNING: "warning",
21
+ INFO: "info",
22
+ };
23
+
24
+ /** Default Android API floors for device fitness (overridable). */
25
+ export const DEFAULT_API_LEVEL_THRESHOLDS = {
26
+ MIN_LEGACY_GNSS: 21,
27
+ MIN_BASIC_GNSS: 21,
28
+ MIN_FULL_GNSS_STATUS: 24,
29
+ MIN_CARRIER_FREQUENCY: 26,
30
+ MIN_BACKGROUND_LOCATION_PERMISSION: 29,
31
+ MIN_PRECISE_LOCATION_MODEL: 31,
32
+ MIN_FGS_LOCATION_TYPE: 34,
33
+ MIN_ACCEPTABLE_FOR_TRACKING: 24,
34
+ PREFERRED_FOR_ENHANCED_GNSS: 26,
35
+ };
36
+
37
+ /** @deprecated Use DEFAULT_API_LEVEL_THRESHOLDS or getApiLevelThresholds() */
38
+ export const API_LEVEL_THRESHOLDS = DEFAULT_API_LEVEL_THRESHOLDS;
39
+
40
+ export const DEVICE_FITNESS = {
41
+ UNFIT: "unfit",
42
+ WEAK: "weak",
43
+ ACCEPTABLE: "acceptable",
44
+ GOOD: "good",
45
+ RISKY_SETTINGS: "risky_settings",
46
+ UNKNOWN: "unknown",
47
+ };
48
+
49
+ export const GNSS_CAPABILITY_BY_API = {
50
+ unsupported: {
51
+ satelliteCount: false,
52
+ constellation: false,
53
+ cn0: false,
54
+ elevationAzimuth: false,
55
+ measurements: false,
56
+ carrierFrequency: false,
57
+ },
58
+ legacy: {
59
+ satelliteCount: true,
60
+ constellation: false,
61
+ cn0: false,
62
+ elevationAzimuth: false,
63
+ measurements: false,
64
+ carrierFrequency: false,
65
+ },
66
+ basic: {
67
+ satelliteCount: true,
68
+ constellation: true,
69
+ cn0: false,
70
+ elevationAzimuth: false,
71
+ measurements: false,
72
+ carrierFrequency: false,
73
+ },
74
+ full_status: {
75
+ satelliteCount: true,
76
+ constellation: true,
77
+ cn0: true,
78
+ elevationAzimuth: true,
79
+ measurements: true,
80
+ carrierFrequency: false,
81
+ },
82
+ enhanced: {
83
+ satelliteCount: true,
84
+ constellation: true,
85
+ cn0: true,
86
+ elevationAzimuth: true,
87
+ measurements: true,
88
+ carrierFrequency: true,
89
+ },
90
+ unknown: {
91
+ satelliteCount: false,
92
+ constellation: false,
93
+ cn0: false,
94
+ elevationAzimuth: false,
95
+ measurements: false,
96
+ carrierFrequency: false,
97
+ },
98
+ };
99
+
100
+ /**
101
+ * Runtime quality / alert thresholds (library defaults).
102
+ * Override any subset with configure({ thresholds: { ... } }).
103
+ */
104
+ export const DEFAULT_THRESHOLDS = {
105
+ /** Trip-start satellite visibility window (ms) */
106
+ tripStartSatWindowMs: 30 * 1000,
107
+ /** Minimum visible sats considered a good fix */
108
+ minSatellitesForGoodFix: 6,
109
+ /** Sustained poor tracking duration (ms) */
110
+ poorTrackingDurationMs: 10 * 60 * 1000,
111
+ /** Accuracy above this (meters) counts as poor */
112
+ poorAccuracyThresholdM: 50,
113
+ /** Teleport implied speed (km/h) */
114
+ teleportImpliedSpeedKmh: 200,
115
+ /** Teleport minimum jump distance (meters) */
116
+ teleportMinJumpMeters: 500,
117
+ /** Expected location update interval (ms) */
118
+ expectedTraceIntervalMs: 60 * 1000,
119
+ /** Multiplier on expected interval for throttle detection */
120
+ throttleGapMultiplier: 3,
121
+ /** Absolute minimum gap before throttle alert (ms) */
122
+ throttleMinGapMs: 3 * 60 * 1000,
123
+ /** How often to re-check OS / battery / time (ms) */
124
+ systemCheckIntervalMs: 60 * 1000,
125
+ /** Cooldown so the same alert type does not spam (ms) */
126
+ alertCooldownMs: 5 * 60 * 1000,
127
+ /** Clock skew vs HTTP Date sources (minutes) */
128
+ timeSkewThresholdMinutes: 2,
129
+ /** Battery level (0..1) below which lowBatteryMode is true */
130
+ lowBatteryFraction: 0.15,
131
+ };
132
+
133
+ /** Named exports kept for docs / backward compatibility (= defaults). */
134
+ export const TRIP_START_SAT_WINDOW_MS = DEFAULT_THRESHOLDS.tripStartSatWindowMs;
135
+ export const MIN_SATELLITES_FOR_GOOD_FIX =
136
+ DEFAULT_THRESHOLDS.minSatellitesForGoodFix;
137
+ export const POOR_TRACKING_DURATION_MS =
138
+ DEFAULT_THRESHOLDS.poorTrackingDurationMs;
139
+ export const POOR_ACCURACY_THRESHOLD_M =
140
+ DEFAULT_THRESHOLDS.poorAccuracyThresholdM;
141
+ export const TELEPORT_IMPLIED_SPEED_KMH =
142
+ DEFAULT_THRESHOLDS.teleportImpliedSpeedKmh;
143
+ export const TELEPORT_MIN_JUMP_METERS = DEFAULT_THRESHOLDS.teleportMinJumpMeters;
144
+ export const EXPECTED_TRACE_INTERVAL_MS =
145
+ DEFAULT_THRESHOLDS.expectedTraceIntervalMs;
146
+ export const THROTTLE_GAP_MULTIPLIER = DEFAULT_THRESHOLDS.throttleGapMultiplier;
147
+ export const THROTTLE_MIN_GAP_MS = DEFAULT_THRESHOLDS.throttleMinGapMs;
148
+ export const SYSTEM_CHECK_INTERVAL_MS =
149
+ DEFAULT_THRESHOLDS.systemCheckIntervalMs;
150
+ export const ALERT_COOLDOWN_MS = DEFAULT_THRESHOLDS.alertCooldownMs;
151
+ export const TIME_SKEW_THRESHOLD_MINUTES =
152
+ DEFAULT_THRESHOLDS.timeSkewThresholdMinutes;
153
+
154
+ /** Same event names as the driver-app TrackingQualityMonitor for drop-in listeners. */
155
+ export const EVENT_NAMES = {
156
+ ALERT: "TrackingQualityMonitor:alert",
157
+ GNSS_UPDATE: "TrackingQualityMonitor:gnss",
158
+ STATUS: "TrackingQualityMonitor:status",
159
+ /** Explicit user/system actions for POC live log (start/stop/trip/fitness). */
160
+ ACTION: "TrackingQualityMonitor:action",
161
+ };
@@ -0,0 +1,135 @@
1
+ import { Platform } from "react-native";
2
+ import { DEVICE_FITNESS, GNSS_CAPABILITY_BY_API } from "./constants";
3
+ import { getApiLevelThresholds } from "./config";
4
+
5
+ /**
6
+ * Device fitness = capability + API level + settings only.
7
+ * Do NOT use satellite counts, accuracy, or traces — those are trip warnings.
8
+ */
9
+
10
+ export function getAndroidApiLevel() {
11
+ if (Platform.OS !== "android") {
12
+ return null;
13
+ }
14
+ const level = parseInt(Platform.Version, 10);
15
+ return Number.isFinite(level) ? level : null;
16
+ }
17
+
18
+ export function getGnssCapabilityProfile(apiLevel) {
19
+ const floors = getApiLevelThresholds();
20
+ if (apiLevel == null) {
21
+ return { tier: "unknown", ...GNSS_CAPABILITY_BY_API.unknown };
22
+ }
23
+ if (apiLevel < floors.MIN_LEGACY_GNSS) {
24
+ return { tier: "unsupported", ...GNSS_CAPABILITY_BY_API.unsupported };
25
+ }
26
+ if (apiLevel < floors.MIN_BASIC_GNSS) {
27
+ return { tier: "legacy", ...GNSS_CAPABILITY_BY_API.legacy };
28
+ }
29
+ if (apiLevel < floors.MIN_FULL_GNSS_STATUS) {
30
+ return { tier: "basic", ...GNSS_CAPABILITY_BY_API.basic };
31
+ }
32
+ if (apiLevel < floors.MIN_CARRIER_FREQUENCY) {
33
+ return { tier: "full_status", ...GNSS_CAPABILITY_BY_API.full_status };
34
+ }
35
+ return { tier: "enhanced", ...GNSS_CAPABILITY_BY_API.enhanced };
36
+ }
37
+
38
+ export function scoreApiLevel(apiLevel) {
39
+ const floors = getApiLevelThresholds();
40
+ if (apiLevel == null) {
41
+ return {
42
+ score: DEVICE_FITNESS.UNKNOWN,
43
+ reason: "API level unavailable",
44
+ };
45
+ }
46
+ if (apiLevel < floors.MIN_BASIC_GNSS) {
47
+ return {
48
+ score: DEVICE_FITNESS.UNFIT,
49
+ reason: `API ${apiLevel} < ${floors.MIN_BASIC_GNSS}: insufficient GNSS status APIs`,
50
+ };
51
+ }
52
+ if (apiLevel < floors.MIN_FULL_GNSS_STATUS) {
53
+ return {
54
+ score: DEVICE_FITNESS.WEAK,
55
+ reason: `API ${apiLevel}: basic sat/constellation only (no reliable C/N0 / GnssStatus.Callback)`,
56
+ };
57
+ }
58
+ if (apiLevel < floors.MIN_CARRIER_FREQUENCY) {
59
+ return {
60
+ score: DEVICE_FITNESS.ACCEPTABLE,
61
+ reason: `API ${apiLevel}: full GnssStatus + measurements; no carrier-frequency API`,
62
+ };
63
+ }
64
+ if (apiLevel < floors.MIN_PRECISE_LOCATION_MODEL) {
65
+ return {
66
+ score: DEVICE_FITNESS.GOOD,
67
+ reason: `API ${apiLevel}: carrier frequency available; pre-precise-location permission model`,
68
+ };
69
+ }
70
+ return {
71
+ score: DEVICE_FITNESS.GOOD,
72
+ reason: `API ${apiLevel}: modern GNSS + precise-location / FGS location model`,
73
+ };
74
+ }
75
+
76
+ export function assessDeviceFitness({
77
+ apiLevel = getAndroidApiLevel(),
78
+ systemHealth = null,
79
+ gnssCapabilityFlags = null,
80
+ } = {}) {
81
+ const api = scoreApiLevel(apiLevel);
82
+ const capability = getGnssCapabilityProfile(apiLevel);
83
+ const settingsIssues = [];
84
+
85
+ if (systemHealth) {
86
+ if (systemHealth.batteryOptimizationEnabled) {
87
+ settingsIssues.push("battery_optimization_enabled");
88
+ }
89
+ if (systemHealth.powerSaveMode || systemHealth.lowPowerMode) {
90
+ settingsIssues.push("power_save_or_low_power");
91
+ }
92
+ if (systemHealth.backgroundTrackingRestricted) {
93
+ settingsIssues.push("background_tracking_restricted");
94
+ }
95
+ if (systemHealth.badTimeOrTimezone) {
96
+ settingsIssues.push("bad_time_timezone");
97
+ }
98
+ }
99
+
100
+ if (gnssCapabilityFlags?.isGNSSSupported === false) {
101
+ settingsIssues.push("gnss_not_supported_or_disabled");
102
+ }
103
+
104
+ let score = api.score;
105
+
106
+ if (
107
+ gnssCapabilityFlags?.isGNSSSupported === false ||
108
+ score === DEVICE_FITNESS.UNFIT
109
+ ) {
110
+ score = DEVICE_FITNESS.UNFIT;
111
+ } else if (settingsIssues.length > 0) {
112
+ if (
113
+ score === DEVICE_FITNESS.GOOD ||
114
+ score === DEVICE_FITNESS.ACCEPTABLE
115
+ ) {
116
+ score = DEVICE_FITNESS.RISKY_SETTINGS;
117
+ }
118
+ }
119
+
120
+ return {
121
+ platform: Platform.OS,
122
+ apiLevel,
123
+ apiScore: api.score,
124
+ apiReason: api.reason,
125
+ gnssCapability: capability,
126
+ settingsIssues,
127
+ fitness: score,
128
+ capableForTracking:
129
+ score === DEVICE_FITNESS.GOOD ||
130
+ score === DEVICE_FITNESS.ACCEPTABLE ||
131
+ score === DEVICE_FITNESS.RISKY_SETTINGS,
132
+ thresholds: { ...getApiLevelThresholds() },
133
+ assessedAt: Date.now(),
134
+ };
135
+ }