diff --git a/Documentation/Plan.md b/Documentation/Plan.md index e054308..cc09348 100644 --- a/Documentation/Plan.md +++ b/Documentation/Plan.md @@ -52,7 +52,7 @@ contracts. D-Bus is PureSwift/DBus, in Swift, without libdbus. | arm64 and x86_64 Linux with glibc (Debian 13, Ubuntu 24.04+) | armv7, musl | | Native slices, loaded by the runner | `App.wasm`, in an engine in the runner; wasm2c for a target a bundle lacks, before it's installed | | Wayland and X11 through SDL3; a headless driver for tests | Multiple windows | -| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, the built-ins | Motion (iio-sensor-proxy), NFC (neard) | +| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, motion, the built-ins | NFC (neard) | ## 2. Process model @@ -99,12 +99,13 @@ timers for `schedule`. | `LinuxGraphics` | `Surface` over EGL and GLES 2.0, loaded at run time; the player's `GLSurface` view shows it (§7) | | `LinuxWebKit` | `WebContent` over WPE WebKit, loaded at run time; the player's `WebView` view shows it (§8) | | `LinuxCoreModel` | `LinuxModelStore`: the model store over CoreModel-SQLite, through AppRuntime's `HostModelStore` (§9) | -| `LinuxDevice` | `Device` from `/etc`, DMI, the device tree, and power and heat in sysfs (§10) | +| `LinuxDevice` | `Device` from `/etc`, DMI, the device tree, and power and heat in sysfs; orientation and proximity from iio-sensor-proxy (§10) | | `LinuxDBus` | `Bus`: the system and session buses, for the modules that talk to system services: method calls, properties and signals by match rule, delivered on the main loop (§11.1) | | `LinuxLocation` | `LocationManager`, `Location` and `Heading` over GeoClue 2 (§11) | | `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser, and bookmarks (§12) | +| `LinuxMotion` | `MotionManager` and `Altimeter` over the kernel's IIO sensors in sysfs, and an unavailable `Pedometer` and `ActivityRecognizer` (§13) | | `LinuxHostApp` | `main`: reads the app's keys, starts the host, and runs Cacao's SDL loop with one window showing the guest's first renderer | -| `LinuxPackager`, `linux-app` | The packager (§14, [Packager.md](Packager.md)) | +| `LinuxPackager`, `linux-app` | The packager (§15, [Packager.md](Packager.md)) | The package depends on AppRuntime without its `GuestExports` trait, like DarwinAppRuntime, so the slice's `rt_dispatch` and `rt_finalize` are the @@ -439,8 +440,17 @@ asked of D-Bus: monitoring is on, low power and thermal state always. - **Firmware placeholders** in DMI ("To be filled by O.E.M.", "Default string") count as nothing. -- **Orientation and proximity** read as unknown and off: they come from - iio-sensor-proxy, with the motion contracts. +- **Orientation and proximity** are iio-sensor-proxy's + (`net.hadess.SensorProxy`, on the system bus). Enabling orientation + claims its accelerometer, if it has one, and `AccelerometerOrientation` + is the orientation: `normal` portrait (the device's natural + orientation), `bottom-up` upside down, `left-up` (the top to the right) + `landscapeRight`, `right-up` `landscapeLeft`; it has no face up or down. + Enabling proximity asks whether it has a sensor, waiting for the answer, + and claims it if so; `ProximityNear` is the state. Each change from + `PropertiesChanged` reaches the delegate once, and disabling releases + the sensor. Without iio-sensor-proxy, orientation reads as unknown and + proximity monitoring stays off. ## 11. Location @@ -502,8 +512,9 @@ of its own, made when it first needs one: ### 11.1 D-Bus -`LinuxDBus` is what Bluetooth and Location, and later Motion -(iio-sensor-proxy), NFC (neard) and the desktop portal, share. `Bus.system` +`LinuxDBus` is what Bluetooth, Location, the device's orientation and +proximity (iio-sensor-proxy) and the desktop portal, and later NFC (neard), +share. `Bus.system` and `Bus.session` are one connection each per process, made on first use through PureSwift/DBus, which speaks D-Bus in Swift, without libdbus; its values are `DBusMessageArgument`s, whose arrays and dictionaries carry @@ -576,7 +587,61 @@ another, outside the app. handle from xdg-foreign. The titles and the filter's name are English. The photo picker is the file chooser for images and videos. -## 13. Testing +## 13. Motion + +`LinuxMotion` is the Motion contracts (AppRuntime's `Motion.md`). +iio-sensor-proxy only says which way the screen is up, which is the +device's orientation (§10), so the samples come from the kernel's +Industrial I/O sensors themselves, read through sysfs +(`/sys/bus/iio/devices/iio:deviceN`), as iio-sensor-proxy reads the ones it +polls. Reading them needs no permission. + +| Sensor | IIO channel | Contract | +|---|---|---| +| Accelerometer | `in_accel_{x,y,z}`, m/s² | as it is: face up, z ≈ +9.81 | +| Gyroscope | `in_anglvel_{x,y,z}`, rad/s | as it is | +| Magnetometer | `in_magn_{x,y,z}`, gauss | ×100, µT; accuracy `uncalibrated` | +| Device motion | the accelerometer and gyroscope | fused (below) | +| Barometer | `in_pressure`, kPa | `Altimeter` | + +- **Sensors** are the first IIO device, by number, with each one's + channels. A channel's value is its `_input`, or `(_raw + offset) × + scale`, its own scale and offset or its type's. Its mount matrix (the + type's `_mount_matrix`, or the device's `mount_matrix`) turns the + sensor's axes into the device's, which are the contract's: x to the + right, y toward the top, z out of the screen. +- **Samples** are polled off the main thread, since a driver may answer + over I²C, on one queue for every sensor, at the interval asked for: no + faster than 100 Hz, as on iOS, or than the sensor's fastest + `sampling_frequency_available`, which is `minimumInterval`. Each is + stamped with `CLOCK_BOOTTIME` as it's read, and posted to the main loop; + none arrives after `stop`. Each attribute's file stays open, and is read + again from its start. +- **Device motion** is a Mahony filter: it integrates the rotation rate and + pulls the attitude toward the gravity the accelerometer measures. It + starts level with the first reading, so its attitude has z vertical and + x where the device's x pointed, as Android's game rotation vector does; + nothing corrects drift around the vertical. Gravity is the vertical in + the device's axes, and user acceleration what's left without it. +- **Failing**: a sensor that isn't there fails at `start` with + `unavailable`. One that stops reading stops, `unavailable` once it's gone + and `unknown` otherwise. A driver streaming to its buffer, as one does + while iio-sensor-proxy has it claimed, may answer busy: those readings + are skipped. +- **The altimeter** reads the pressure once a second, as CoreMotion + delivers it, and the relative altitude is the standard atmosphere's from + the first reading, as Android's `SensorManager.getAltitude` computes it. + Nothing asks the user, as on Android: it's `authorized`, and `motion` + asks for nothing. +- **The pedometer and activity recognition** have nothing under them on + Linux. They're registered, so an app written for phones runs: not + available, `authorized`, and updates and queries fail with + `unavailable`. +- **Not yet**: an IIO device plugged in or out while a sensor runs isn't + noticed until it's started again, and the magnetometer isn't calibrated. + None of it has run on real sensors. + +## 14. Testing - `LinuxUI`: DarwinUI's tests, on Cacao (§5). - `LinuxBluetooth`: the contract against a fake `BlueZBus` that plays @@ -596,7 +661,17 @@ another, outside the app. temporary root: identity, idioms, batteries (energy and capacity, a mouse's left out, each status), thermal states, low power, the vendor identifier kept per vendor, and changes reaching the delegate once each, - by themselves on the main loop. + by themselves on the main loop. Orientation and proximity against a fake + iio-sensor-proxy: claimed and released, each change once, turned off + before the proxy answered, and no sensor or no proxy. +- `LinuxMotion`: IIO devices' attributes under a temporary root: scaled + readings in the device's axes by the mount matrix, inputs, offsets and + units, the first device by number, the fastest sampling; the fusion + starting level with gravity, integrating a quarter turn, and following + gravity back; samples reaching the delegate on the main loop and none + after `stop`, a missing sensor, one that stops reading, the + magnetometer's accuracy; the altimeter's altitude, and no barometer; the + pedometer and activity recognizer unavailable; the module's contracts. - `LinuxLocation`: the contract against a fake `GeoClueBus` that plays GeoClue's manager, clients, agent and locations. Runs on macOS and Linux: nothing asked until a client's needed; the client's desktop ID and @@ -649,7 +724,7 @@ another, outside the app. `bluetoothd`. Real GeoClue needs a session with an agent, or the app allowed in `geoclue.conf`. -## 14. Phases +## 15. Phases 1. **Host runtime and player**: `LinuxHost`, `LinuxUI`, `LinuxBluetooth`, `LinuxHostApp`; `ExampleUI` runs in Docker. @@ -657,14 +732,14 @@ another, outside the app. thinned to the target's `libapp.so`, a `.desktop` file and icon, for the runner; later Flatpak and AppImage, whose manifests carry the capabilities (`--system-talk-name=org.bluez` for `bluetooth`). -3. **More contracts**: Motion (iio-sensor-proxy), NFC (neard). - Formatting and HTTP are done: AppRuntime's `RuntimeFormatting` and - `RuntimeNetworking` (§3), and so are the device (§10), location - (§11), over GeoClue2, and documents (§12), over the desktop portal. +3. **More contracts**: NFC (neard). Formatting and HTTP are done: + AppRuntime's `RuntimeFormatting` and `RuntimeNetworking` (§3), and so + are the device (§10), location (§11), over GeoClue2, documents (§12), + over the desktop portal, and motion (§13), over IIO. 4. **Player**: what DarwinUI and Cacao add: Cacao's AT-SPI bridge, input replay for end-to-end tests. -## 15. Open questions +## 16. Open questions - **Permissions.** Desktop Linux has no prompts for Bluetooth; Flatpak's portals cover location and the camera. `Permissions.request` answers from diff --git a/Package.swift b/Package.swift index 0d19c24..d85fc40 100644 --- a/Package.swift +++ b/Package.swift @@ -69,6 +69,7 @@ let package = Package( .library(name: "LinuxDevice", targets: ["LinuxDevice"]), .library(name: "LinuxDBus", targets: ["LinuxDBus"]), .library(name: "LinuxLocation", targets: ["LinuxLocation"]), + .library(name: "LinuxMotion", targets: ["LinuxMotion"]), .library(name: "LinuxHostApp", targets: ["LinuxHostApp"]), .executable(name: "linux-app-host", targets: ["LinuxAppHost"]), .executable(name: "linux-app", targets: ["LinuxAppTool"]), @@ -159,10 +160,10 @@ let package = Package( // MARK: - Device // The machine: /etc, DMI, the device tree, and power and heat in - // sysfs. + // sysfs; orientation and proximity from iio-sensor-proxy. .target( name: "LinuxDevice", - dependencies: ["LinuxHost", runtime("DynamicDevice"), runtime("DynamicRuntime")], + dependencies: ["LinuxHost", "LinuxDBus", runtime("DynamicDevice"), runtime("DynamicRuntime"), .product(name: "DBus", package: "DBus")], swiftSettings: host ), @@ -199,6 +200,16 @@ let package = Package( swiftSettings: host ), + // MARK: - Motion + + // The kernel's IIO sensors in sysfs: accelerometer, gyroscope, + // magnetometer and barometer. + .target( + name: "LinuxMotion", + dependencies: ["LinuxHost", runtime("DynamicMotion"), runtime("DynamicRuntime"), runtime("RuntimeHost")], + swiftSettings: host + ), + // MARK: - App // What the runner's process supplies that libc may not @@ -206,7 +217,7 @@ let package = Package( .target(name: "CLinuxHost"), .target( name: "LinuxHostApp", - dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), + dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicGraphics"), .product(name: "CacaoSDL", package: "Cacao")], swiftSettings: host ), @@ -230,7 +241,7 @@ let package = Package( // doesn't build Cacao. .target( name: "LinuxPackager", - dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), + dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), .product(name: "Crypto", package: "swift-crypto")] ), .executableTarget( @@ -255,7 +266,8 @@ let package = Package( .product(name: "CoreModelSQLite", package: "CoreModel-SQLite")], swiftSettings: host ), - .testTarget(name: "LinuxDeviceTests", dependencies: ["LinuxDevice", runtime("DynamicDevice")], swiftSettings: host), + .testTarget(name: "LinuxDeviceTests", dependencies: ["LinuxDevice", "LinuxDBus", runtime("DynamicDevice"), .product(name: "DBus", package: "DBus")], + swiftSettings: host), .testTarget(name: "LinuxDBusTests", dependencies: ["LinuxDBus", .product(name: "DBus", package: "DBus")], swiftSettings: host), .testTarget(name: "LinuxLocationTests", dependencies: ["LinuxLocation", "LinuxDBus", runtime("DynamicLocation"), .product(name: "DBus", package: "DBus")], swiftSettings: host), @@ -263,6 +275,7 @@ let package = Package( runtime("DynamicFiles"), runtime("RuntimeHost"), runtime("RuntimeNative"), .product(name: "DBus", package: "DBus")], swiftSettings: host), + .testTarget(name: "LinuxMotionTests", dependencies: ["LinuxMotion", runtime("DynamicMotion")], swiftSettings: host), .testTarget(name: "LinuxWebKitTests", dependencies: ["LinuxWebKit", runtime("DynamicWebKit")], swiftSettings: host), .testTarget(name: "LinuxPackagerTests", dependencies: ["LinuxPackager", "LinuxHostApp", runtime("RuntimeNetworking")]), ] diff --git a/README.md b/README.md index f7d18ad..8856cc3 100644 --- a/README.md +++ b/README.md @@ -59,10 +59,11 @@ added to its database between launches: | `LinuxGraphics` | `Surface`: GLES 2.0 drawn in EGL pbuffers, loaded at run time, and read back into the player's `GLSurface` view ([plan](Documentation/Plan.md) §7) | | `LinuxWebKit` | `WebContent`: WPE WebKit pages, loaded at run time, drawn into shared memory and shown by the player's `WebView` view ([plan](Documentation/Plan.md) §8) | | `LinuxCoreModel` | `LinuxModelStore`: the app's CoreModel stores in SQLite, through AppRuntime's `HostModelStore` and CoreModel-SQLite ([plan](Documentation/Plan.md) §9) | -| `LinuxDevice` | `Device`: the machine, its battery, power mode and heat, from `/etc`, DMI, the device tree and sysfs ([plan](Documentation/Plan.md) §10) | +| `LinuxDevice` | `Device`: the machine, its battery, power mode and heat, from `/etc`, DMI, the device tree and sysfs, and its orientation and proximity from iio-sensor-proxy ([plan](Documentation/Plan.md) §10) | | `LinuxDBus` | `Bus`: the system and session buses for the modules that talk to system services, over PureSwift/DBus, with calls, properties and signals delivered on the main loop ([plan](Documentation/Plan.md) §11.1) | | `LinuxLocation` | `LocationManager`: the device's location from GeoClue 2 on the system bus, which its agent authorizes by the app's desktop ID; no heading ([plan](Documentation/Plan.md) §11) | | `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser on the session bus, for opening, folders and saving, and bookmarks in the app's data ([plan](Documentation/Plan.md) §12) | +| `LinuxMotion` | Motion: the accelerometer, gyroscope, magnetometer and barometer from the kernel's IIO sensors in sysfs, device motion fused from them, and a pedometer and activity recognizer that are unavailable ([plan](Documentation/Plan.md) §13) | | `LinuxHostApp`, `linux-app-host` | The app's `main`: the host, and Cacao's window and loop. It also registers AppRuntime's `RuntimeFormatting`, dates and numbers over Swift Foundation, and `RuntimeNetworking`, HTTP over `URLSession` and libcurl ([plan](Documentation/Plan.md) §3) | | `LinuxPackager`, `linux-app` | The packager: validation, thinning a bundle to one target, the install tree, PortMaster ports | diff --git a/Sources/LinuxDevice/LinuxDevice.swift b/Sources/LinuxDevice/LinuxDevice.swift index 123c709..b39bb2b 100644 --- a/Sources/LinuxDevice/LinuxDevice.swift +++ b/Sources/LinuxDevice/LinuxDevice.swift @@ -1,6 +1,8 @@ +import DBus import DynamicDevice import DynamicRuntime import Foundation +import LinuxDBus import LinuxHost /// The `Device` contract on Linux (`Plan.md` §10): identity from @@ -12,13 +14,18 @@ import LinuxHost /// delegate: battery level and state while battery monitoring is on, and /// low power and thermal state always, as on other hosts. /// -/// Orientation and proximity read as unknown: they come from -/// iio-sensor-proxy, with the motion contracts. +/// Orientation and proximity are iio-sensor-proxy's, on the system bus: +/// its accelerometer's orientation and its proximity sensor, claimed while +/// they're enabled. Without it, orientation reads as unknown and proximity +/// monitoring stays off. public final class LinuxDevice: Device { /// The machine's files; replaceable for tests. nonisolated(unsafe) static var system = SystemInfo() + /// iio-sensor-proxy; replaceable for tests. + nonisolated(unsafe) static var sensorProxy: any SensorProxyBus = SystemSensorProxy() + /// How often changes are looked for. nonisolated(unsafe) static var interval: Int64 = 5_000_000_000 @@ -33,6 +40,18 @@ public final class LinuxDevice: Device { /// What the delegate was last told. private var last: (level: Float, state: BatteryState, lowPower: Bool, thermal: ThermalState)? + /// The app's wish, and whether the proxy has the sensor claimed for it. + private var orientationUpdates = false + private var accelerometerClaimed = false + private var currentOrientation = DeviceOrientation.unknown + + private var proximityMonitoring = false + private var proximityClaimed = false + private var near = false + + /// The proxy's `PropertiesChanged`, while either is enabled. + private var changes: BusSubscription? + init() { } public static func current() -> LinuxDevice { @@ -49,6 +68,9 @@ public final class LinuxDevice: Device { if let timer = instance?.timer { MainLoop.shared.cancel(timer) } + if let changes = instance?.changes { + sensorProxy.unsubscribe(changes) + } instance = nil } @@ -148,21 +170,134 @@ public final class LinuxDevice: Device { // MARK: Orientation and proximity - public func setOrientationUpdatesEnabled(_ enabled: Bool) { } + /// Claims the proxy's accelerometer, if it has one; the orientation + /// arrives on a later turn, and the delegate hears of it. + public func setOrientationUpdatesEnabled(_ enabled: Bool) { + guard enabled != orientationUpdates else { return } + orientationUpdates = enabled + if enabled { + subscribe() + claim(has: "HasAccelerometer", "ClaimAccelerometer", wanted: { $0.orientationUpdates }) { device, properties in + device.accelerometerClaimed = true + device.orient(properties["AccelerometerOrientation"]?.text) + } + } else { + if accelerometerClaimed { + accelerometerClaimed = false + release("ReleaseAccelerometer") + } + currentOrientation = .unknown + unsubscribeIfIdle() + } + } public func orientation() -> Int32 { - DeviceOrientation.unknown.rawValue + currentOrientation.rawValue } - /// There's no proximity sensor to turn on. - public func setProximityMonitoringEnabled(_ enabled: Bool) { } + /// Asks the proxy whether there's a proximity sensor, waiting for the + /// answer, and claims it if there is; it stays off if not. + public func setProximityMonitoringEnabled(_ enabled: Bool) { + guard enabled != proximityMonitoring else { return } + if enabled { + guard (try? Self.sensorProxy.propertyAndWait("HasProximity").get())?.flag == true else { return } + proximityMonitoring = true + subscribe() + claim(has: "HasProximity", "ClaimProximity", wanted: { $0.proximityMonitoring }) { device, properties in + device.proximityClaimed = true + device.approach(properties["ProximityNear"]?.flag ?? false) + } + } else { + proximityMonitoring = false + if proximityClaimed { + proximityClaimed = false + release("ReleaseProximity") + } + near = false + unsubscribeIfIdle() + } + } public func isProximityMonitoringEnabled() -> Bool { - false + proximityMonitoring } public func proximityState() -> Bool { - false + near + } + + // MARK: iio-sensor-proxy + + /// Claims a sensor the proxy has, while it's still `wanted`, and hands + /// over the properties once it's claimed. + private func claim(has: String, _ method: String, wanted: @escaping (LinuxDevice) -> Bool, + claimed: @escaping (LinuxDevice, [String: DBusMessageArgument]) -> Void) { + let proxy = Self.sensorProxy + proxy.properties { [weak self] result in + guard let self, wanted(self) else { return } + guard case .success(let properties) = result, properties[has]?.flag == true else { + if case .failure(let error) = result, !error.isServiceMissing { + HostLog.error("device: iio-sensor-proxy: \(error)") + } + return + } + proxy.call(method) { [weak self] result in + guard let self else { return } + if case .failure(let error) = result { + HostLog.error("device: iio-sensor-proxy: \(method): \(error)") + return + } + guard wanted(self) else { + self.release(method.replacingOccurrences(of: "Claim", with: "Release")) + return + } + // What it reads now it's claimed. + proxy.properties { [weak self] result in + guard let self, wanted(self), case .success(let properties) = result else { return } + claimed(self, properties) + } + } + } + } + + private func release(_ method: String) { + Self.sensorProxy.call(method) { result in + if case .failure(let error) = result { + HostLog.error("device: iio-sensor-proxy: \(method): \(error)") + } + } + } + + private func subscribe() { + guard changes == nil else { return } + changes = Self.sensorProxy.subscribeToChanges { [weak self] changed in + guard let self else { return } + if self.accelerometerClaimed, let orientation = changed["AccelerometerOrientation"]?.text { + self.orient(orientation) + } + if self.proximityClaimed, let near = changed["ProximityNear"]?.flag { + self.approach(near) + } + } + } + + private func unsubscribeIfIdle() { + guard !orientationUpdates, !proximityMonitoring, let changes else { return } + Self.sensorProxy.unsubscribe(changes) + self.changes = nil + } + + private func orient(_ name: String?) { + let orientation = SensorProxy.orientation(name ?? "") + guard orientation != currentOrientation else { return } + currentOrientation = orientation + delegate?.didChangeOrientation(self, orientation: orientation.rawValue) + } + + private func approach(_ near: Bool) { + guard near != self.near else { return } + self.near = near + delegate?.didChangeProximityState(self, near: near) } // MARK: Changes diff --git a/Sources/LinuxDevice/SensorProxy.swift b/Sources/LinuxDevice/SensorProxy.swift new file mode 100644 index 0000000..e18783f --- /dev/null +++ b/Sources/LinuxDevice/SensorProxy.swift @@ -0,0 +1,85 @@ +import DBus +import DynamicDevice +import LinuxDBus +import LinuxHost + +/// iio-sensor-proxy on the system bus (`Plan.md` §10), or a fake one in +/// tests: `net.hadess.SensorProxy` at `/net/hadess/SensorProxy`. Everything +/// it answers arrives on the main loop. +public protocol SensorProxyBus: AnyObject { + + /// Calls one of its methods, which take nothing and answer nothing: + /// `ClaimAccelerometer`, `ReleaseProximity` and so on. + func call(_ method: String, reply: @escaping (Result) -> Void) + + /// Every property. + func properties(reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) + + /// One property, waiting for it: for the contract's synchronous calls. + func propertyAndWait(_ name: String) -> Result + + /// Calls `handler` with the properties each `PropertiesChanged` signal + /// changes. + func subscribeToChanges(_ handler: @escaping ([String: DBusMessageArgument]) -> Void) -> BusSubscription + + func unsubscribe(_ subscription: BusSubscription) +} + +/// iio-sensor-proxy's names and values. +public enum SensorProxy { + + public static let service = "net.hadess.SensorProxy" + + public static let path = "/net/hadess/SensorProxy" + + public static let interface = "net.hadess.SensorProxy" + + /// `AccelerometerOrientation`: which edge of the device is up, from its + /// natural orientation, `normal`. `left-up` has the top to the right. + public static func orientation(_ name: String) -> DeviceOrientation { + switch name { + case "normal": .portrait + case "bottom-up": .portraitUpsideDown + case "left-up": .landscapeRight + case "right-up": .landscapeLeft + default: .unknown + } + } +} + +/// iio-sensor-proxy on the system bus, through LinuxDBus. +public final class SystemSensorProxy: SensorProxyBus { + + private let bus: Bus + + public init(bus: Bus = .system) { + self.bus = bus + } + + public func call(_ method: String, reply: @escaping (Result) -> Void) { + bus.call(SensorProxy.service, SensorProxy.path, SensorProxy.interface, method) { result in + reply(result.map { _ in }) + } + } + + public func properties(reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) { + bus.properties(SensorProxy.service, SensorProxy.path, SensorProxy.interface, reply: reply) + } + + public func propertyAndWait(_ name: String) -> Result { + bus.propertyAndWait(SensorProxy.service, SensorProxy.path, SensorProxy.interface, name) + } + + public func subscribeToChanges(_ handler: @escaping ([String: DBusMessageArgument]) -> Void) -> BusSubscription { + let rule = MatchRule(sender: SensorProxy.service, path: SensorProxy.path, interface: "org.freedesktop.DBus.Properties", + member: "PropertiesChanged", arg0: SensorProxy.interface) + return bus.subscribe(rule) { signal in + guard signal.body.count > 1 else { return } + handler(signal.body[1].entries) + } + } + + public func unsubscribe(_ subscription: BusSubscription) { + bus.unsubscribe(subscription) + } +} diff --git a/Sources/LinuxHostApp/HostApp.swift b/Sources/LinuxHostApp/HostApp.swift index 5536e5c..e1cb370 100644 --- a/Sources/LinuxHostApp/HostApp.swift +++ b/Sources/LinuxHostApp/HostApp.swift @@ -10,6 +10,7 @@ import LinuxDevice import LinuxDocuments import LinuxGraphics import LinuxLocation +import LinuxMotion import LinuxWebKit import LinuxUI import RuntimeFormatting @@ -37,11 +38,11 @@ public enum HostApp { /// Bluetooth, GL surfaces and web pages, which the player shows, the /// app's files, settings and model stores, AppRuntime's date and number /// formatting and its HTTP client over Swift Foundation, the device, - /// location, and the user's documents. + /// location, the user's documents, and motion sensors. public static let modules: [any HostModule.Type] = [ DarwinUI.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, + LinuxDocuments.self, LinuxMotion.self, ] /// Points AppRuntime's modules at this host: networking's callbacks, diff --git a/Sources/LinuxMotion/IIOSensors.swift b/Sources/LinuxMotion/IIOSensors.swift new file mode 100644 index 0000000..37aa8d5 --- /dev/null +++ b/Sources/LinuxMotion/IIOSensors.swift @@ -0,0 +1,215 @@ +import Foundation +import Glibc + +/// The kernel's Industrial I/O sensors, read through sysfs +/// (`/sys/bus/iio/devices/iio:deviceN`), as iio-sensor-proxy reads the +/// ones it polls. Reading an attribute needs no permission. +/// +/// | Sensor | Channel | Unit after scale | +/// |---|---|---| +/// | Accelerometer | `in_accel_{x,y,z}` | m/s² | +/// | Gyroscope | `in_anglvel_{x,y,z}` | rad/s | +/// | Magnetometer | `in_magn_{x,y,z}` | gauss (×100 for µT) | +/// | Barometer | `in_pressure` | kPa | +/// +/// A channel's value is its `_input`, or `(_raw + offset) × scale`, the +/// scale and offset its own or the channel type's. Its mount matrix (the +/// channel type's `_mount_matrix`, or the device's `mount_matrix`) turns +/// the sensor's axes into the device's: x to the right, y toward the top, z +/// out of the screen, which is the contract's convention. +public struct IIOSensors { + + /// The directory of IIO devices. + public let root: String + + public init(root: String = "/sys/bus/iio/devices") { + self.root = root + } + + public enum Kind: String, Sendable, CaseIterable { + case accelerometer = "accel" + case gyroscope = "anglvel" + case magnetometer = "magn" + case barometer = "pressure" + + var axes: [String] { + self == .barometer ? [""] : ["_x", "_y", "_z"] + } + } + + /// The first device with `kind`'s channels, by device number. + public func channel(_ kind: Kind) -> IIOChannel? { + for device in devices() { + if let channel = IIOChannel(kind: kind, device: device) { + return channel + } + } + return nil + } + + /// The IIO devices' directories, `iio:device0` first. + func devices() -> [String] { + let names = (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? [] + return names + .filter { $0.hasPrefix("iio:device") } + .sorted { (Int($0.dropFirst(10)) ?? .max, $0) < (Int($1.dropFirst(10)) ?? .max, $1) } + .map { root + "/" + $0 } + } +} + +/// One sensor's channel: three axes, or one value for a barometer. Its +/// files stay open while it's being read. +public final class IIOChannel: @unchecked Sendable { + + public let kind: IIOSensors.Kind + + /// The device's directory. + public let device: String + + /// The device's `name`. + public let name: String + + /// Each axis's value file, and whether it's `_raw`. + private let files: [(path: String, raw: Bool)] + + private let scales: [Double] + + private let offsets: [Double] + + /// Rows of the sensor-to-device rotation. + let mountMatrix: [[Double]] + + /// The shortest interval the sensor samples at, from its sampling + /// frequencies; `nil` when it doesn't say. + public let minimumInterval: Double? + + private var descriptors: [Int32] = [] + + init?(kind: IIOSensors.Kind, device: String) { + let type = "in_" + kind.rawValue + var files: [(path: String, raw: Bool)] = [] + var scales: [Double] = [] + var offsets: [Double] = [] + for axis in kind.axes { + let channel = type + axis + if Self.exists(device + "/" + channel + "_input") { + files.append((device + "/" + channel + "_input", false)) + } else if Self.exists(device + "/" + channel + "_raw") { + files.append((device + "/" + channel + "_raw", true)) + } else { + return nil + } + scales.append(Self.number(device, [channel + "_scale", type + "_scale"]) ?? 1) + offsets.append(Self.number(device, [channel + "_offset", type + "_offset"]) ?? 0) + } + self.kind = kind + self.device = device + self.name = Self.text(device + "/name") ?? "" + self.files = files + self.scales = scales + self.offsets = offsets + self.mountMatrix = Self.matrix(Self.text(device + "/" + type + "_mount_matrix") ?? Self.text(device + "/mount_matrix")) + ?? Self.identity + let available = [type + "_sampling_frequency_available", "sampling_frequency_available"] + .lazy.compactMap { Self.text(device + "/" + $0) }.first + .map { $0.split(whereSeparator: \.isWhitespace).compactMap { Double($0) }.max() } + let frequency = available ?? Self.number(device, [type + "_sampling_frequency", "sampling_frequency"]) + self.minimumInterval = frequency.flatMap { $0 > 0 ? 1 / $0 : nil } + } + + deinit { + close() + } + + /// Why a reading failed. + public enum ReadError: Error, Equatable { + /// The driver is streaming to a buffer (iio-sensor-proxy has it + /// claimed), and won't answer one reading: try again later. + case busy + /// The file can't be read, or doesn't hold a number. + case failed(Int32) + } + + /// The channel's values, in the device's axes and the kind's units (µT + /// for a magnetometer). Opens its files the first time. + public func read() -> Result<[Double], ReadError> { + if descriptors.isEmpty { + for file in files { + let descriptor = open(file.path, O_RDONLY | O_CLOEXEC) + guard descriptor >= 0 else { + let error = errno + close() + return .failure(.failed(error)) + } + descriptors.append(descriptor) + } + } + var values: [Double] = [] + for (index, descriptor) in descriptors.enumerated() { + switch Self.value(descriptor) { + case .success(let value): + values.append(files[index].raw ? (value + offsets[index]) * scales[index] : value) + case .failure(let error): + if error != .busy { + close() + } + return .failure(error) + } + } + if kind == .magnetometer { + values = values.map { $0 * 100 } + } + guard values.count == 3 else { return .success(values) } + return .success(mountMatrix.map { row in row[0] * values[0] + row[1] * values[1] + row[2] * values[2] }) + } + + /// Closes the files; the next `read` opens them again. + public func close() { + for descriptor in descriptors { + Glibc.close(descriptor) + } + descriptors = [] + } + + // MARK: Files + + static let identity: [[Double]] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + + /// `x1, y1, z1; x2, y2, z2; x3, y3, z3`, as rows. + static func matrix(_ text: String?) -> [[Double]]? { + guard let text else { return nil } + let rows = text.split(separator: ";").map { row in + row.split(separator: ",").compactMap { Double($0.trimmingCharacters(in: .whitespaces)) } + } + guard rows.count == 3, rows.allSatisfy({ $0.count == 3 }) else { return nil } + return rows + } + + /// An attribute's number, read again from the start of the file. + static func value(_ descriptor: Int32) -> Result { + var buffer = [UInt8](repeating: 0, count: 64) + let count = buffer.withUnsafeMutableBytes { pread(descriptor, $0.baseAddress, $0.count, 0) } + guard count >= 0 else { + let error = errno + return .failure(error == EBUSY || error == EAGAIN ? .busy : .failed(error)) + } + let text = String(decoding: buffer[.. Bool { + access(path, R_OK) == 0 + } + + static func text(_ path: String) -> String? { + guard let data = FileManager.default.contents(atPath: path) else { return nil } + let text = String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) + return text.isEmpty ? nil : text + } + + /// The first of `names` in `device` that holds a number. + static func number(_ device: String, _ names: [String]) -> Double? { + names.lazy.compactMap { text(device + "/" + $0).flatMap(Double.init) }.first + } +} diff --git a/Sources/LinuxMotion/LinuxAltimeter.swift b/Sources/LinuxMotion/LinuxAltimeter.swift new file mode 100644 index 0000000..c299d9a --- /dev/null +++ b/Sources/LinuxMotion/LinuxAltimeter.swift @@ -0,0 +1,89 @@ +import DynamicMotion +import DynamicRuntime +import Foundation +import Glibc +import LinuxHost + +/// The `Altimeter` contract over an IIO barometer (`in_pressure`), polled +/// once a second as CoreMotion delivers. Main loop only. +/// +/// Nothing asks the user, as on Android: it's always `authorized`. The +/// relative altitude is the standard atmosphere's, from the first pressure +/// since `startUpdates()`, as Android's `SensorManager.getAltitude` +/// computes it. +public final class LinuxAltimeter: Altimeter { + + /// How often the pressure is read; replaceable for tests. + nonisolated(unsafe) static var interval = 1.0 + + let delegate: any AltimeterDelegate + + private var poller: SensorPoller<(Double, Int64)>? + + init(delegate: any AltimeterDelegate) { + self.delegate = delegate + } + + deinit { + poller?.stop() + } + + public static func isAvailable() -> Bool { + LinuxMotionManager.sensors.channel(.barometer) != nil + } + + public static func authorizationStatus() -> Int32 { + MotionAuthorization.authorized.rawValue + } + + public static func make(_ delegate: any AltimeterDelegate) -> LinuxAltimeter { + LinuxAltimeter(delegate: delegate) + } + + /// There's nothing to ask; the answer arrives on a later turn. + public func requestAuthorization() { + MainLoop.shared.post { [weak self] in + guard let self else { return } + self.delegate.didChangeAuthorization(self, status: MotionAuthorization.authorized.rawValue) + } + } + + public func startUpdates() { + guard poller == nil else { return } + guard let channel = LinuxMotionManager.sensors.channel(.barometer) else { + MainLoop.shared.post { [weak self] in + guard let self else { return } + self.delegate.didFail(self, error: MotionError.unavailable.rawValue) + } + return + } + var start: Double? + poller = SensorPoller(interval: Self.interval, read: { + channel.read().map { ($0[0], bootNanoseconds()) } + }, deliver: { [weak self] reading in + guard let self else { return } + let pressure = reading.0 + let base = start ?? pressure + start = base + let relative = Self.altitude(pressure) - Self.altitude(base) + self.delegate.didUpdate(self, pressure: pressure, relativeAltitude: relative, timestamp: reading.1) + }, fail: { [weak self] error in + guard let self else { return } + self.poller = nil + HostLog.error("motion: can't read \(channel.device): \(String(cString: strerror(error)))") + let code: MotionError = error == ENOENT || error == ENODEV ? .unavailable : .unknown + self.delegate.didFail(self, error: code.rawValue) + }) + } + + public func stopUpdates() { + poller?.stop() + poller = nil + } + + /// Metres above sea level at `pressure` kPa, in the standard + /// atmosphere. + static func altitude(_ pressure: Double) -> Double { + 44_330 * (1 - pow(pressure / 101.325, 1 / 5.255)) + } +} diff --git a/Sources/LinuxMotion/LinuxMotion.swift b/Sources/LinuxMotion/LinuxMotion.swift new file mode 100644 index 0000000..3868913 --- /dev/null +++ b/Sources/LinuxMotion/LinuxMotion.swift @@ -0,0 +1,39 @@ +import DynamicMotion +import DynamicRuntime +import LinuxHost +import RuntimeHost + +/// The Motion contracts (`Plan.md` §13): the inertial sensors and the +/// barometer over the kernel's IIO sensors, and a pedometer and activity +/// recognizer that are unavailable. Main loop only. +public enum LinuxMotion: HostModule { + + public static var contracts: [ContractDescriptor] { + [ + MotionManagerProxy.descriptor, + MotionManagerDelegateProxy.descriptor, + AltimeterProxy.descriptor, + AltimeterDelegateProxy.descriptor, + PedometerProxy.descriptor, + PedometerDelegateProxy.descriptor, + ActivityRecognizerProxy.descriptor, + ActivityRecognizerDelegateProxy.descriptor, + ] + } + + public static func register(in registrar: some ContractRegistrar) { + MotionManagerProxy.register(LinuxMotionManager.self, in: registrar) + MotionManagerDelegateProxy.registerInterface(in: registrar) + AltimeterProxy.register(LinuxAltimeter.self, in: registrar) + AltimeterDelegateProxy.registerInterface(in: registrar) + PedometerProxy.register(LinuxPedometer.self, in: registrar) + PedometerDelegateProxy.registerInterface(in: registrar) + ActivityRecognizerProxy.register(LinuxActivityRecognizer.self, in: registrar) + ActivityRecognizerDelegateProxy.registerInterface(in: registrar) + } + + /// Nothing asks: Motion & Fitness is a phone's permission. + public static func permissionProviders() -> [Capability: any PermissionProvider] { + [.motion: GrantedPermission()] + } +} diff --git a/Sources/LinuxMotion/LinuxMotionManager.swift b/Sources/LinuxMotion/LinuxMotionManager.swift new file mode 100644 index 0000000..421020e --- /dev/null +++ b/Sources/LinuxMotion/LinuxMotionManager.swift @@ -0,0 +1,168 @@ +import DynamicMotion +import DynamicRuntime +import Foundation +import Glibc +import LinuxHost + +/// The `MotionManager` contract over the kernel's IIO sensors (`Plan.md` +/// §13). Main loop only. +/// +/// - **Sensors** are the first IIO device with each one's channels (see +/// `IIOSensors`), in the device's axes by their mount matrix. Device +/// motion needs an accelerometer and a gyroscope, and is fused from them +/// (`MotionFusion`). +/// - **Samples** are polled from sysfs off the main thread, at the interval +/// asked for, no faster than 100 Hz or the sensor's own fastest +/// sampling. Each is stamped with the time since boot as it's read. +/// - **The magnetometer** isn't calibrated: its accuracy is +/// `uncalibrated`. +/// - A sensor that can't be read stops, with `unavailable` once it's gone +/// and `unknown` otherwise. A driver streaming to iio-sensor-proxy may +/// answer busy; those readings are skipped. +public final class LinuxMotionManager: MotionManager { + + /// The machine's sensors; replaceable for tests. + nonisolated(unsafe) static var sensors = IIOSensors() + + /// The shortest interval polled: 100 Hz, as on iOS. + static let fastest = 0.01 + + let delegate: any MotionManagerDelegate + + private var pollers: [MotionSensor: any Stoppable] = [:] + + init(delegate: any MotionManagerDelegate) { + self.delegate = delegate + } + + deinit { + for poller in pollers.values { + poller.stop() + } + } + + // MARK: Contract + + public static func isAvailable(_ sensor: Int32) -> Bool { + guard let sensor = MotionSensor(rawValue: sensor) else { return false } + return channels(sensor) != nil + } + + public static func make(_ delegate: any MotionManagerDelegate) -> LinuxMotionManager { + LinuxMotionManager(delegate: delegate) + } + + /// Starts again at `interval` if it's running. + public func start(_ sensor: Int32, interval: Double) { + guard let kind = MotionSensor(rawValue: sensor) else { + HostLog.error("motion: unknown MotionSensor \(sensor)") + return + } + pollers.removeValue(forKey: kind)?.stop() + guard let channels = Self.channels(kind) else { + MainLoop.shared.post { [weak self] in + guard let self else { return } + self.delegate.didFail(self, sensor: sensor, error: MotionError.unavailable.rawValue) + } + return + } + let interval = max(interval.isFinite ? interval : 0, Self.minimumInterval(channels)) + pollers[kind] = poller(kind, channels, interval: interval) + } + + public func stop(_ sensor: Int32) { + guard let kind = MotionSensor(rawValue: sensor) else { return } + pollers.removeValue(forKey: kind)?.stop() + } + + public func isActive(_ sensor: Int32) -> Bool { + MotionSensor(rawValue: sensor).map { pollers[$0] != nil } ?? false + } + + public func minimumInterval(_ sensor: Int32) -> Double { + guard let kind = MotionSensor(rawValue: sensor), let channels = Self.channels(kind) else { return Self.fastest } + return Self.minimumInterval(channels) + } + + // MARK: Sensors + + /// The channels `sensor` reads, each its own; `nil` without them. + static func channels(_ sensor: MotionSensor) -> [IIOChannel]? { + let kinds: [IIOSensors.Kind] = switch sensor { + case .accelerometer: [.accelerometer] + case .gyroscope: [.gyroscope] + case .magnetometer: [.magnetometer] + case .deviceMotion: [.accelerometer, .gyroscope] + } + let channels = kinds.compactMap { sensors.channel($0) } + return channels.count == kinds.count ? channels : nil + } + + static func minimumInterval(_ channels: [IIOChannel]) -> Double { + channels.compactMap(\.minimumInterval).reduce(fastest, max) + } + + private func poller(_ kind: MotionSensor, _ channels: [IIOChannel], interval: Double) -> any Stoppable { + let fail: (Int32) -> Void = { [weak self] error in + guard let self else { return } + self.pollers[kind] = nil + let code: MotionError = error == ENOENT || error == ENODEV ? .unavailable : .unknown + HostLog.error("motion: can't read \(channels.map(\.device)): \(String(cString: strerror(error)))") + self.delegate.didFail(self, sensor: kind.rawValue, error: code.rawValue) + } + let channel = channels[0] + switch kind { + case .accelerometer, .gyroscope, .magnetometer: + return SensorPoller(interval: interval, read: { + channel.read().map { ($0, bootNanoseconds()) } + }, deliver: { [weak self] reading in + self?.deliver(kind, reading.0, timestamp: reading.1) + }, fail: fail) + case .deviceMotion: + let gyroscope = channels[1] + var fusion = MotionFusion() + return SensorPoller(interval: interval, read: { + channel.read().flatMap { acceleration in + gyroscope.read().map { rotation in + fusion.update(acceleration: acceleration, rotationRate: rotation, timestamp: bootNanoseconds()) + } + } + }, deliver: { [weak self] sample in + self?.deliver(sample) + }, fail: fail) + } + } + + private func deliver(_ kind: MotionSensor, _ v: [Double], timestamp: Int64) { + switch kind { + case .accelerometer: + delegate.didUpdateAcceleration(self, x: v[0], y: v[1], z: v[2], timestamp: timestamp) + case .gyroscope: + delegate.didUpdateRotationRate(self, x: v[0], y: v[1], z: v[2], timestamp: timestamp) + case .magnetometer: + delegate.didUpdateMagneticField(self, x: v[0], y: v[1], z: v[2], accuracy: MagneticFieldAccuracy.uncalibrated.rawValue, + timestamp: timestamp) + case .deviceMotion: + break + } + } + + private func deliver(_ sample: MotionFusion.Sample) { + let (q, g, a, r) = (sample.attitude, sample.gravity, sample.userAcceleration, sample.rotationRate) + delegate.didUpdateDeviceMotion( + self, + attitudeX: q.x, attitudeY: q.y, attitudeZ: q.z, attitudeW: q.w, + gravityX: g[0], gravityY: g[1], gravityZ: g[2], + userAccelerationX: a[0], userAccelerationY: a[1], userAccelerationZ: a[2], + rotationRateX: r[0], rotationRateY: r[1], rotationRateZ: r[2], + timestamp: sample.timestamp + ) + } +} + +/// A poller, whatever it reads. +protocol Stoppable: AnyObject { + func stop() +} + +extension SensorPoller: Stoppable { } diff --git a/Sources/LinuxMotion/LinuxMotionServices.swift b/Sources/LinuxMotion/LinuxMotionServices.swift new file mode 100644 index 0000000..f769366 --- /dev/null +++ b/Sources/LinuxMotion/LinuxMotionServices.swift @@ -0,0 +1,97 @@ +import DynamicMotion +import DynamicRuntime +import LinuxHost + +/// The `Pedometer` contract where there's nothing to count steps: Linux +/// has no step counter or service for one. It's `authorized`, since nothing +/// asks, and every count fails with `unavailable`, so an app written for +/// phones runs and hears why. Main loop only. +public final class LinuxPedometer: Pedometer { + + let delegate: any PedometerDelegate + + init(delegate: any PedometerDelegate) { + self.delegate = delegate + } + + public static func isStepCountingAvailable() -> Bool { false } + + public static func isDistanceAvailable() -> Bool { false } + + public static func isFloorCountingAvailable() -> Bool { false } + + public static func isHistoryAvailable() -> Bool { false } + + public static func authorizationStatus() -> Int32 { + MotionAuthorization.authorized.rawValue + } + + public static func make(_ delegate: any PedometerDelegate) -> LinuxPedometer { + LinuxPedometer(delegate: delegate) + } + + public func requestAuthorization() { + later { $0.delegate.didChangeAuthorization($0, status: MotionAuthorization.authorized.rawValue) } + } + + public func startUpdates(from start: Int64) { + later { $0.delegate.didFail($0, error: MotionError.unavailable.rawValue) } + } + + public func stopUpdates() { } + + public func query(from start: Int64, to end: Int64) { + later { + $0.delegate.didQuery($0, steps: -1, distance: .nan, floorsAscended: -1, floorsDescended: -1, start: start, end: end, + error: MotionError.unavailable.rawValue) + } + } + + private func later(_ body: @escaping (LinuxPedometer) -> Void) { + MainLoop.shared.post { [weak self] in + if let self { + body(self) + } + } + } +} + +/// The `ActivityRecognizer` contract where nothing recognizes activities: +/// unavailable, as on Android without Play services. It's `authorized`, +/// and starting fails with `unavailable`. Main loop only. +public final class LinuxActivityRecognizer: ActivityRecognizer { + + let delegate: any ActivityRecognizerDelegate + + init(delegate: any ActivityRecognizerDelegate) { + self.delegate = delegate + } + + public static func isAvailable() -> Bool { false } + + public static func authorizationStatus() -> Int32 { + MotionAuthorization.authorized.rawValue + } + + public static func make(_ delegate: any ActivityRecognizerDelegate) -> LinuxActivityRecognizer { + LinuxActivityRecognizer(delegate: delegate) + } + + public func requestAuthorization() { + later { $0.delegate.didChangeAuthorization($0, status: MotionAuthorization.authorized.rawValue) } + } + + public func startUpdates() { + later { $0.delegate.didFail($0, error: MotionError.unavailable.rawValue) } + } + + public func stopUpdates() { } + + private func later(_ body: @escaping (LinuxActivityRecognizer) -> Void) { + MainLoop.shared.post { [weak self] in + if let self { + body(self) + } + } + } +} diff --git a/Sources/LinuxMotion/MotionFusion.swift b/Sources/LinuxMotion/MotionFusion.swift new file mode 100644 index 0000000..1a76b43 --- /dev/null +++ b/Sources/LinuxMotion/MotionFusion.swift @@ -0,0 +1,104 @@ +import DynamicMotion +import Foundation + +/// Device motion from an accelerometer and a gyroscope: a Mahony filter, +/// which integrates the rotation rate and pulls the attitude toward the +/// gravity the accelerometer measures. +/// +/// The attitude rotates device coordinates into a frame with z vertical +/// and an x fixed where the device's x pointed when it started, as +/// Android's game rotation vector does; without a magnetometer, nothing +/// corrects drift around the vertical. Gravity is the vertical, back in the +/// device's axes, in the accelerometer's sign (z ≈ +9.81 face up), and user +/// acceleration what's left of the acceleration without it. +public struct MotionFusion { + + /// A unit quaternion. + public struct Quaternion: Equatable, Sendable { + public var x, y, z, w: Double + + public init(x: Double, y: Double, z: Double, w: Double) { + (self.x, self.y, self.z, self.w) = (x, y, z, w) + } + + public static let identity = Quaternion(x: 0, y: 0, z: 0, w: 1) + + var normalized: Quaternion { + let length = (x * x + y * y + z * z + w * w).squareRoot() + guard length > 0 else { return .identity } + return Quaternion(x: x / length, y: y / length, z: z / length, w: w / length) + } + + /// The reference frame's vertical, in device coordinates: the third + /// row of the rotation. + var vertical: [Double] { + [2 * (x * z - w * y), 2 * (w * x + y * z), w * w - x * x - y * y + z * z] + } + } + + public struct Sample: Equatable, Sendable { + public var attitude: Quaternion + public var gravity: [Double] + public var userAcceleration: [Double] + public var rotationRate: [Double] + public var timestamp: Int64 + } + + /// How hard the accelerometer pulls the attitude, per second. + public var gain = 1.0 + + public private(set) var attitude: Quaternion? + + private var last: Int64? + + public init() { } + + /// The device motion of one acceleration (m/s²) and rotation rate + /// (rad/s) read together at `timestamp` (nanoseconds). + public mutating func update(acceleration: [Double], rotationRate: [Double], timestamp: Int64) -> Sample { + let length = (acceleration[0] * acceleration[0] + acceleration[1] * acceleration[1] + + acceleration[2] * acceleration[2]).squareRoot() + var q = attitude ?? Self.level(acceleration, length: length) + if attitude != nil, let last, timestamp > last { + let dt = min(Double(timestamp - last) / 1e9, 0.5) + var rate = rotationRate + if length > 0 { + // The error between the measured and the estimated + // vertical, as a rotation that closes it. + let a = acceleration.map { $0 / length } + let v = q.vertical + let error = [a[1] * v[2] - a[2] * v[1], a[2] * v[0] - a[0] * v[2], a[0] * v[1] - a[1] * v[0]] + rate = zip(rate, error).map { $0 + gain * $1 } + } + let (gx, gy, gz) = (rate[0] * dt / 2, rate[1] * dt / 2, rate[2] * dt / 2) + q = Quaternion( + x: q.x + q.w * gx + q.y * gz - q.z * gy, + y: q.y + q.w * gy - q.x * gz + q.z * gx, + z: q.z + q.w * gz + q.x * gy - q.y * gx, + w: q.w - q.x * gx - q.y * gy - q.z * gz + ).normalized + } + attitude = q + last = timestamp + let gravity = q.vertical.map { $0 * standardGravity } + return Sample( + attitude: q, + gravity: gravity, + userAcceleration: zip(acceleration, gravity).map { $0 - $1 }, + rotationRate: rotationRate, + timestamp: timestamp + ) + } + + /// The attitude that turns `acceleration` to the vertical with the + /// least rotation, so x stays as level as it can. + static func level(_ acceleration: [Double], length: Double) -> Quaternion { + guard length > 0 else { return .identity } + let a = acceleration.map { $0 / length } + // The rotation from a to z: about a × z, by the angle between them. + if a[2] < -0.999999 { + return Quaternion(x: 1, y: 0, z: 0, w: 0) + } + return Quaternion(x: a[1], y: -a[0], z: 0, w: 1 + a[2]).normalized + } +} diff --git a/Sources/LinuxMotion/SensorPoller.swift b/Sources/LinuxMotion/SensorPoller.swift new file mode 100644 index 0000000..5bec505 --- /dev/null +++ b/Sources/LinuxMotion/SensorPoller.swift @@ -0,0 +1,73 @@ +import Dispatch +import Glibc +import LinuxHost + +/// Reads a sensor every `interval` seconds, off the main thread (a driver +/// may take a bus transaction to answer), and hands each reading to the +/// main loop until it's stopped. +/// +/// A busy driver skips the reading; any other failure stops the poller and +/// is handed over once, as `errno`. +final class SensorPoller { + + let interval: Double + + private var timer: DispatchSourceTimer? + + /// Main loop only. + private(set) var isStopped = false + + init( + interval: Double, + read: @escaping () -> Result, + deliver: @escaping (Reading) -> Void, + fail: @escaping (Int32) -> Void + ) { + self.interval = interval + let timer = DispatchSource.makeTimerSource(queue: motionQueue) + self.timer = timer + timer.setEventHandler { [weak self] in + switch read() { + case .success(let reading): + MainLoop.shared.post { + guard let self, !self.isStopped else { return } + deliver(reading) + } + case .failure(.busy): + break + case .failure(.failed(let error)): + // Stopped on the main loop; a reading meanwhile fails the + // same way, and isn't handed over. + MainLoop.shared.post { + guard let self, !self.isStopped else { return } + self.stop() + fail(error) + } + } + } + timer.schedule(deadline: .now(), repeating: .nanoseconds(Int(interval * 1e9)), leeway: .milliseconds(1)) + timer.resume() + } + + deinit { + timer?.cancel() + } + + /// No reading is delivered after this. Main loop only. + func stop() { + isStopped = true + timer?.cancel() + timer = nil + } +} + +/// Nanoseconds since boot, counting time asleep, as the contract's +/// timestamps are. +func bootNanoseconds() -> Int64 { + var time = timespec() + clock_gettime(CLOCK_BOOTTIME, &time) + return Int64(time.tv_sec) * 1_000_000_000 + Int64(time.tv_nsec) +} + +/// Every poller's reads, one at a time. +private let motionQueue = DispatchQueue(label: "linux-app-host.motion") diff --git a/Sources/LinuxPackager/Validator.swift b/Sources/LinuxPackager/Validator.swift index 158d243..5ebe06b 100644 --- a/Sources/LinuxPackager/Validator.swift +++ b/Sources/LinuxPackager/Validator.swift @@ -6,6 +6,7 @@ import LinuxDevice import LinuxDocuments import LinuxGraphics import LinuxLocation +import LinuxMotion import LinuxWebKit import LinuxHost import DynamicUI @@ -19,11 +20,11 @@ public enum HostContracts { /// The modules `linux-app-host` registers (`HostApp.modules`): the /// player's contracts, without building the player, Bluetooth, /// graphics, web views, files, settings, model stores, formatting, HTTP, - /// the device, location and documents. + /// the device, location, documents and motion. nonisolated(unsafe) public static let modules: [any HostModule.Type] = [ PlayerContracts.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, + LinuxDocuments.self, LinuxMotion.self, ] public static var provided: [String: ContractDescriptor] { @@ -32,8 +33,9 @@ public enum HostContracts { /// Capabilities some contract here serves: `network` is what lets an /// HTTP session or a web view's page reach the network, `location` - /// GeoClue's, and `userFiles` the documents' pickers. - public static let capabilities: Set = [.bluetooth, .graphics, .network, .location, .userFiles] + /// GeoClue's, `userFiles` the documents' pickers, and `motion` the + /// altimeter, which asks nothing. + public static let capabilities: Set = [.bluetooth, .graphics, .network, .location, .userFiles, .motion] } /// The checks of `Packager.md` §1, which install makes before it copies an diff --git a/Tests/LinuxDeviceTests/SensorProxyTests.swift b/Tests/LinuxDeviceTests/SensorProxyTests.swift new file mode 100644 index 0000000..0bbcc79 --- /dev/null +++ b/Tests/LinuxDeviceTests/SensorProxyTests.swift @@ -0,0 +1,186 @@ +import DBus +import DynamicDevice +import Foundation +import LinuxDBus +import LinuxHost +import Testing +@testable import LinuxDevice + +/// Plays iio-sensor-proxy: answers on the main loop, as the bus does, and +/// records the methods called. +final class FakeSensorProxy: SensorProxyBus { + + var properties: [String: DBusMessageArgument] + + /// Fails every call, as the bus does without the proxy. + var error: BusError? + + private(set) var calls: [String] = [] + + private var handlers: [UInt64: ([String: DBusMessageArgument]) -> Void] = [:] + + private var next: UInt64 = 0 + + init(_ properties: [String: DBusMessageArgument] = [:]) { + self.properties = properties + } + + var subscribers: Int { handlers.count } + + func call(_ method: String, reply: @escaping (Result) -> Void) { + calls.append(method) + let answer: Result = error.map { .failure($0) } ?? .success(()) + MainLoop.shared.post { reply(answer) } + } + + func properties(reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) { + let answer: Result<[String: DBusMessageArgument], BusError> = error.map { .failure($0) } ?? .success(properties) + MainLoop.shared.post { reply(answer) } + } + + func propertyAndWait(_ name: String) -> Result { + if let error { + return .failure(error) + } + return properties[name].map { .success($0) } ?? .failure(BusError(name: "org.freedesktop.DBus.Error.UnknownProperty")) + } + + func subscribeToChanges(_ handler: @escaping ([String: DBusMessageArgument]) -> Void) -> BusSubscription { + next += 1 + handlers[next] = handler + return BusSubscription(id: next) + } + + func unsubscribe(_ subscription: BusSubscription) { + handlers[subscription.id] = nil + } + + /// The proxy's properties change. + func change(_ changed: [String: DBusMessageArgument]) { + properties.merge(changed) { $1 } + MainLoop.shared.post { [handlers] in + for id in handlers.keys.sorted() { + handlers[id]?(changed) + } + } + } +} + +extension LinuxDeviceTests { + + func withProxy(_ proxy: FakeSensorProxy, _ body: (LinuxDevice, RecordingDelegate) throws -> Void) rethrows { + LinuxDevice.reset() + let previous = LinuxDevice.sensorProxy + LinuxDevice.sensorProxy = proxy + defer { + LinuxDevice.reset() + LinuxDevice.sensorProxy = previous + } + let device = LinuxDevice.current() + let delegate = RecordingDelegate() + device.setDelegate(delegate) + defer { device.setDelegate(nil) } + try body(device, delegate) + } + + @Test func orientationNames() { + #expect(SensorProxy.orientation("normal") == .portrait) + #expect(SensorProxy.orientation("bottom-up") == .portraitUpsideDown) + // The left edge up has the top to the right. + #expect(SensorProxy.orientation("left-up") == .landscapeRight) + #expect(SensorProxy.orientation("right-up") == .landscapeLeft) + #expect(SensorProxy.orientation("undefined") == .unknown) + } + + @Test func orientationComesFromTheProxysAccelerometer() { + let proxy = FakeSensorProxy(["HasAccelerometer": .boolean(true), "AccelerometerOrientation": .string("right-up")]) + withProxy(proxy) { device, delegate in + #expect(device.orientation() == DeviceOrientation.unknown.rawValue, "unknown until enabled") + device.setOrientationUpdatesEnabled(true) + MainLoop.shared.drain() + #expect(proxy.calls == ["ClaimAccelerometer"]) + #expect(device.orientation() == DeviceOrientation.landscapeLeft.rawValue) + #expect(delegate.events == ["orientation \(DeviceOrientation.landscapeLeft.rawValue)"]) + + delegate.events = [] + proxy.change(["AccelerometerOrientation": .string("normal")]) + proxy.change(["AccelerometerOrientation": .string("normal"), "LightLevel": .double(3)]) + MainLoop.shared.drain() + #expect(delegate.events == ["orientation \(DeviceOrientation.portrait.rawValue)"], "each change once") + + device.setOrientationUpdatesEnabled(false) + MainLoop.shared.drain() + #expect(proxy.calls == ["ClaimAccelerometer", "ReleaseAccelerometer"]) + #expect(device.orientation() == DeviceOrientation.unknown.rawValue) + #expect(proxy.subscribers == 0) + } + } + + @Test func orientationStaysUnknownWithoutAnAccelerometer() { + let proxy = FakeSensorProxy(["HasAccelerometer": .boolean(false), "AccelerometerOrientation": .string("undefined")]) + withProxy(proxy) { device, delegate in + device.setOrientationUpdatesEnabled(true) + MainLoop.shared.drain() + #expect(proxy.calls.isEmpty, "nothing to claim") + #expect(device.orientation() == DeviceOrientation.unknown.rawValue) + #expect(delegate.events.isEmpty) + } + // Nor without the proxy. + let missing = FakeSensorProxy() + missing.error = BusError(name: "org.freedesktop.DBus.Error.ServiceUnknown") + withProxy(missing) { device, delegate in + device.setOrientationUpdatesEnabled(true) + MainLoop.shared.drain() + #expect(device.orientation() == DeviceOrientation.unknown.rawValue) + #expect(delegate.events.isEmpty) + } + } + + @Test func disablingBeforeTheClaimReleasesIt() { + let proxy = FakeSensorProxy(["HasAccelerometer": .boolean(true), "AccelerometerOrientation": .string("normal")]) + withProxy(proxy) { device, delegate in + device.setOrientationUpdatesEnabled(true) + device.setOrientationUpdatesEnabled(false) + MainLoop.shared.drain() + #expect(proxy.calls.isEmpty, "turned off before the proxy answered") + #expect(delegate.events.isEmpty) + } + } + + @Test func proximityComesFromTheProxysSensor() { + let proxy = FakeSensorProxy(["HasProximity": .boolean(true), "ProximityNear": .boolean(false)]) + withProxy(proxy) { device, delegate in + device.setProximityMonitoringEnabled(true) + #expect(device.isProximityMonitoringEnabled()) + MainLoop.shared.drain() + #expect(proxy.calls == ["ClaimProximity"]) + #expect(!device.proximityState()) + + proxy.change(["ProximityNear": .boolean(true)]) + MainLoop.shared.drain() + #expect(device.proximityState()) + #expect(delegate.events == ["proximity true"]) + + device.setProximityMonitoringEnabled(false) + MainLoop.shared.drain() + #expect(!device.isProximityMonitoringEnabled() && !device.proximityState()) + #expect(proxy.calls == ["ClaimProximity", "ReleaseProximity"]) + } + } + + @Test func proximityStaysOffWithoutASensor() { + let proxy = FakeSensorProxy(["HasProximity": .boolean(false)]) + withProxy(proxy) { device, _ in + device.setProximityMonitoringEnabled(true) + #expect(!device.isProximityMonitoringEnabled()) + MainLoop.shared.drain() + #expect(proxy.calls.isEmpty) + } + let missing = FakeSensorProxy() + missing.error = BusError(name: "org.freedesktop.DBus.Error.ServiceUnknown") + withProxy(missing) { device, _ in + device.setProximityMonitoringEnabled(true) + #expect(!device.isProximityMonitoringEnabled()) + } + } +} diff --git a/Tests/LinuxMotionTests/LinuxMotionTests.swift b/Tests/LinuxMotionTests/LinuxMotionTests.swift new file mode 100644 index 0000000..8352005 --- /dev/null +++ b/Tests/LinuxMotionTests/LinuxMotionTests.swift @@ -0,0 +1,408 @@ +import DynamicMotion +import DynamicRuntime +import Foundation +import LinuxHost +import Testing +@testable import LinuxMotion + +/// IIO devices' attributes, laid out under a temporary root as sysfs has +/// them. +struct FakeIIO { + + let root = FileManager.default.temporaryDirectory.appendingPathComponent("iio-\(UUID().uuidString)").path + + /// Writes in place, in one write of a fixed length, so a reading + /// meanwhile sees the old value or the new one, as sysfs gives them. + func write(_ device: Int, _ name: String, _ text: String) throws { + let directory = root + "/iio:device\(device)" + try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true) + let path = directory + "/" + name + if !FileManager.default.fileExists(atPath: path) { + FileManager.default.createFile(atPath: path, contents: nil) + } + let padded = (text + "\n").padding(toLength: 48, withPad: " ", startingAt: 0) + let file = try #require(FileHandle(forWritingAtPath: path)) + defer { try? file.close() } + try file.write(contentsOf: Data(padded.utf8)) + } + + var sensors: IIOSensors { IIOSensors(root: root) } + + /// An accelerometer lying face up, read in counts of 1/1024 g; a + /// gyroscope at rest; both on one chip, as an IMU has them. + static func imu() throws -> FakeIIO { + let iio = FakeIIO() + try iio.write(0, "name", "bmi260") + for (axis, value) in [("x", "0"), ("y", "0"), ("z", "1024")] { + try iio.write(0, "in_accel_\(axis)_raw", value) + try iio.write(0, "in_anglvel_\(axis)_raw", "0") + } + try iio.write(0, "in_accel_scale", "\(standardGravity / 1024)") + try iio.write(0, "in_anglvel_scale", "0.001") + try iio.write(0, "in_accel_sampling_frequency_available", "12.5 25 50 100 200") + return iio + } +} + +/// Records what the manager tells its delegate. +final class RecordingMotionDelegate: MotionManagerDelegate { + + var accelerations: [[Double]] = [] + var rotations: [[Double]] = [] + var fields: [([Double], Int32)] = [] + var motions: [(attitude: [Double], gravity: [Double], user: [Double])] = [] + var timestamps: [Int64] = [] + var failures: [(sensor: Int32, error: Int32)] = [] + + func didUpdateAcceleration(_ manager: any MotionManager, x: Double, y: Double, z: Double, timestamp: Int64) { + accelerations.append([x, y, z]) + timestamps.append(timestamp) + } + + func didUpdateRotationRate(_ manager: any MotionManager, x: Double, y: Double, z: Double, timestamp: Int64) { + rotations.append([x, y, z]) + } + + func didUpdateMagneticField(_ manager: any MotionManager, x: Double, y: Double, z: Double, accuracy: Int32, timestamp: Int64) { + fields.append(([x, y, z], accuracy)) + } + + func didUpdateDeviceMotion( + _ manager: any MotionManager, + attitudeX: Double, attitudeY: Double, attitudeZ: Double, attitudeW: Double, + gravityX: Double, gravityY: Double, gravityZ: Double, + userAccelerationX: Double, userAccelerationY: Double, userAccelerationZ: Double, + rotationRateX: Double, rotationRateY: Double, rotationRateZ: Double, + timestamp: Int64 + ) { + motions.append(([attitudeX, attitudeY, attitudeZ, attitudeW], [gravityX, gravityY, gravityZ], + [userAccelerationX, userAccelerationY, userAccelerationZ])) + } + + func didFail(_ manager: any MotionManager, sensor: Int32, error: Int32) { + failures.append((sensor, error)) + } +} + +final class RecordingAltimeterDelegate: AltimeterDelegate { + + var statuses: [Int32] = [] + var samples: [(pressure: Double, altitude: Double)] = [] + var failures: [Int32] = [] + + func didChangeAuthorization(_ altimeter: any Altimeter, status: Int32) { statuses.append(status) } + func didUpdate(_ altimeter: any Altimeter, pressure: Double, relativeAltitude: Double, timestamp: Int64) { + samples.append((pressure, relativeAltitude)) + } + func didFail(_ altimeter: any Altimeter, error: Int32) { failures.append(error) } +} + +final class RecordingPedometerDelegate: PedometerDelegate { + + var events: [String] = [] + + func didChangeAuthorization(_ pedometer: any Pedometer, status: Int32) { events.append("status \(status)") } + func didUpdate(_ pedometer: any Pedometer, steps: Int64, distance: Double, floorsAscended: Int32, floorsDescended: Int32, + start: Int64, end: Int64) { events.append("update") } + func didQuery(_ pedometer: any Pedometer, steps: Int64, distance: Double, floorsAscended: Int32, floorsDescended: Int32, + start: Int64, end: Int64, error: Int32) { events.append("query \(steps) \(start) \(end) \(error)") } + func didFail(_ pedometer: any Pedometer, error: Int32) { events.append("fail \(error)") } +} + +final class RecordingActivityDelegate: ActivityRecognizerDelegate { + + var events: [String] = [] + + func didChangeAuthorization(_ recognizer: any ActivityRecognizer, status: Int32) { events.append("status \(status)") } + func didUpdateActivity(_ recognizer: any ActivityRecognizer, activity: Int32, confidence: Int32, timestamp: Int64) { + events.append("activity") + } + func didFail(_ recognizer: any ActivityRecognizer, error: Int32) { events.append("fail \(error)") } +} + +func isClose(_ a: [Double], _ b: [Double], within tolerance: Double = 1e-6) -> Bool { + a.count == b.count && zip(a, b).allSatisfy { abs($0 - $1) <= tolerance } +} + +/// `LinuxMotionManager.sensors` is every test's, so one at a time. +@Suite(.serialized) struct LinuxMotionTests { + + func with(_ iio: FakeIIO, _ body: () throws -> Void) rethrows { + let previous = LinuxMotionManager.sensors + LinuxMotionManager.sensors = iio.sensors + defer { LinuxMotionManager.sensors = previous } + try body() + } + + /// Runs the main loop until `done`, for up to five seconds: a timer + /// wakes it then, since nothing else may. + func run(until done: () -> Bool) { + var expired = false + let timer = MainLoop.shared.schedule(after: 5_000_000_000) { expired = true } + defer { MainLoop.shared.cancel(timer) } + MainLoop.shared.run { done() || expired } + } + + // MARK: IIO + + @Test func channelsReadScaledValuesInTheDevicesAxes() throws { + let iio = try FakeIIO.imu() + // Mounted turned a quarter: the sensor's x is the device's y. + try iio.write(0, "in_accel_mount_matrix", "0, -1, 0; 1, 0, 0; 0, 0, 1") + try iio.write(0, "in_accel_x_raw", "512") + let channel = try #require(iio.sensors.channel(.accelerometer)) + #expect(channel.name == "bmi260") + let values = try channel.read().get() + #expect(isClose(values, [0, standardGravity / 2, standardGravity])) + #expect(channel.minimumInterval == 1.0 / 200) + + // Read again from the start of each file. + try iio.write(0, "in_accel_x_raw", "-1024") + #expect(isClose(try channel.read().get(), [0, -standardGravity, standardGravity])) + } + + @Test func inputsOffsetsAndUnits() throws { + let iio = FakeIIO() + // A magnetometer giving processed gauss, per axis. + try iio.write(1, "in_magn_x_input", "0.25") + try iio.write(1, "in_magn_y_input", "-0.1") + try iio.write(1, "in_magn_z_input", "0.4") + try iio.write(1, "in_magn_x_scale", "1000") + // A barometer with an offset, in kPa. + try iio.write(2, "in_pressure_raw", "1000") + try iio.write(2, "in_pressure_offset", "13.25") + try iio.write(2, "in_pressure_scale", "0.1") + // Neither has the other's channels, nor an accelerometer. + #expect(iio.sensors.channel(.accelerometer) == nil) + let magnetometer = try #require(iio.sensors.channel(.magnetometer)) + #expect(isClose(try magnetometer.read().get(), [25, -10, 40]), "µT; an input is already scaled") + #expect(magnetometer.minimumInterval == nil) + let barometer = try #require(iio.sensors.channel(.barometer)) + #expect(isClose(try barometer.read().get(), [101.325])) + + try iio.write(2, "in_pressure_raw", "not a number") + #expect(barometer.read() == .failure(.failed(EINVAL))) + } + + @Test func theFirstDeviceWithTheChannels() throws { + let iio = FakeIIO() + for device in [10, 2] { + for axis in ["x", "y", "z"] { + try iio.write(device, "in_accel_\(axis)_raw", "\(device)") + } + } + // Device 10 sorts after 2 by number, not by name. + #expect(try iio.sensors.channel(.accelerometer)?.read().get() == [2, 2, 2]) + #expect(IIOChannel.matrix("1, 0; 0, 1") == nil) + } + + // MARK: Fusion + + @Test func fusionStartsLevelWithGravity() { + for acceleration in [[0, 0, standardGravity], [3, -4, 8], [0, 0, -standardGravity], [standardGravity, 0, 0]] { + var fusion = MotionFusion() + let sample = fusion.update(acceleration: acceleration, rotationRate: [0, 0, 0], timestamp: 0) + let length = (acceleration.map { $0 * $0 }.reduce(0, +)).squareRoot() + #expect(isClose(sample.gravity, acceleration.map { $0 / length * standardGravity }), "gravity along \(acceleration)") + let q = sample.attitude + #expect(abs(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w - 1) < 1e-9) + } + } + + @Test func fusionIntegratesTheRotationRate() { + var fusion = MotionFusion() + let rest = [0, 0, standardGravity] + _ = fusion.update(acceleration: rest, rotationRate: [0, 0, 0], timestamp: 0) + // A quarter turn about the vertical in a second. + var sample = fusion.update(acceleration: rest, rotationRate: [0, 0, 0], timestamp: 0) + for step in 1...100 { + sample = fusion.update(acceleration: rest, rotationRate: [0, 0, .pi / 2], timestamp: Int64(step) * 10_000_000) + } + let half = Double.pi / 4 + #expect(isClose([sample.attitude.x, sample.attitude.y, sample.attitude.z, sample.attitude.w], [0, 0, sin(half), cos(half)], + within: 1e-3)) + #expect(isClose(sample.gravity, rest, within: 1e-6), "still level") + #expect(isClose(sample.userAcceleration, [0, 0, 0], within: 1e-6)) + #expect(sample.rotationRate == [0, 0, .pi / 2]) + } + + @Test func fusionFollowsGravityBack() { + var fusion = MotionFusion() + _ = fusion.update(acceleration: [0, 0, standardGravity], rotationRate: [0, 0, 0], timestamp: 0) + // Tipped onto its side with no rotation seen: the accelerometer + // pulls the attitude over. + let side = [0, standardGravity, 0] + var sample = fusion.update(acceleration: side, rotationRate: [0, 0, 0], timestamp: 0) + for step in 1...2000 { + sample = fusion.update(acceleration: side, rotationRate: [0, 0, 0], timestamp: Int64(step) * 10_000_000) + } + #expect(isClose(sample.gravity, side, within: 1e-3)) + } + + // MARK: MotionManager + + @Test func availability() throws { + let imu = try FakeIIO.imu() + try with(imu) { + #expect(LinuxMotionManager.isAvailable(MotionSensor.accelerometer.rawValue)) + #expect(LinuxMotionManager.isAvailable(MotionSensor.gyroscope.rawValue)) + #expect(LinuxMotionManager.isAvailable(MotionSensor.deviceMotion.rawValue)) + #expect(!LinuxMotionManager.isAvailable(MotionSensor.magnetometer.rawValue)) + #expect(!LinuxMotionManager.isAvailable(99)) + let manager = LinuxMotionManager.make(RecordingMotionDelegate()) + #expect(manager.minimumInterval(MotionSensor.accelerometer.rawValue) == 0.01, "no faster than 100 Hz") + try imu.write(0, "in_accel_sampling_frequency_available", "12.5 25") + #expect(manager.minimumInterval(MotionSensor.accelerometer.rawValue) == 0.04) + #expect(manager.minimumInterval(MotionSensor.deviceMotion.rawValue) == 0.04) + } + try with(FakeIIO()) { + #expect(!LinuxMotionManager.isAvailable(MotionSensor.accelerometer.rawValue)) + #expect(!LinuxMotionManager.isAvailable(MotionSensor.deviceMotion.rawValue)) + } + } + + @Test func samplesReachTheDelegate() throws { + try with(try FakeIIO.imu()) { + let delegate = RecordingMotionDelegate() + let manager = LinuxMotionManager.make(delegate) + manager.start(MotionSensor.accelerometer.rawValue, interval: 0) + manager.start(MotionSensor.deviceMotion.rawValue, interval: 0.02) + #expect(manager.isActive(MotionSensor.accelerometer.rawValue)) + run { delegate.accelerations.count >= 3 && delegate.motions.count >= 2 } + #expect(delegate.accelerations.count >= 3) + #expect(isClose(delegate.accelerations[0], [0, 0, standardGravity])) + #expect(delegate.timestamps == delegate.timestamps.sorted() && delegate.timestamps[0] > 0) + let motion = try #require(delegate.motions.first) + #expect(isClose(motion.gravity, [0, 0, standardGravity]) && isClose(motion.user, [0, 0, 0])) + #expect(isClose(motion.attitude, [0, 0, 0, 1])) + + manager.stop(MotionSensor.accelerometer.rawValue) + manager.stop(MotionSensor.deviceMotion.rawValue) + #expect(!manager.isActive(MotionSensor.accelerometer.rawValue)) + let count = delegate.accelerations.count + var waited = false + MainLoop.shared.schedule(after: 100_000_000) { waited = true } + MainLoop.shared.run { waited } + #expect(delegate.accelerations.count == count, "nothing after stop") + #expect(delegate.failures.isEmpty) + } + } + + @Test func aMissingSensorFails() throws { + try with(try FakeIIO.imu()) { + let delegate = RecordingMotionDelegate() + let manager = LinuxMotionManager.make(delegate) + manager.start(MotionSensor.magnetometer.rawValue, interval: 0.1) + #expect(!manager.isActive(MotionSensor.magnetometer.rawValue)) + run { !delegate.failures.isEmpty } + #expect(delegate.failures.map(\.sensor) == [MotionSensor.magnetometer.rawValue]) + #expect(delegate.failures.map(\.error) == [MotionError.unavailable.rawValue]) + } + } + + @Test func anUnreadableSensorStops() throws { + let imu = try FakeIIO.imu() + try with(imu) { + let delegate = RecordingMotionDelegate() + let manager = LinuxMotionManager.make(delegate) + manager.start(MotionSensor.gyroscope.rawValue, interval: 0.01) + run { !delegate.rotations.isEmpty } + try imu.write(0, "in_anglvel_y_raw", "garbage") + run { !delegate.failures.isEmpty } + #expect(delegate.failures.map(\.error) == [MotionError.unknown.rawValue]) + #expect(!manager.isActive(MotionSensor.gyroscope.rawValue)) + } + } + + @Test func magneticFieldIsUncalibrated() throws { + let iio = FakeIIO() + for axis in ["x", "y", "z"] { + try iio.write(0, "in_magn_\(axis)_raw", "1") + } + try iio.write(0, "in_magn_scale", "0.5") + try with(iio) { + let delegate = RecordingMotionDelegate() + let manager = LinuxMotionManager.make(delegate) + manager.start(MotionSensor.magnetometer.rawValue, interval: 0.01) + run { !delegate.fields.isEmpty } + manager.stop(MotionSensor.magnetometer.rawValue) + let field = try #require(delegate.fields.first) + #expect(isClose(field.0, [50, 50, 50])) + #expect(field.1 == MagneticFieldAccuracy.uncalibrated.rawValue) + } + } + + // MARK: Altimeter + + @Test func altitudeFromPressure() throws { + let iio = FakeIIO() + try iio.write(3, "in_pressure_input", "101.325") + try with(iio) { + #expect(LinuxAltimeter.isAvailable()) + #expect(LinuxAltimeter.authorizationStatus() == MotionAuthorization.authorized.rawValue) + LinuxAltimeter.interval = 0.01 + defer { LinuxAltimeter.interval = 1 } + let delegate = RecordingAltimeterDelegate() + let altimeter = LinuxAltimeter.make(delegate) + altimeter.requestAuthorization() + altimeter.startUpdates() + run { !delegate.samples.isEmpty } + #expect(delegate.statuses == [MotionAuthorization.authorized.rawValue]) + #expect(delegate.samples.first.map { isClose([$0.pressure, $0.altitude], [101.325, 0]) } == true) + + // About 8.4 m higher per 0.1 kPa near sea level. + try iio.write(3, "in_pressure_input", "101.225") + run { delegate.samples.last?.pressure == 101.225 } + altimeter.stopUpdates() + let altitude = try #require(delegate.samples.last?.altitude) + #expect(abs(altitude - 8.32) < 0.05, "\(altitude)") + #expect(delegate.failures.isEmpty) + } + try with(FakeIIO()) { + #expect(!LinuxAltimeter.isAvailable()) + let delegate = RecordingAltimeterDelegate() + let altimeter = LinuxAltimeter.make(delegate) + altimeter.startUpdates() + run { !delegate.failures.isEmpty } + #expect(delegate.failures == [MotionError.unavailable.rawValue]) + } + } + + // MARK: Pedometer and activity + + @Test func pedometerAndActivityAreUnavailable() { + #expect(!LinuxPedometer.isStepCountingAvailable() && !LinuxPedometer.isHistoryAvailable()) + #expect(!LinuxPedometer.isDistanceAvailable() && !LinuxPedometer.isFloorCountingAvailable()) + #expect(LinuxPedometer.authorizationStatus() == MotionAuthorization.authorized.rawValue) + let pedometer = RecordingPedometerDelegate() + let steps = LinuxPedometer.make(pedometer) + steps.requestAuthorization() + steps.startUpdates(from: 0) + steps.query(from: 10, to: 20) + MainLoop.shared.drain() + let unavailable = MotionError.unavailable.rawValue + #expect(pedometer.events == ["status \(MotionAuthorization.authorized.rawValue)", "fail \(unavailable)", + "query -1 10 20 \(unavailable)"]) + + #expect(!LinuxActivityRecognizer.isAvailable()) + let activity = RecordingActivityDelegate() + let recognizer = LinuxActivityRecognizer.make(activity) + recognizer.requestAuthorization() + recognizer.startUpdates() + MainLoop.shared.drain() + #expect(activity.events == ["status \(MotionAuthorization.authorized.rawValue)", "fail \(unavailable)"]) + } + + // MARK: The module + + @Test func moduleRegistersTheContracts() { + let names = LinuxMotion.contracts.map(\.name) + #expect(names == [ + "org.pureswift.motion.MotionManager", "org.pureswift.motion.MotionManagerDelegate", + "org.pureswift.motion.Altimeter", "org.pureswift.motion.AltimeterDelegate", + "org.pureswift.motion.Pedometer", "org.pureswift.motion.PedometerDelegate", + "org.pureswift.motion.ActivityRecognizer", "org.pureswift.motion.ActivityRecognizerDelegate", + ]) + #expect(LinuxMotion.permissionProviders()[.motion]?.status() == .granted) + } +} diff --git a/Tests/LinuxPackagerTests/PackagerTests.swift b/Tests/LinuxPackagerTests/PackagerTests.swift index 59fd0c6..c3e9652 100644 --- a/Tests/LinuxPackagerTests/PackagerTests.swift +++ b/Tests/LinuxPackagerTests/PackagerTests.swift @@ -33,13 +33,13 @@ import Testing @Test func contractsThisHostLacks() throws { let fixture = try Fixture(contracts: [ - ("org.pureswift.motion.MotionManager", 1, "contract"), + ("org.pureswift.nfc.Reader", 1, "contract"), ("org.pureswift.ui.Renderer", 99, "contract"), ("org.pureswift.ui.RendererDelegate", 1, "contract"), ]) let strict = try diagnostics(fixture) #expect(strict.filter { $0.severity == .error }.map(\.message) == [ - "org.pureswift.motion.MotionManager isn't implemented on Linux", + "org.pureswift.nfc.Reader isn't implemented on Linux", "org.pureswift.ui.RendererDelegate is a different kind of interface on Linux", ]) #expect(strict.contains { $0.severity == .warning && $0.message.contains("Renderer is version") }) @@ -83,6 +83,21 @@ import Testing #expect(try diagnostics(fixture).map(\.message) == []) } + @Test func motionIsImplemented() throws { + let fixture = try Fixture(contracts: [ + ("org.pureswift.ui.Renderer", 1, "contract"), + ("org.pureswift.motion.MotionManager", 1, "contract"), + ("org.pureswift.motion.MotionManagerDelegate", 1, "callback"), + ("org.pureswift.motion.Altimeter", 1, "contract"), + ("org.pureswift.motion.AltimeterDelegate", 1, "callback"), + ("org.pureswift.motion.Pedometer", 1, "contract"), + ("org.pureswift.motion.PedometerDelegate", 1, "callback"), + ("org.pureswift.motion.ActivityRecognizer", 1, "contract"), + ("org.pureswift.motion.ActivityRecognizerDelegate", 1, "callback"), + ], capabilities: ["motion"]) + #expect(try diagnostics(fixture).map(\.message) == []) + } + /// AppRuntime's `RuntimeNetworking`, over `FoundationNetworking`. @Test func networkingIsImplemented() throws { let fixture = try Fixture(contracts: [ @@ -153,8 +168,8 @@ import Testing } @Test func capabilitiesWithoutSupportWarn() throws { - let messages = try diagnostics(Fixture(capabilities: ["bluetooth", "location", "motion"])) - #expect(messages == [.warning("the app declares motion, which the Linux host doesn't support yet")]) + let messages = try diagnostics(Fixture(capabilities: ["bluetooth", "location", "motion", "nfc"])) + #expect(messages == [.warning("the app declares nfc, which the Linux host doesn't support yet")]) } @Test func theHostAndThePackagerAgreeOnModules() {