@blotch/angular-lynx-native 22.3.0 → 22.3.2
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.md +41 -15
- package/dist/android/project.d.ts +90 -1
- package/dist/android/project.d.ts.map +1 -1
- package/dist/android/project.js +369 -5
- package/dist/eject.d.ts +15 -1
- package/dist/eject.d.ts.map +1 -1
- package/dist/eject.js +13 -2
- package/dist/features.d.ts +70 -0
- package/dist/features.d.ts.map +1 -0
- package/dist/features.js +115 -0
- package/dist/generate.d.ts +17 -1
- package/dist/generate.d.ts.map +1 -1
- package/dist/generate.js +12 -4
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/ios/build.d.ts.map +1 -1
- package/dist/ios/build.js +8 -2
- package/dist/ios/frameworks.d.ts +6 -5
- package/dist/ios/frameworks.d.ts.map +1 -1
- package/dist/ios/frameworks.js +46 -15
- package/dist/ios/project.d.ts +173 -11
- package/dist/ios/project.d.ts.map +1 -1
- package/dist/ios/project.js +767 -33
- package/dist/options.d.ts +143 -2
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +127 -0
- package/dist/permissions.d.ts +18 -1
- package/dist/permissions.d.ts.map +1 -1
- package/dist/permissions.js +63 -3
- package/package.json +1 -1
- package/templates/android/README.md +37 -2
- package/templates/android/angular-lynx.properties +2 -0
- package/templates/android/app/build.gradle.kts +70 -1
- package/templates/android/app/src/main/AndroidManifest.xml +24 -3
- package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
- package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +376 -6
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +25 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +168 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +6 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +47 -3
- package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
- package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
- package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
- package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
- package/templates/android/app/src/main/res/values/share_target.xml +11 -0
- package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
- package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
- package/templates/android/build.gradle.kts +1 -1
- package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
- package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
- package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
- package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
- package/templates/ios/App/AngularLynxVideo.h +37 -0
- package/templates/ios/App/AngularLynxVideo.m +435 -0
- package/templates/ios/App/AngularLynxWebGL.h +69 -7
- package/templates/ios/App/AngularLynxWebGL.m +538 -29
- package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
- package/templates/ios/App/AppDelegate.swift +34 -2
- package/templates/ios/App/AppleSignInButton.swift +106 -0
- package/templates/ios/App/AppleSignInModule.swift +222 -0
- package/templates/ios/App/BarcodeScannerModule.swift +284 -0
- package/templates/ios/App/BiometricsModule.swift +256 -0
- package/templates/ios/App/BluetoothModule.swift +1086 -0
- package/templates/ios/App/CalendarModule.swift +158 -0
- package/templates/ios/App/FilePickerModule.swift +240 -0
- package/templates/ios/App/HapticsModule.swift +90 -0
- package/templates/ios/App/Info.plist +2 -0
- package/templates/ios/App/LynxViewController.swift +210 -6
- package/templates/ios/App/MotionModule.swift +430 -0
- package/templates/ios/App/NfcModule.swift +346 -0
- package/templates/ios/App/PhotoLibraryModule.swift +169 -0
- package/templates/ios/App/ShareTargetModule.swift +150 -0
- package/templates/ios/App/ShellModule.swift +17 -0
- package/templates/ios/App/StoreReviewModule.swift +61 -0
- package/templates/ios/App/TrackingModule.swift +121 -0
- package/templates/ios/App/WifiModule.swift +237 -0
- package/templates/ios/App/XElementRegistry.swift +13 -3
- package/templates/ios/ShareExtension/Info.plist +42 -0
- package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import CoreLocation
|
|
2
|
+
import CoreMotion
|
|
3
|
+
import Lynx
|
|
4
|
+
import UIKit
|
|
5
|
+
|
|
6
|
+
/// The native module behind the runtime's `LynxMotion`, which calls it as
|
|
7
|
+
/// `NativeModules.AngularLynxMotion` (from the background thread, where
|
|
8
|
+
/// NativeModules lives).
|
|
9
|
+
///
|
|
10
|
+
/// `start(sensor, interval)` runs a sensor, sampling every `interval`
|
|
11
|
+
/// milliseconds, or changes how often; `stop(sensor)` stops it; and
|
|
12
|
+
/// `availability` calls back with which sensors the phone has. The sensors
|
|
13
|
+
/// are `acceleration` (the accelerometer, in m/s² with gravity), `rotation`
|
|
14
|
+
/// (Core Motion's device motion rotation rate, in rad/s), `orientation`
|
|
15
|
+
/// (device motion's attitude, as a rotation matrix), `heading`
|
|
16
|
+
/// (`CLLocationManager`'s heading, which asks for no location permission)
|
|
17
|
+
/// and `shake`, which this module hears from the accelerometer itself, so a
|
|
18
|
+
/// shake costs the runtime one event rather than 50 samples a second.
|
|
19
|
+
///
|
|
20
|
+
/// The samples go to the runtime in the `angularLynxMotion` global event,
|
|
21
|
+
/// one object with a flat array of numbers for each sensor that sampled
|
|
22
|
+
/// (see `MotionBatch` in the runtime's motion.ts), at most once every 16 ms:
|
|
23
|
+
/// each event is work for Lynx's engine thread, where Angular runs. The
|
|
24
|
+
/// sensors stop while the app is in the background, and start again when it
|
|
25
|
+
/// comes back.
|
|
26
|
+
///
|
|
27
|
+
/// The generator leaves this file out of an app whose angular.json doesn't
|
|
28
|
+
/// set `motion`, and LynxViewController registers the module by its
|
|
29
|
+
/// Objective-C name only when it's there, hence the `@objc` name.
|
|
30
|
+
@objc(AngularLynxMotionModule)
|
|
31
|
+
final class MotionModule: NSObject, LynxContextModule, CLLocationManagerDelegate {
|
|
32
|
+
static var name: String { "AngularLynxMotion" }
|
|
33
|
+
|
|
34
|
+
static var methodLookup: [String: String] {
|
|
35
|
+
[
|
|
36
|
+
"start": NSStringFromSelector(#selector(start(_:interval:))),
|
|
37
|
+
"stop": NSStringFromSelector(#selector(stop(_:))),
|
|
38
|
+
"availability": NSStringFromSelector(#selector(availability(_:))),
|
|
39
|
+
]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
static let event = "angularLynxMotion"
|
|
43
|
+
/// The least time between events, about a frame.
|
|
44
|
+
private static let flushInterval = 0.016
|
|
45
|
+
/// How often the accelerometer samples for shakes: the runtime's
|
|
46
|
+
/// `SHAKE.intervalMs`.
|
|
47
|
+
private static let shakeInterval = 0.02
|
|
48
|
+
|
|
49
|
+
private weak var context: LynxContext?
|
|
50
|
+
/// Everything below belongs to this queue, and the sensors' handlers run
|
|
51
|
+
/// on it. Lynx calls modules on threads of its own.
|
|
52
|
+
private let queue = DispatchQueue(label: "dev.angularlynx.motion")
|
|
53
|
+
private lazy var handlers: OperationQueue = {
|
|
54
|
+
let operations = OperationQueue()
|
|
55
|
+
operations.underlyingQueue = queue
|
|
56
|
+
operations.maxConcurrentOperationCount = 1
|
|
57
|
+
return operations
|
|
58
|
+
}()
|
|
59
|
+
private let manager = CMMotionManager()
|
|
60
|
+
/// Made, started and stopped on the main thread, which its delegate
|
|
61
|
+
/// methods are called on.
|
|
62
|
+
private var locationManager: CLLocationManager?
|
|
63
|
+
/// The interval each running sensor was started at, in seconds.
|
|
64
|
+
private var requested: [String: TimeInterval] = [:]
|
|
65
|
+
/// The intervals the hardware runs at now, to restart it only on a change.
|
|
66
|
+
private var accelerometerInterval: TimeInterval?
|
|
67
|
+
private var deviceMotionInterval: TimeInterval?
|
|
68
|
+
private var headingOn = false
|
|
69
|
+
/// When each sensor's last sample was kept, in milliseconds.
|
|
70
|
+
private var lastSample: [String: Double] = [:]
|
|
71
|
+
private var batch: [String: [Double]] = [:]
|
|
72
|
+
private var flushScheduled = false
|
|
73
|
+
private var lastFlush: TimeInterval = 0
|
|
74
|
+
private var inBackground = false
|
|
75
|
+
private var shakes = ShakeDetector()
|
|
76
|
+
/// Turns the uptime Core Motion stamps its samples with into milliseconds
|
|
77
|
+
/// since the epoch.
|
|
78
|
+
private let clock = MotionClock()
|
|
79
|
+
private var observers: [NSObjectProtocol] = []
|
|
80
|
+
|
|
81
|
+
override init() {
|
|
82
|
+
super.init()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Swift can't import an optional initializer as optional, so Lynx's
|
|
86
|
+
// initWithParam: and initWithLynxContext:WithParam: are required here.
|
|
87
|
+
init(param: Any) {
|
|
88
|
+
super.init()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
init(lynxContext context: LynxContext) {
|
|
92
|
+
self.context = context
|
|
93
|
+
super.init()
|
|
94
|
+
observeAppState()
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
init(lynxContext context: LynxContext, withParam param: Any) {
|
|
98
|
+
self.context = context
|
|
99
|
+
super.init()
|
|
100
|
+
observeAppState()
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
deinit {
|
|
104
|
+
observers.forEach { NotificationCenter.default.removeObserver($0) }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/// The LynxView is going: nothing should keep the sensors on for it.
|
|
108
|
+
func destroy() {
|
|
109
|
+
queue.async {
|
|
110
|
+
self.requested.removeAll()
|
|
111
|
+
self.apply()
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
@objc func start(_ sensor: String, interval: Double) {
|
|
116
|
+
queue.async {
|
|
117
|
+
// At least 5 ms, as the runtime asks: Core Motion's rates top out
|
|
118
|
+
// near 100 Hz on most iPhones anyway.
|
|
119
|
+
self.requested[sensor] = max(interval, 5) / 1000
|
|
120
|
+
self.apply()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
@objc func stop(_ sensor: String) {
|
|
125
|
+
queue.async {
|
|
126
|
+
self.requested.removeValue(forKey: sensor)
|
|
127
|
+
self.lastSample.removeValue(forKey: sensor)
|
|
128
|
+
// Samples still waiting for the next event were for the watches that
|
|
129
|
+
// just stopped: a shake heard before a new listener came mustn't reach
|
|
130
|
+
// it.
|
|
131
|
+
self.batch.removeValue(forKey: sensor)
|
|
132
|
+
// A shake begun for the last listener can't be finished for the next.
|
|
133
|
+
if sensor == "shake" { self.shakes = ShakeDetector() }
|
|
134
|
+
self.apply()
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// Calls back with which sensors the phone has. The Simulator has none.
|
|
139
|
+
@objc func availability(_ callback: @escaping LynxCallbackBlock) {
|
|
140
|
+
callback([
|
|
141
|
+
"acceleration": manager.isAccelerometerAvailable,
|
|
142
|
+
"rotation": manager.isGyroAvailable && manager.isDeviceMotionAvailable,
|
|
143
|
+
"orientation": manager.isDeviceMotionAvailable,
|
|
144
|
+
"heading": CLLocationManager.headingAvailable(),
|
|
145
|
+
])
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/// Stops the sensors while the app is in the background, where Lynx
|
|
149
|
+
/// pauses the runtime and nobody sees what they'd measure.
|
|
150
|
+
private func observeAppState() {
|
|
151
|
+
let center = NotificationCenter.default
|
|
152
|
+
observers = [
|
|
153
|
+
center.addObserver(
|
|
154
|
+
forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil
|
|
155
|
+
) { [weak self] _ in
|
|
156
|
+
self?.queue.async {
|
|
157
|
+
self?.inBackground = true
|
|
158
|
+
// Samples from before the app left aren't sent after it, and
|
|
159
|
+
// aren't half of a shake with one after it either.
|
|
160
|
+
self?.batch.removeAll()
|
|
161
|
+
self?.shakes = ShakeDetector()
|
|
162
|
+
self?.apply()
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
center.addObserver(
|
|
166
|
+
forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil
|
|
167
|
+
) { [weak self] _ in
|
|
168
|
+
self?.queue.async {
|
|
169
|
+
self?.inBackground = false
|
|
170
|
+
self?.apply()
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
]
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/// Runs each piece of hardware at the shortest interval anything asks of
|
|
177
|
+
/// it, or stops it. On the queue.
|
|
178
|
+
private func apply() {
|
|
179
|
+
let wanted = inBackground ? [:] : requested
|
|
180
|
+
|
|
181
|
+
// The accelerometer serves the acceleration and the shakes.
|
|
182
|
+
var accelerometer = wanted["acceleration"]
|
|
183
|
+
if wanted["shake"] != nil {
|
|
184
|
+
accelerometer = min(accelerometer ?? Self.shakeInterval, Self.shakeInterval)
|
|
185
|
+
}
|
|
186
|
+
if accelerometer != accelerometerInterval {
|
|
187
|
+
manager.stopAccelerometerUpdates()
|
|
188
|
+
accelerometerInterval = accelerometer
|
|
189
|
+
if let interval = accelerometer, manager.isAccelerometerAvailable {
|
|
190
|
+
manager.accelerometerUpdateInterval = interval
|
|
191
|
+
manager.startAccelerometerUpdates(to: handlers) { [weak self] data, _ in
|
|
192
|
+
if let data { self?.accelerometer(data) }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Device motion, which fuses the accelerometer and the gyroscope, serves
|
|
198
|
+
// the rotation rate (without the gyroscope's drift) and the attitude.
|
|
199
|
+
// Its yaw counts from where the phone faced when it started, without the
|
|
200
|
+
// magnetometer, as Android's game rotation vector does.
|
|
201
|
+
let motion = [wanted["rotation"], wanted["orientation"]].compactMap { $0 }.min()
|
|
202
|
+
if let interval = motion, deviceMotionInterval != nil, manager.isDeviceMotionActive {
|
|
203
|
+
// Already running: only the rate changes. A restart would take the
|
|
204
|
+
// phone's heading now as the new zero of .xArbitraryZVertical, and a
|
|
205
|
+
// watch of the orientation would see alpha jump when another watch
|
|
206
|
+
// starts or stops.
|
|
207
|
+
if interval != deviceMotionInterval {
|
|
208
|
+
manager.deviceMotionUpdateInterval = interval
|
|
209
|
+
deviceMotionInterval = interval
|
|
210
|
+
}
|
|
211
|
+
} else if motion != deviceMotionInterval {
|
|
212
|
+
manager.stopDeviceMotionUpdates()
|
|
213
|
+
deviceMotionInterval = motion
|
|
214
|
+
if let interval = motion, manager.isDeviceMotionAvailable {
|
|
215
|
+
manager.deviceMotionUpdateInterval = interval
|
|
216
|
+
manager.startDeviceMotionUpdates(using: .xArbitraryZVertical, to: handlers) {
|
|
217
|
+
[weak self] data, _ in
|
|
218
|
+
if let data { self?.deviceMotion(data) }
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let heading = wanted["heading"] != nil
|
|
224
|
+
if heading != headingOn {
|
|
225
|
+
headingOn = heading
|
|
226
|
+
DispatchQueue.main.async { self.setHeading(on: heading) }
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/// On the main thread, where CLLocationManager wants to be made and calls
|
|
231
|
+
/// its delegate.
|
|
232
|
+
private func setHeading(on: Bool) {
|
|
233
|
+
guard CLLocationManager.headingAvailable() else { return }
|
|
234
|
+
if on {
|
|
235
|
+
let manager = locationManager ?? CLLocationManager()
|
|
236
|
+
manager.delegate = self
|
|
237
|
+
// A new heading for each degree it turns: the runtime throttles to the
|
|
238
|
+
// watch's interval, and a phone held still reports nothing.
|
|
239
|
+
manager.headingFilter = 1
|
|
240
|
+
locationManager = manager
|
|
241
|
+
manager.startUpdatingHeading()
|
|
242
|
+
} else {
|
|
243
|
+
locationManager?.stopUpdatingHeading()
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
|
|
248
|
+
// A negative accuracy means iOS has no heading at all, not one of
|
|
249
|
+
// unknown accuracy.
|
|
250
|
+
guard newHeading.headingAccuracy >= 0 else { return }
|
|
251
|
+
let t = clock.milliseconds(ProcessInfo.processInfo.systemUptime)
|
|
252
|
+
let magnetic = newHeading.magneticHeading
|
|
253
|
+
// Negative when iOS doesn't know: true north needs the location, which
|
|
254
|
+
// the app may not have access to.
|
|
255
|
+
let trueHeading = newHeading.trueHeading >= 0 ? newHeading.trueHeading : -1
|
|
256
|
+
let accuracy = newHeading.headingAccuracy
|
|
257
|
+
queue.async {
|
|
258
|
+
// One that came as the app went to the background, before the
|
|
259
|
+
// heading stopped.
|
|
260
|
+
guard !self.inBackground, self.keep("heading", at: t) else { return }
|
|
261
|
+
self.add("heading", [t, magnetic, trueHeading, accuracy])
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private func accelerometer(_ data: CMAccelerometerData) {
|
|
266
|
+
// One Core Motion queued before the app went to the background and the
|
|
267
|
+
// accelerometer stopped, as the heading's delegate skips.
|
|
268
|
+
guard !inBackground else { return }
|
|
269
|
+
let t = clock.milliseconds(data.timestamp)
|
|
270
|
+
// Core Motion measures in g, and as the force on the phone: a phone
|
|
271
|
+
// lying face up reads z = -1. The web and Android give the acceleration
|
|
272
|
+
// in m/s² the other way round, z = 9.81, so the runtime gets the same on
|
|
273
|
+
// both.
|
|
274
|
+
let g = -9.80665
|
|
275
|
+
let (x, y, z) = (data.acceleration.x * g, data.acceleration.y * g, data.acceleration.z * g)
|
|
276
|
+
if requested["acceleration"] != nil, keep("acceleration", at: t) {
|
|
277
|
+
add("acceleration", [t, x, y, z])
|
|
278
|
+
}
|
|
279
|
+
if requested["shake"] != nil, shakes.add(t, x, y, z) {
|
|
280
|
+
add("shake", [t])
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private func deviceMotion(_ data: CMDeviceMotion) {
|
|
285
|
+
guard !inBackground else { return }
|
|
286
|
+
let t = clock.milliseconds(data.timestamp)
|
|
287
|
+
if requested["rotation"] != nil, keep("rotation", at: t) {
|
|
288
|
+
let rate = data.rotationRate
|
|
289
|
+
add("rotation", [t, rate.x, rate.y, rate.z])
|
|
290
|
+
}
|
|
291
|
+
if requested["orientation"] != nil, keep("orientation", at: t) {
|
|
292
|
+
add("orientation", [t] + Self.deviceToEarth(data))
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/// The attitude as the matrix the runtime reads: the one that turns a
|
|
297
|
+
/// vector in the phone's frame into the earth's, row by row, as Android's
|
|
298
|
+
/// `getRotationMatrixFromVector` makes it. Its last row is the earth's up
|
|
299
|
+
/// in the phone's frame, which is gravity turned around.
|
|
300
|
+
///
|
|
301
|
+
/// Apple doesn't say which way `CMRotationMatrix` turns, so the matrix is
|
|
302
|
+
/// taken as it is or transposed, whichever's last row points up as gravity
|
|
303
|
+
/// says it should.
|
|
304
|
+
private static func deviceToEarth(_ data: CMDeviceMotion) -> [Double] {
|
|
305
|
+
let m = data.attitude.rotationMatrix
|
|
306
|
+
let up = (-data.gravity.x, -data.gravity.y, -data.gravity.z)
|
|
307
|
+
let asIs = [m.m11, m.m12, m.m13, m.m21, m.m22, m.m23, m.m31, m.m32, m.m33]
|
|
308
|
+
let transposed = [m.m11, m.m21, m.m31, m.m12, m.m22, m.m32, m.m13, m.m23, m.m33]
|
|
309
|
+
let dot = { (r: [Double]) in r[6] * up.0 + r[7] * up.1 + r[8] * up.2 }
|
|
310
|
+
return dot(transposed) >= dot(asIs) ? transposed : asIs
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/// Whether a sensor's sample at `t` is due, by the interval it was started
|
|
314
|
+
/// at, allowing a little early for the sensor's jitter. Marks it kept.
|
|
315
|
+
private func keep(_ sensor: String, at t: Double) -> Bool {
|
|
316
|
+
guard let interval = requested[sensor] else { return false }
|
|
317
|
+
// The runtime's own rule (`due()` in motion.ts): a sample up to a quarter
|
|
318
|
+
// of the interval early, 4 ms at most, counts. A wider one here would
|
|
319
|
+
// pass samples the runtime then skips, halving a watch's rate.
|
|
320
|
+
let ms = interval * 1000
|
|
321
|
+
if let last = lastSample[sensor], t - last < ms - min(4, ms / 4) { return false }
|
|
322
|
+
lastSample[sensor] = t
|
|
323
|
+
return true
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/// Adds a sample to the next event, which goes at most every 16 ms.
|
|
327
|
+
private func add(_ sensor: String, _ values: [Double]) {
|
|
328
|
+
batch[sensor, default: []].append(contentsOf: values)
|
|
329
|
+
guard !flushScheduled else { return }
|
|
330
|
+
flushScheduled = true
|
|
331
|
+
let wait = max(0, lastFlush + Self.flushInterval - ProcessInfo.processInfo.systemUptime)
|
|
332
|
+
queue.asyncAfter(deadline: .now() + wait) { self.flush() }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private func flush() {
|
|
336
|
+
flushScheduled = false
|
|
337
|
+
lastFlush = ProcessInfo.processInfo.systemUptime
|
|
338
|
+
guard !batch.isEmpty else { return }
|
|
339
|
+
let sent = batch
|
|
340
|
+
batch = [:]
|
|
341
|
+
context?.sendGlobalEvent(Self.event, withParams: [sent])
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/// Stamps the samples in milliseconds since the epoch, as the runtime's
|
|
346
|
+
/// `Date.now()` counts, from the epoch time of the phone's start read once:
|
|
347
|
+
/// each time is counted from there, so the times only go forward, and
|
|
348
|
+
/// spacing and shakes go by them, even when the system's clock is changed.
|
|
349
|
+
///
|
|
350
|
+
/// Core Motion stamps a sample with the uptime (`systemUptime`, Mach's
|
|
351
|
+
/// absolute time), which stops while the phone sleeps. Counted from the
|
|
352
|
+
/// start on that clock alone, every stamp would fall behind by all the time
|
|
353
|
+
/// the phone has ever slept (issue #1021), and `onShake()`, which notes
|
|
354
|
+
/// `Date.now()` as a handler starts, would skip each shake after the phone
|
|
355
|
+
/// woke. So the start is read on Mach's continuous time, which counts the
|
|
356
|
+
/// sleep, and each stamp adds the sleep so far to the sample's uptime, as
|
|
357
|
+
/// Android's `elapsedRealtimeNanos()` includes it. The sleep only changes
|
|
358
|
+
/// while the phone sleeps, and the app is in the background then, its
|
|
359
|
+
/// sensors stopped, so no sample measured before a sleep is stamped after.
|
|
360
|
+
struct MotionClock {
|
|
361
|
+
/// Seconds since the phone started, with the sleep and without it. They're
|
|
362
|
+
/// parameters only so a test can put the phone to sleep.
|
|
363
|
+
private let continuousTime: () -> TimeInterval
|
|
364
|
+
private let uptime: () -> TimeInterval
|
|
365
|
+
private let epochAtBoot: TimeInterval
|
|
366
|
+
|
|
367
|
+
init(
|
|
368
|
+
continuousTime: @escaping () -> TimeInterval = MotionClock.machContinuousTime,
|
|
369
|
+
uptime: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
|
|
370
|
+
) {
|
|
371
|
+
self.continuousTime = continuousTime
|
|
372
|
+
self.uptime = uptime
|
|
373
|
+
epochAtBoot = Date().timeIntervalSince1970 - continuousTime()
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/// An uptime, seconds the phone has been awake since it started, in
|
|
377
|
+
/// milliseconds since the epoch.
|
|
378
|
+
func milliseconds(_ uptime: TimeInterval) -> Double {
|
|
379
|
+
(epochAtBoot + slept() + uptime) * 1000
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/// How long the phone has slept since it started, in seconds: the time
|
|
383
|
+
/// that counts sleep less the uptime, which doesn't.
|
|
384
|
+
private func slept() -> TimeInterval {
|
|
385
|
+
// The uptime first, so the nanoseconds between the two reads add to the
|
|
386
|
+
// sleep rather than taking it below zero.
|
|
387
|
+
let awake = uptime()
|
|
388
|
+
return continuousTime() - awake
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/// Mach's continuous time, which goes on while the phone sleeps, in seconds.
|
|
392
|
+
/// Its ticks are 1 ns on Intel and 125/3 ns on Apple silicon.
|
|
393
|
+
static func machContinuousTime() -> TimeInterval {
|
|
394
|
+
Double(mach_continuous_time()) * Double(timebase.numer) / Double(timebase.denom)
|
|
395
|
+
/ 1_000_000_000
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
private static let timebase: mach_timebase_info_data_t = {
|
|
399
|
+
var info = mach_timebase_info_data_t()
|
|
400
|
+
mach_timebase_info(&info)
|
|
401
|
+
return info
|
|
402
|
+
}()
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/// Hears a shake in accelerometer samples: the runtime's `ShakeDetector`
|
|
406
|
+
/// (`motion/motion-math.ts`), after Square's Seismic. A sample accelerates
|
|
407
|
+
/// past 13 m/s², and the phone is shaking when three quarters of the samples
|
|
408
|
+
/// of the last half second do, over a quarter of a second or more.
|
|
409
|
+
private struct ShakeDetector {
|
|
410
|
+
private var samples: [(t: Double, accelerating: Bool)] = []
|
|
411
|
+
private var accelerating = 0
|
|
412
|
+
private var quietUntil = -Double.infinity
|
|
413
|
+
|
|
414
|
+
mutating func add(_ t: Double, _ x: Double, _ y: Double, _ z: Double) -> Bool {
|
|
415
|
+
let fast = x * x + y * y + z * z > 13 * 13
|
|
416
|
+
samples.append((t, fast))
|
|
417
|
+
if fast { accelerating += 1 }
|
|
418
|
+
while let first = samples.first, first.t < t - 500 {
|
|
419
|
+
if samples.removeFirst().accelerating { accelerating -= 1 }
|
|
420
|
+
}
|
|
421
|
+
if t < quietUntil { return false }
|
|
422
|
+
guard let first = samples.first, samples.count >= 4, t - first.t >= 250,
|
|
423
|
+
accelerating * 4 >= samples.count * 3
|
|
424
|
+
else { return false }
|
|
425
|
+
samples.removeAll()
|
|
426
|
+
accelerating = 0
|
|
427
|
+
quietUntil = t + 750
|
|
428
|
+
return true
|
|
429
|
+
}
|
|
430
|
+
}
|