craft-native 0.0.435 → 0.0.442

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.
Files changed (39) hide show
  1. package/LICENSE.md +30 -0
  2. package/README.md +35 -0
  3. package/dist/android/src/index.d.ts +8 -0
  4. package/dist/android/src/index.js +17 -2
  5. package/dist/android/templates/CraftHealthServices.kt.template +2 -0
  6. package/dist/android/templates/CraftNativeCapabilities.kt.template +42 -1
  7. package/dist/android/templates/CraftNativeMotion.kt.template +269 -0
  8. package/dist/android/templates/CraftNativeServices.kt.template +6 -1
  9. package/dist/android/templates/CraftPassiveSteps.kt.template +159 -0
  10. package/dist/android/templates/CraftRecordingPressure.kt.template +156 -0
  11. package/dist/android/templates/LocationRecordingService.kt.template +77 -9
  12. package/dist/android/templates/MainActivityNative.kt.template +129 -1
  13. package/dist/cli.js +289 -108
  14. package/dist/components/index.d.ts +25 -0
  15. package/dist/index.cjs +207 -27
  16. package/dist/index.d.cts +2 -2
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +321 -140
  19. package/dist/installer-background.d.ts +2 -0
  20. package/dist/installer-layout.d.ts +1 -0
  21. package/dist/ios/src/index.d.ts +10 -0
  22. package/dist/ios/src/index.js +28 -2
  23. package/dist/ios/templates/CraftApp.swift +14 -0
  24. package/dist/ios/templates/CraftHealth.swift +2 -1
  25. package/dist/ios/templates/CraftHealthBackground.swift +308 -0
  26. package/dist/ios/templates/CraftNativeActions.swift +153 -0
  27. package/dist/ios/templates/CraftNativeMutation.swift +18 -3
  28. package/dist/ios/templates/CraftNativePedometer.swift +181 -0
  29. package/dist/ios/templates/CraftNativeScreen.swift +76 -0
  30. package/dist/ios/templates/testing/DriverTests.swift.template +24 -4
  31. package/dist/macos/src/index.js +1 -1
  32. package/dist/macos/src/toolchain.d.ts +1 -1
  33. package/dist/macos/templates/CraftMacApplication.swift +124 -39
  34. package/dist/macos/templates/CraftMacRenderer.swift +169 -37
  35. package/dist/macos/templates/CraftMacRuntime.swift +298 -77
  36. package/dist/macos/templates/CraftNativeMutation.swift +18 -3
  37. package/dist/package.d.ts +40 -0
  38. package/dist/types.d.ts +26 -0
  39. package/package.json +1 -1
@@ -0,0 +1,159 @@
1
+ package {{PACKAGE_NAME}}
2
+
3
+ import android.Manifest
4
+ import android.content.Context
5
+ import android.content.BroadcastReceiver
6
+ import android.content.Intent
7
+ import androidx.work.Worker
8
+ import androidx.work.WorkerParameters
9
+ import androidx.work.WorkManager
10
+ import androidx.work.OneTimeWorkRequestBuilder
11
+ import androidx.work.ExistingWorkPolicy
12
+ import android.content.pm.PackageManager
13
+ import android.os.SystemClock
14
+ import androidx.core.content.ContextCompat
15
+ import androidx.health.services.client.HealthServices
16
+ import androidx.health.services.client.PassiveListenerService
17
+ import androidx.health.services.client.data.DataPointContainer
18
+ import androidx.health.services.client.data.DataType
19
+ import androidx.health.services.client.data.PassiveListenerConfig
20
+ import org.json.JSONArray
21
+ import org.json.JSONObject
22
+ import java.time.Instant
23
+ import java.time.ZoneId
24
+ import java.util.concurrent.TimeUnit
25
+
26
+ /** Daily Health Services totals are not the raw counter since boot. */
27
+ internal class CraftPassiveStepStore(context: Context) {
28
+ private val prefs = context.getSharedPreferences("craft-passive-steps", Context.MODE_PRIVATE)
29
+ companion object { private val lock = Any() }
30
+ fun enabled(): Boolean = synchronized(lock) { prefs.getBoolean("enabled", false) }
31
+ fun setEnabled(value: Boolean): Boolean = synchronized(lock) { prefs.edit().putBoolean("enabled", value).commit() }
32
+ fun history(): JSONArray = synchronized(lock) { JSONArray(prefs.getString("days", "[]")) }
33
+ fun save(steps: Long, start: Long, end: Long, zone: String): Boolean = synchronized(lock) {
34
+ if (!enabled() || steps < 0 || start > end) return@synchronized false
35
+ // Attribute a completed interval ending at midnight to its start day.
36
+ val day = Instant.ofEpochMilli(start).atZone(ZoneId.of(zone)).toLocalDate().toString()
37
+ val rows = history()
38
+ val values = (0 until rows.length()).map { rows.getJSONObject(it) }.toMutableList()
39
+ val previous = values.firstOrNull { it.optString("day") == day && it.optString("timeZone") == zone }
40
+ if (previous != null && previous.optLong("endDate") > end) return@synchronized false
41
+ values.removeAll { it.optString("day") == day && it.optString("timeZone") == zone }
42
+ values.add(JSONObject().put("kind", "daily").put("source", "healthServices").put("day", day).put("timeZone", zone)
43
+ .put("startDate", start).put("endDate", end).put("steps", steps))
44
+ val retained = JSONArray(values.sortedBy { it.getLong("endDate") }.takeLast(8))
45
+ prefs.edit().putString("days", retained.toString()).commit()
46
+ }
47
+ }
48
+
49
+ /** Health Services binds this service even when no Craft screen is alive. */
50
+ class CraftPassiveStepsService : PassiveListenerService() {
51
+ override fun onNewDataPointsReceived(dataPoints: DataPointContainer) {
52
+ val storage = CraftPassiveStepStore(this)
53
+ val boot = Instant.ofEpochMilli(System.currentTimeMillis() - SystemClock.elapsedRealtime())
54
+ for (point in dataPoints.getData(DataType.STEPS_DAILY)) {
55
+ storage.save(point.value, point.getStartInstant(boot).toEpochMilli(), point.getEndInstant(boot).toEpochMilli(), ZoneId.systemDefault().id)
56
+ }
57
+ }
58
+ override fun onPermissionLost() { CraftPassiveStepStore(this).setEnabled(false) }
59
+ }
60
+
61
+ internal interface CraftPassiveStepProvider {
62
+ fun supported(): Boolean
63
+ fun start()
64
+ fun stop()
65
+ fun discardRegistration() { stop() }
66
+ }
67
+
68
+ private class CraftHealthPassiveProvider(context: Context) : CraftPassiveStepProvider {
69
+ private val client = HealthServices.getClient(context).passiveMonitoringClient
70
+ override fun supported(): Boolean = DataType.STEPS_DAILY in client.getCapabilitiesAsync().get(10, TimeUnit.SECONDS).supportedDataTypesPassiveMonitoring
71
+ override fun start() {
72
+ client.setPassiveListenerServiceAsync(CraftPassiveStepsService::class.java,
73
+ PassiveListenerConfig.builder().setDataTypes(setOf(DataType.STEPS_DAILY)).build()).get(10, TimeUnit.SECONDS)
74
+ }
75
+ override fun stop() { client.clearPassiveListenerServiceAsync().get(10, TimeUnit.SECONDS) }
76
+ override fun discardRegistration() { client.clearPassiveListenerServiceAsync() }
77
+ }
78
+
79
+ internal class CraftPassiveSteps(
80
+ private val context: Context,
81
+ private val provider: CraftPassiveStepProvider = CraftHealthPassiveProvider(context),
82
+ private val permission: () -> Boolean = { ContextCompat.checkSelfPermission(context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED },
83
+ ) {
84
+ private val storage = CraftPassiveStepStore(context)
85
+ private fun failure(code: String, message: String) = CraftNativeCapabilityResult(code = code, message = message)
86
+
87
+ fun perform(method: String, done: (CraftNativeCapabilityResult) -> Unit) {
88
+ // These bounded provider calls run on a worker: no main-thread binder wait.
89
+ executor.execute {
90
+ val result = try {
91
+ when (method) {
92
+ "history" -> CraftNativeCapabilityResult(data = storage.history())
93
+ "availability" -> CraftNativeCapabilityResult(data = JSONObject()
94
+ .put("supported", provider.supported())
95
+ .put("enabled", storage.enabled()).put("permissionGranted", permission()))
96
+ "start", "restore" -> {
97
+ if (method == "restore" && !storage.enabled()) CraftNativeCapabilityResult(data = false)
98
+ else if (!permission()) failure("PERMISSION_DENIED", "Activity recognition access is required")
99
+ else if (!provider.supported())
100
+ failure("UNAVAILABLE", "This device has no passive daily steps provider")
101
+ else {
102
+ // Persist intent before binding; the service may receive data immediately.
103
+ if (!storage.setEnabled(true)) failure("STORAGE_ERROR", "Passive registration intent could not be saved")
104
+ else {
105
+ try {
106
+ provider.start()
107
+ CraftNativeCapabilityResult(data = true)
108
+ } catch (error: Exception) {
109
+ if (method == "start") storage.setEnabled(false)
110
+ runCatching { provider.discardRegistration() }
111
+ throw error
112
+ }
113
+ }
114
+ }
115
+ }
116
+ "stop" -> {
117
+ if (!storage.setEnabled(false)) failure("STORAGE_ERROR", "Passive registration intent could not be cleared")
118
+ else {
119
+ provider.stop()
120
+ CraftNativeCapabilityResult(data = true)
121
+ }
122
+ }
123
+ else -> failure("UNKNOWN_ACTION", "Unknown passive pedometer action")
124
+ }
125
+ } catch (error: Exception) {
126
+ failure("UNAVAILABLE", error.cause?.message ?: error.message ?: "Health Services is unavailable")
127
+ }
128
+ ContextCompat.getMainExecutor(context).execute { done(result) }
129
+ }
130
+ }
131
+ companion object {
132
+ // Serialize app-wide start/stop commands, including commands from different routes.
133
+ private val executor = java.util.concurrent.Executors.newSingleThreadExecutor()
134
+ }
135
+ }
136
+
137
+ /** Registrations do not survive a reboot. Restore only explicit saved opt-in. */
138
+ class CraftPassiveStepsBootReceiver : BroadcastReceiver() {
139
+ override fun onReceive(context: Context, intent: Intent) {
140
+ if (intent.action != Intent.ACTION_BOOT_COMPLETED || !CraftPassiveStepStore(context).enabled()) return
141
+ WorkManager.getInstance(context).enqueueUniqueWork("craft-passive-steps-restore", ExistingWorkPolicy.KEEP,
142
+ OneTimeWorkRequestBuilder<CraftPassiveStepsRestoreWorker>().build())
143
+ }
144
+ }
145
+
146
+ class CraftPassiveStepsRestoreWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
147
+ override fun doWork(): Result {
148
+ if (!CraftPassiveStepStore(applicationContext).enabled()) return Result.success()
149
+ val finished = java.util.concurrent.CountDownLatch(1)
150
+ var answer: CraftNativeCapabilityResult? = null
151
+ CraftPassiveSteps(applicationContext).perform("restore") { answer = it; finished.countDown() }
152
+ if (!finished.await(25, TimeUnit.SECONDS)) return Result.retry()
153
+ return when (answer?.code) {
154
+ null -> Result.success()
155
+ "PERMISSION_DENIED" -> { CraftPassiveStepStore(applicationContext).setEnabled(false); Result.failure() }
156
+ else -> if (runAttemptCount < 3) Result.retry() else Result.failure()
157
+ }
158
+ }
159
+ }
@@ -0,0 +1,156 @@
1
+ package com.craft.runtime
2
+
3
+ import android.content.Context
4
+ import android.hardware.Sensor
5
+ import android.hardware.SensorEvent
6
+ import android.hardware.SensorEventListener
7
+ import android.hardware.SensorManager
8
+ import android.os.Handler
9
+ import android.os.Looper
10
+ import android.os.PowerManager
11
+ import org.json.JSONArray
12
+ import org.json.JSONObject
13
+ import java.io.File
14
+ import java.util.UUID
15
+
16
+ /** Native-only journal: JS suspension cannot drop pressure readings from a route. */
17
+ object CraftRecordingPressure {
18
+ private fun file(context: Context, id: String): File {
19
+ val digest = java.security.MessageDigest.getInstance("SHA-256").digest(id.toByteArray(Charsets.UTF_8))
20
+ return File(context.filesDir, "craft-pressure-${digest.joinToString("") { "%02x".format(it) }}.jsonl")
21
+ }
22
+ fun requireAvailable(context: Context) {
23
+ val config = context.assets.open("craft.config.json").bufferedReader().use { JSONObject(it.readText()) }
24
+ if (!config.optBoolean("enableBarometer") || !config.optBoolean("enableBackgroundLocation"))
25
+ throw CraftRecordingException("CAPABILITY_DISABLED", "Recording pressure requires enableBarometer and enableBackgroundLocation")
26
+ val manager = context.getSystemService(SensorManager::class.java)
27
+ if (manager?.getDefaultSensor(Sensor.TYPE_PRESSURE, true) == null && manager?.getDefaultSensor(Sensor.TYPE_PRESSURE) == null)
28
+ throw CraftRecordingException("UNAVAILABLE", "Barometer is not present")
29
+ }
30
+ // Callers also hold the recording-store lock to serialize owner/ACK changes.
31
+ fun append(context: Context, id: String, event: JSONObject) {
32
+ val bytes = (event.put("recordingId", id).toString() + "\n").toByteArray(Charsets.UTF_8)
33
+ java.io.FileOutputStream(file(context, id), true).use { it.write(bytes); it.fd.sync() }
34
+ }
35
+ fun read(context: Context, id: String): JSONArray {
36
+ val result = JSONArray()
37
+ val source = file(context, id)
38
+ if (id.isEmpty() || !source.exists()) return result
39
+ source.forEachLine { line ->
40
+ if (line.isNotBlank()) {
41
+ val event = JSONObject(line)
42
+ check(event.getString("recordingId") == id) { "Invalid pressure recording owner" }
43
+ result.put(event)
44
+ }
45
+ }
46
+ return result
47
+ }
48
+ fun delete(context: Context, id: String) {
49
+ val source = file(context, id)
50
+ if (source.exists() && !source.delete()) throw CraftRecordingException("RECORDING_STORAGE_ERROR", "Unable to remove acknowledged pressure recording")
51
+ }
52
+ }
53
+
54
+ internal interface CraftRecordingPressureSource {
55
+ fun open(sample: (Float, Long) -> Unit): AutoCloseable
56
+ }
57
+
58
+ private class AndroidRecordingPressureSource(private val context: Context) : CraftRecordingPressureSource {
59
+ override fun open(sample: (Float, Long) -> Unit): AutoCloseable {
60
+ CraftRecordingPressure.requireAvailable(context)
61
+ val manager = context.getSystemService(SensorManager::class.java)
62
+ ?: throw IllegalStateException("Sensor manager unavailable")
63
+ val sensor = manager.getDefaultSensor(Sensor.TYPE_PRESSURE, true)
64
+ ?: manager.getDefaultSensor(Sensor.TYPE_PRESSURE)
65
+ ?: throw IllegalStateException("Barometer unavailable")
66
+ // A non-wake-up sensor cannot deliver continuously during CPU suspend.
67
+ // Only the explicitly requested, unpaused foreground recording owns this lock.
68
+ val wake = if (!sensor.isWakeUpSensor) context.getSystemService(PowerManager::class.java)
69
+ .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "craft:recording-pressure").apply { setReferenceCounted(false) } else null
70
+ val listener = object : SensorEventListener {
71
+ override fun onSensorChanged(event: SensorEvent) { sample(event.values.firstOrNull() ?: Float.NaN, event.timestamp) }
72
+ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
73
+ }
74
+ try {
75
+ wake?.acquire()
76
+ check(manager.registerListener(listener, sensor, 1_000_000, Handler(Looper.getMainLooper()))) { "Pressure registration rejected" }
77
+ } catch (error: Exception) {
78
+ manager.unregisterListener(listener)
79
+ if (wake?.isHeld == true) wake.release()
80
+ throw error
81
+ }
82
+ return AutoCloseable {
83
+ try { manager.unregisterListener(listener) }
84
+ finally { if (wake?.isHeld == true) wake.release() }
85
+ }
86
+ }
87
+ }
88
+
89
+ /** One service-owned segment, independent of native screen and WebView lifetimes. */
90
+ internal class CraftRecordingPressureSession(
91
+ private val context: Context,
92
+ val id: String,
93
+ private val source: CraftRecordingPressureSource = AndroidRecordingPressureSource(context),
94
+ ) {
95
+ val epoch = CraftLocationRecordingStore.pressureEpoch
96
+ private var registration: AutoCloseable? = null
97
+ private var closed = false
98
+ private var started = false
99
+ private var reference: Float? = null
100
+ private var lastTimestamp: Long? = null
101
+ private var segment = UUID.randomUUID().toString()
102
+
103
+ private fun ownsRecording() = epoch == CraftLocationRecordingStore.pressureEpoch && CraftLocationRecordingStore.recordingId(context) == id &&
104
+ CraftLocationRecordingStore.isActive(context) && !CraftLocationRecordingStore.isPaused(context) &&
105
+ CraftLocationRecordingStore.pressureEnabled(context)
106
+
107
+ fun start() = synchronized(CraftLocationRecordingStore) {
108
+ if (closed || started || !ownsRecording()) return@synchronized
109
+ started = true
110
+ try {
111
+ write(JSONObject().put("state", "segment").put("reason", "startedOrRecovered"))
112
+ val acquired = source.open(::sample)
113
+ if (closed) acquired.close() else registration = acquired
114
+ } catch (error: Exception) { fail(error) }
115
+ }
116
+
117
+ private fun write(event: JSONObject) {
118
+ CraftRecordingPressure.append(context, id, event.put("segmentId", segment).put("timestamp", System.currentTimeMillis()))
119
+ }
120
+
121
+ private fun sample(pressure: Float, timestamp: Long) = synchronized(CraftLocationRecordingStore) {
122
+ if (closed || !ownsRecording()) return@synchronized
123
+ try {
124
+ require(pressure.isFinite() && pressure > 0 && timestamp >= 0) { "Invalid pressure sample" }
125
+ val previous = lastTimestamp
126
+ if (previous != null && timestamp <= previous) return@synchronized
127
+ if (previous != null && timestamp - previous < 1_000_000_000L) return@synchronized
128
+ if (previous != null && timestamp - previous > 3_000_000_000L) {
129
+ segment = UUID.randomUUID().toString()
130
+ reference = null
131
+ write(JSONObject().put("state", "segment").put("reason", "sampleGap").put("timestampMs", timestamp / 1_000_000.0))
132
+ }
133
+ val baseline = reference ?: pressure.also { reference = it }
134
+ val altitude = SensorManager.getAltitude(baseline, pressure)
135
+ require(altitude.isFinite()) { "Invalid pressure altitude" }
136
+ write(JSONObject().put("state", "sample").put("pressureHpa", pressure)
137
+ .put("referencePressureHpa", baseline).put("relativeAltitudeMeters", altitude)
138
+ .put("timestampMs", timestamp / 1_000_000.0))
139
+ lastTimestamp = timestamp
140
+ } catch (error: Exception) { fail(error) }
141
+ }
142
+
143
+ private fun fail(error: Exception) {
144
+ close()
145
+ runCatching { write(JSONObject().put("state", "stopped").put("reason", "sensorOrStorageError")) }
146
+ CraftLocationRecordingStore.failPressure(context, id, error.message ?: "Pressure recording failed")
147
+ }
148
+
149
+ fun close() {
150
+ if (closed) return
151
+ closed = true
152
+ runCatching { registration?.close() }
153
+ .onFailure { android.util.Log.e("CraftLocation", "Unable to unregister pressure listener", it) }
154
+ registration = null
155
+ }
156
+ }
@@ -110,20 +110,21 @@ object CraftLocationRecordingStore {
110
110
  if (!acknowledged(context, id)) return
111
111
  val saved = archive(context, id)
112
112
  if (saved.exists() && !saved.delete()) throw CraftRecordingException("RECORDING_STORAGE_ERROR", "Unable to remove acknowledged recording")
113
+ CraftRecordingPressure.delete(context, id)
113
114
  if (file(context).exists() && !file(context).delete()) throw CraftRecordingException("RECORDING_STORAGE_ERROR", "Unable to remove acknowledged samples")
114
- edit(context) { it.remove("id").remove("startedAt").putBoolean("active", false).putBoolean("paused", false) }
115
+ edit(context) { it.remove("id").remove("startedAt").remove("barometer").remove("barometerError").putBoolean("active", false).putBoolean("paused", false) }
115
116
  listener = null
116
117
  }
117
118
 
118
119
  @Synchronized
119
- fun start(context: Context, id: String, startedAt: Long, powerMode: String = "default") {
120
+ fun start(context: Context, id: String, startedAt: Long, powerMode: String = "default", barometer: Boolean = false) {
120
121
  recover(context)
121
122
  if (isActive(context)) throw CraftRecordingException("RECORDING_ALREADY_ACTIVE", "A location recording is already active")
122
123
  if (id == recordingId(context) || archive(context, id).exists() || acknowledged(context, id))
123
124
  throw CraftRecordingException("RECORDING_CONFLICT", "Recording IDs cannot be reused")
124
125
  archiveCompleted(context)
125
126
  file(context).writeText("")
126
- edit(context) { it.putString("id", id).putBoolean("active", true).putBoolean("paused", false).putLong("startedAt", startedAt).putString("powerMode", powerMode).remove("powerSaver") }
127
+ edit(context) { it.putString("id", id).putBoolean("barometer", barometer).remove("barometerError").putBoolean("active", true).putBoolean("paused", false).putLong("startedAt", startedAt).putString("powerMode", powerMode).remove("powerSaver") }
127
128
  }
128
129
 
129
130
  private val POWER_MODES = setOf("default", "saver", "auto")
@@ -187,7 +188,10 @@ object CraftLocationRecordingStore {
187
188
  fun updatePause(context: Context, paused: Boolean, options: JSONObject?): JSONObject {
188
189
  requireOwner(context, options)
189
190
  if (!isActive(context)) throw CraftRecordingException("NO_ACTIVE_RECORDING", "No active location recording")
191
+ if (paused && !isPaused(context)) pressureEvent(context, "paused")
190
192
  commit(context, true, paused)
193
+ pressureEpoch += 1
194
+ changed?.invoke()
191
195
  return state(context)
192
196
  }
193
197
  @Synchronized fun setPaused(context: Context, paused: Boolean) { updatePause(context, paused, null) }
@@ -196,8 +200,10 @@ object CraftLocationRecordingStore {
196
200
  fun finish(context: Context, options: JSONObject?): JSONObject {
197
201
  completed(context, expected(options))?.let { return it }
198
202
  requireOwner(context, options)
203
+ if (isActive(context)) pressureEvent(context, "stopped")
199
204
  val stopped = state(context, includeLocations = true)
200
205
  commit(context, false, false)
206
+ changed?.invoke()
201
207
  listener = null
202
208
  return stopped.put("active", false).put("paused", false).put("effectivePowerMode", "default")
203
209
  }
@@ -213,9 +219,10 @@ object CraftLocationRecordingStore {
213
219
  val marker = File(saved.path.replace("-completed-", "-ack-"))
214
220
  if (!marker.exists()) writeAtomic(marker, id)
215
221
  if (saved.exists() && !saved.delete()) throw CraftRecordingException("RECORDING_STORAGE_ERROR", "Unable to remove completed recording")
222
+ CraftRecordingPressure.delete(context, id)
216
223
  if (current) {
217
224
  if (file(context).exists() && !file(context).delete()) throw CraftRecordingException("RECORDING_STORAGE_ERROR", "Unable to remove recording samples")
218
- edit(context) { it.remove("id").remove("startedAt").putBoolean("active", false).putBoolean("paused", false) }
225
+ edit(context) { it.remove("id").remove("startedAt").remove("barometer").remove("barometerError").putBoolean("active", false).putBoolean("paused", false) }
219
226
  listener = null
220
227
  }
221
228
  return true
@@ -236,7 +243,11 @@ object CraftLocationRecordingStore {
236
243
  if (requested !is String || requested.isBlank()) throw CraftRecordingException("INVALID_ARGUMENT", "recordingId must be a nonempty recording ID")
237
244
  requested
238
245
  } else java.util.UUID.randomUUID().toString()
239
- start(context, id, System.currentTimeMillis(), requestedPowerMode(options, "default"))
246
+ if (options.has("barometer") && options.opt("barometer") !is Boolean)
247
+ throw CraftRecordingException("INVALID_ARGUMENT", "barometer must be boolean")
248
+ val pressure = options.optBoolean("barometer", false)
249
+ if (pressure) CraftRecordingPressure.requireAvailable(context)
250
+ start(context, id, System.currentTimeMillis(), requestedPowerMode(options, "default"), pressure)
240
251
  try { ContextCompat.startForegroundService(context, Intent(context, LocationRecordingService::class.java).setAction(LocationRecordingService.ACTION_START).putExtra("recordingId", id)) }
241
252
  catch (error: Exception) { finish(context, JSONObject().put("expectedId", id)); throw error }
242
253
  state(context)
@@ -267,7 +278,16 @@ object CraftLocationRecordingStore {
267
278
  context.startService(Intent(context, LocationRecordingService::class.java).setAction(LocationRecordingService.ACTION_STOP).putExtra("recordingId", stopped.optString("id")))
268
279
  stopped
269
280
  }
270
- "getRecordingState" -> state(context, options = options)
281
+ "getRecordingState" -> {
282
+ if (options.has("includeBarometerSamples") && options.opt("includeBarometerSamples") !is Boolean)
283
+ throw CraftRecordingException("INVALID_ARGUMENT", "includeBarometerSamples must be boolean")
284
+ state(context, options = options).also { result ->
285
+ if (options.optBoolean("includeBarometerSamples")) {
286
+ val id = result.optString("id")
287
+ result.put("barometerEvents", CraftRecordingPressure.read(context, id))
288
+ }
289
+ }
290
+ }
271
291
  "readRecording" -> read(context, options)
272
292
  "acknowledgeRecording" -> acknowledge(context, options)
273
293
  else -> throw CraftRecordingException("UNKNOWN_ACTION", "Unsupported Location method")
@@ -281,6 +301,19 @@ object CraftLocationRecordingStore {
281
301
  @Synchronized fun isActive(context: Context) = prefs(context).getBoolean("active", false)
282
302
  @Synchronized fun isPaused(context: Context) = prefs(context).getBoolean("paused", false)
283
303
  @Synchronized fun recordingId(context: Context): String? = prefs(context).getString("id", null)
304
+ @Volatile internal var pressureEpoch = 0L
305
+ @Volatile internal var changed: (() -> Unit)? = null
306
+ @Synchronized internal fun pressureEnabled(context: Context) = prefs(context).getBoolean("barometer", false)
307
+ @Synchronized internal fun failPressure(context: Context, id: String, message: String) {
308
+ if (recordingId(context) != id || !isActive(context)) return
309
+ edit(context) { it.putBoolean("active", false).putBoolean("paused", false).putString("barometerError", message) }
310
+ changed?.invoke()
311
+ }
312
+ private fun pressureEvent(context: Context, reason: String) {
313
+ val id = recordingId(context) ?: return
314
+ if (pressureEnabled(context)) CraftRecordingPressure.append(context, id,
315
+ JSONObject().put("state", "stopped").put("reason", reason).put("timestamp", System.currentTimeMillis()))
316
+ }
284
317
  @Volatile var listener: ((android.location.Location, String) -> Unit)? = null
285
318
  @Volatile var nativeListener: ((android.location.Location, String) -> Unit)? = null
286
319
 
@@ -329,7 +362,7 @@ object CraftLocationRecordingStore {
329
362
  @Synchronized
330
363
  fun state(context: Context, includeLocations: Boolean = false, options: JSONObject? = null): JSONObject {
331
364
  completed(context, expected(options))?.let {
332
- if (!includeLocations) it.remove("locations")
365
+ if (!includeLocations) { it.remove("locations"); it.remove("barometerEvents") }
333
366
  return it
334
367
  }
335
368
  requireOwner(context, options)
@@ -343,7 +376,12 @@ object CraftLocationRecordingStore {
343
376
  put("sampleCount", locations.length())
344
377
  put("powerMode", powerMode(context))
345
378
  put("effectivePowerMode", if (isPowerSaver(context)) "saver" else "default")
346
- if (includeLocations) put("locations", locations)
379
+ put("barometer", pressureEnabled(context))
380
+ values.getString("barometerError", null)?.let { put("barometerError", it) }
381
+ if (includeLocations) {
382
+ put("locations", locations)
383
+ if (pressureEnabled(context)) put("barometerEvents", CraftRecordingPressure.read(context, recordingId(context) ?: ""))
384
+ }
347
385
  }
348
386
  }
349
387
  }
@@ -355,9 +393,33 @@ class LocationRecordingService : Service() {
355
393
  private var callbackSaver = false
356
394
  private var serviceStartId = 0
357
395
  private var powerReceiver: BroadcastReceiver? = null
396
+ private var pressure: CraftRecordingPressureSession? = null
397
+ private val mainHandler = android.os.Handler(Looper.getMainLooper())
398
+ private val pressureChanged: () -> Unit = {
399
+ mainHandler.post {
400
+ if (!CraftLocationRecordingStore.isActive(this)) { stopUpdates(); stopSelfResult(serviceStartId) }
401
+ else syncPressure()
402
+ }
403
+ Unit
404
+ }
405
+
406
+ private fun syncPressure() = synchronized(CraftLocationRecordingStore) {
407
+ val id = CraftLocationRecordingStore.recordingId(this)
408
+ val wanted = id != null && CraftLocationRecordingStore.isActive(this) &&
409
+ !CraftLocationRecordingStore.isPaused(this) && CraftLocationRecordingStore.pressureEnabled(this)
410
+ if (wanted && pressure?.id == id && pressure?.epoch == CraftLocationRecordingStore.pressureEpoch) return@synchronized
411
+ pressure?.close()
412
+ pressure = null
413
+ if (wanted) {
414
+ val next = CraftRecordingPressureSession(this, id!!)
415
+ pressure = next
416
+ next.start()
417
+ }
418
+ }
358
419
 
359
420
  override fun onCreate() {
360
421
  super.onCreate()
422
+ CraftLocationRecordingStore.changed = pressureChanged
361
423
  val manager = getSystemService(NotificationManager::class.java)
362
424
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
363
425
  manager.createNotificationChannel(NotificationChannel(CHANNEL, "Activity recording", NotificationManager.IMPORTANCE_LOW))
@@ -417,6 +479,7 @@ class LocationRecordingService : Service() {
417
479
  val saver = CraftLocationRecordingStore.isPowerSaver(this)
418
480
  if (callback != null && callbackRecordingId == id && callbackSaver == saver) {
419
481
  syncPowerReceiver()
482
+ syncPressure()
420
483
  return true
421
484
  }
422
485
  stopUpdates()
@@ -446,6 +509,7 @@ class LocationRecordingService : Service() {
446
509
  callbackRecordingId = id
447
510
  callbackSaver = saver
448
511
  syncPowerReceiver()
512
+ syncPressure()
449
513
  return try {
450
514
  client.requestLocationUpdates(request, nextCallback, Looper.getMainLooper())
451
515
  .addOnFailureListener {
@@ -460,13 +524,15 @@ class LocationRecordingService : Service() {
460
524
  }
461
525
  true
462
526
  } catch (error: Exception) {
463
- callback = null
527
+ stopUpdates()
464
528
  runCatching { CraftLocationRecordingStore.finish(this, JSONObject().put("expectedId", id)) }
465
529
  false
466
530
  }
467
531
  }
468
532
 
469
533
  private fun stopUpdates() {
534
+ pressure?.close()
535
+ pressure = null
470
536
  callback?.let { client.removeLocationUpdates(it) }
471
537
  callback = null
472
538
  callbackRecordingId = null
@@ -504,6 +570,8 @@ class LocationRecordingService : Service() {
504
570
  }
505
571
 
506
572
  override fun onDestroy() {
573
+ if (CraftLocationRecordingStore.changed === pressureChanged) CraftLocationRecordingStore.changed = null
574
+ mainHandler.removeCallbacksAndMessages(null)
507
575
  stopUpdates()
508
576
  super.onDestroy()
509
577
  }