commit ddc7b2c1d3d5bd5a2f27650c6579289940ea2429
parent 01ca2484e6175af1172fd8c68e8cb85760ef6e07
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 11:19:22 -0500
Optional dive computer built on RemoraKit: home screen, dive band and computer page, alarms, dives handed over to Sub Rascasse, dive information in photo and video metadata
The dive computer is a setting, off by default. Off, the app behaves as
before (housing and camera) and only shows basic dive information; nothing
is recorded. On, after accepting the terms, it is the computer of Open
Rémora (RemoraKit: ZHL-16C with gradient factors), fed by the housing's
external pressure sensor (characteristic 1625, still to be validated
underwater).
- Dive/HousingDepthSource: pure adapter from the sensor to DiveReading
(surface pressure, submerged decision, link loss, plausibility checks).
- Dive/DiveSession, Dive/DiveStore: on/off setting, terms, settings and
logbook in Documents/DiveComputer, real dives dropped as <uuid>.json and
<uuid>.uddf in the app group folder OpenMerou/Dives (docs/SHARING.md),
or in Documents without the container. Simulated dives are never saved.
- Home screen: "Start housing mode", "Simulate a housing", and the dive
computer (gas and conservatism, settings from RemoraUI, last dive,
no-fly time, dives pending for Sub Rascasse).
- Underwater: a dive band over the camera, a full-screen computer page
(long press up, or Menu -> Dive computer; left goes back), settings shown
in Menu -> Information. Alarms flash the screen red with a sound and wake
the screen; the leak alarm keeps priority.
- Photos (Exif UserComment) and videos (QuickTime comment) carry depth,
dive time and the temperature inside the housing, computer on or off.
- The simulated housing can play a dive on its pressure sensor; launch
arguments for screenshots (README).
- App group entitlement, RemoraKit package (../remora-kit), KIT and
REMOTE_KIT in the Makefile.
Existing button mappings, stored formats, launch arguments and the BLE
protocol are unchanged (the pump remains the only write).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat:
20 files changed, 1899 insertions(+), 46 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -1,5 +1,6 @@
captures/
.claude/
+OpenMerou/OpenMerou.entitlements
*.xcodeproj
build/
build_output/
diff --git a/Makefile b/Makefile
@@ -1,12 +1,18 @@
# The sources live on this host; Xcode runs on a Mac reachable over SSH (CHUNGA), in the REMOTE directory.
+# RemoraKit (a separate repository) is expected next to this one, here (KIT) and on the Mac
+# (REMOTE_KIT): project.yml refers to it as ../remora-kit.
CHUNGA ?= chunga
REMOTE ?= src/perso/open-merou
+KIT ?= ../remora-kit
+REMOTE_KIT ?= $(dir $(REMOTE))remora-kit
+RSYNC = rsync -a --delete --exclude .git --exclude .claude --exclude captures --exclude '*.xcodeproj' --exclude build --exclude .build --exclude .swiftpm
DEST ?= platform=iOS Simulator,name=OpenMerou test iPhone
.PHONY: sync project build test release
sync:
- rsync -a --delete --exclude .git --exclude .claude --exclude captures --exclude '*.xcodeproj' --exclude build ./ $(CHUNGA):$(REMOTE)/
+ $(RSYNC) ./ $(CHUNGA):$(REMOTE)/
+ $(RSYNC) $(KIT)/ $(CHUNGA):$(REMOTE_KIT)/
project: sync
ssh $(CHUNGA) 'cd $(REMOTE) && xcodegen -q'
diff --git a/OpenMerou/App/AppModel.swift b/OpenMerou/App/AppModel.swift
@@ -4,6 +4,7 @@
import AudioToolbox
import Network
import Observation
+import RemoraDeco
import SwiftUI
import UIKit
@@ -11,6 +12,8 @@ import UIKit
@Observable
final class AppModel {
let housing = HousingClient()
+ /// The optional dive computer, and the basic dive information shown even when it is off.
+ let dive: DiveSession
@ObservationIgnored let engine = CameraEngine()
private(set) var camera = CameraState()
private(set) var settings = CameraSettings.load()
@@ -39,10 +42,15 @@ final class AppModel {
private(set) var online = false
private(set) var freeBytes: Int64?
private(set) var hot = false
- /// Estimated depth (m) and dive start: experimental, until 1625 has been validated in the water.
- private(set) var depth: Double?
- private(set) var diveStart: Date?
- @ObservationIgnored private var surfacePa: Double?
+ /// Depth (m) and dive start: experimental, until 1625 has been validated in the water.
+ var depth: Double? { dive.depth }
+ var diveStart: Date? { dive.diveStart }
+ /// "Start housing mode" was touched on the home screen: the housing start card replaces the home.
+ var housingMode = false
+ /// Full-screen dive computer page (long press up, or Menu → Dive computer).
+ private(set) var showingComputer = false
+ /// Dive alarm: the sound stops at the first button press, the red flash stays.
+ private(set) var diveAlarmSilenced = false
@ObservationIgnored private let pathMonitor = NWPathMonitor()
@ObservationIgnored private var ticks = 0
/// iPhone battery, in % (nil when unknown).
@@ -51,6 +59,10 @@ final class AppModel {
@ObservationIgnored private var awakeBrightness: CGFloat = 0.5
@ObservationIgnored private var sleepTask: Task<Void, Never>?
+ init(dive: DiveSession = DiveSession()) {
+ self.dive = dive
+ }
+
func start() {
UIDevice.current.isBatteryMonitoringEnabled = true
UIApplication.shared.isIdleTimerDisabled = true // the screen never locks by itself
@@ -89,7 +101,30 @@ final class AppModel {
engine.start(settings)
exportRoll() // shots left on disk after a crash
housing.cameraButton = { [weak self] event in self?.button(event) }
- housing.anyButton = { [weak self] in self?.alarmSilenced = true }
+ housing.anyButton = { [weak self] in
+ self?.alarmSilenced = true
+ self?.diveAlarmSilenced = true
+ }
+ housing.externalPressure = { [weak self] pa, time in
+ guard let self else { return }
+ dive.pressure(pa: pa, time: time, simulated: housing.simulated)
+ }
+ housing.linkLost = { [weak self] in self?.dive.linkLost() }
+ housing.sessionStarted = { [weak self] in
+ self?.dive.reset()
+ self?.housingMode = false
+ self?.showingComputer = false
+ }
+ dive.onCue = { [weak self] cue in self?.diveCue(cue) }
+ dive.onDiveEnded = { [weak self] saved, simulation in
+ guard let self else { return }
+ if simulation {
+ show(String(localized: "Simulated dive over: nothing is saved"))
+ } else if let saved {
+ DevLog.shared.event(String(localized: "dive no. \(String(saved.number)) saved"))
+ show(String(localized: "Dive no. \(String(saved.number)) saved"))
+ }
+ }
pathMonitor.pathUpdateHandler = { path in
let online = path.status == .satisfied
Task { @MainActor [weak self] in self?.online = online }
@@ -98,6 +133,7 @@ final class AppModel {
applyBrightness()
// Launched with "-simulation": simulated housing from the start (screenshots, demos).
if ProcessInfo.processInfo.arguments.contains("-simulation") { housing.startSimulation() }
+ launchArgumentsForScreenshots()
// "-demoMenu": opens the settings on their last row (screenshots).
if ProcessInfo.processInfo.arguments.contains("-demoMenu") {
housing.bypassVacuum()
@@ -112,6 +148,50 @@ final class AppModel {
}
}
+ /// Screenshots of the dive computer: "-simulateDive reef|deep|shallow" plays a dive on the simulated
+ /// housing ("-diveSkip <seconds>" jumps into it), "-testAlarm" forces the alarm, "-computerPage" opens
+ /// the full-screen page, "-demoLogbook" shows a past dive on the home screen. ("-diveComputer YES" and
+ /// "-acceptTerms" turn the computer on for the launch.)
+ private func launchArgumentsForScreenshots() {
+ let arguments = ProcessInfo.processInfo.arguments
+ if arguments.contains("-demoLogbook") { dive.store.seedDemo() }
+ if arguments.contains("-testAlarm") { dive.monitor.forcedAlarm = true }
+ if let name = UserDefaults.standard.string(forKey: "simulateDive") {
+ housing.startSimulation()
+ let profile: DemoProfile = name == "deep" ? .deep : name == "shallow" ? .shallow : .reef
+ startSimulatedDive(profile, skip: UserDefaults.standard.double(forKey: "diveSkip"))
+ }
+ if arguments.contains("-computerPage") { showingComputer = true }
+ }
+
+ /// Simulated housing: plays `profile` on its pressure sensor (a minute at the surface ends the dive).
+ func startSimulatedDive(_ profile: DemoProfile = .reef, skip: Double = 0) {
+ housing.startSimulatedDive(depths: profile.depths + Array(repeating: 0, count: 75), skip: skip)
+ }
+
+ /// Feedback asked by the dive logic. Haptics are useless in a housing: sounds, and the screen wakes up.
+ /// The leak alarm keeps priority: no dive sound over it.
+ private func diveCue(_ cue: DiveCue) {
+ switch cue {
+ case .alarm, .depthLost:
+ wakeForDive()
+ if !diveAlarmSilenced, !isLeaking { AudioServicesPlayAlertSound(1005) }
+ case .warning:
+ wakeForDive()
+ if !isLeaking { AudioServicesPlayAlertSound(1016) }
+ case .safetyStopStarted, .safetyStopDone:
+ wakeForDive()
+ if !isLeaking { AudioServicesPlaySystemSound(1057) }
+ case .diveSaved:
+ break
+ }
+ }
+
+ private func wakeForDive() {
+ if sleeping { wake() }
+ lastActivity = Date()
+ }
+
/// Minutes of video that the free space allows, at the chosen quality (approximate HEVC bitrates).
var videoMinutesLeft: Int? {
guard let freeBytes else { return nil }
@@ -146,6 +226,7 @@ final class AppModel {
} else {
alarmSilenced = false
}
+ if !dive.monitor.isAlarming { diveAlarmSilenced = false }
// The log is always on during a sealed dive, even outside development mode.
let sealed: Bool = switch housing.vacuum.step {
case .testing, .sealed, .failed: true
@@ -174,16 +255,8 @@ final class AppModel {
engine.apply(settings)
show(String(localized: "iPhone is hot: video reduced to \(light.label)"))
}
- // Estimated depth: the surface is the lowest external pressure seen (fresh water).
- if let ext = housing.readings.externalPressurePa {
- surfacePa = min(surfacePa ?? ext, ext)
- let meters = max(0, (ext - (surfacePa ?? ext)) / 9_806.65)
- depth = meters
- if meters > 0.5, diveStart == nil { diveStart = .now; DevLog.shared.event(String(localized: "dive start (estimated)")) }
- if meters < 0.2, diveStart != nil { diveStart = nil; DevLog.shared.event(String(localized: "dive end (estimated)")) }
- } else {
- depth = nil
- }
+ // The depth is followed sample by sample in `DiveSession` (see `housing.externalPressure`).
+ if ticks % 10 == 2 { dive.store.refreshOutbox() }
checkSleep()
}
@@ -194,6 +267,7 @@ final class AppModel {
if percent != phoneBattery { phoneBattery = percent }
guard !sleeping, settings.sleepAfter > 0, camera.recordingSince == nil, housing.vacuum.cameraHasButtons,
+ !(dive.isComputing && dive.monitor.isAlarming),
Date().timeIntervalSince(lastActivity) > Double(settings.sleepAfter) else { return }
sleep()
}
@@ -226,6 +300,14 @@ final class AppModel {
lastActivity = Date()
if showingInfo { showingInfo = false; return }
if gallery != nil { galleryButton(event); return }
+ if showingComputer {
+ // Computer page: left or a long press up closes it; the shutter still shoots; nothing else.
+ if (event.button == .left && !event.isLong) || (event.button == .up && event.isLong) {
+ showingComputer = false
+ return
+ }
+ guard event.button == .shutter else { return }
+ }
if menu.isOpen {
guard !event.isLong else { return }
let before = settings
@@ -234,6 +316,7 @@ final class AppModel {
settings.mode = mode
case .sleepNow: sleep()
case .showInfo: showingInfo = true
+ case .showComputer: showingComputer = true
case .none, .close, .changed: break
}
if settings != before {
@@ -251,6 +334,8 @@ final class AppModel {
if event.button == .down { engine.calibrate() }
// Long press on the shutter: lock or release focus and exposure.
if event.button == .shutter { engine.toggleFocusLock() }
+ // Long press up: the dive computer page.
+ if event.button == .up { showingComputer = true }
return
}
switch event.button {
@@ -259,7 +344,8 @@ final class AppModel {
DevLog.shared.event(String(localized: "photo requested"))
shutterFlash += 1
}
- settings.mode == .photo ? engine.capturePhoto() : engine.toggleRecording()
+ let comment = dive.shotComment(housingTemperature: housing.readings.temperatureC)
+ settings.mode == .photo ? engine.capturePhoto(comment: comment) : engine.toggleRecording(comment: comment)
case .up: engine.cycleLens(1)
case .down: engine.cycleLens(-1)
case .right: if camera.recordingSince == nil { menu.open() }
diff --git a/OpenMerou/Camera/CameraEngine.swift b/OpenMerou/Camera/CameraEngine.swift
@@ -66,6 +66,8 @@ final class CameraEngine: NSObject, @unchecked Sendable {
// MARK: Startup
func start(_ settings: CameraSettings) {
+ // "-noPermissionPrompts": screenshots in the simulator, which has no camera; nothing is asked.
+ if ProcessInfo.processInfo.arguments.contains("-noPermissionPrompts") { return }
// All the permissions at once at launch: once the housing is closed, the screen is out of reach.
AVCaptureDevice.requestAccess(for: .video) { [self] granted in
AVCaptureDevice.requestAccess(for: .audio) { [self] audio in
@@ -327,7 +329,8 @@ final class CameraEngine: NSObject, @unchecked Sendable {
}
}
- func capturePhoto() {
+ /// `comment`: basic dive information to write in the metadata of the photo (Exif UserComment), or nil.
+ func capturePhoto(comment: String? = nil) {
queue.async { [self] in
guard device != nil, session.isRunning else { return }
let heif: [String: Any] = [AVVideoCodecKey: AVVideoCodecType.hevc]
@@ -338,7 +341,7 @@ final class CameraEngine: NSObject, @unchecked Sendable {
photoSettings.maxPhotoDimensions = photoOutput.maxPhotoDimensions
photoSettings.photoQualityPrioritization = .balanced // bursts come before the heaviest processing
rotate(photoOutput.connection(with: .video))
- let delegate = PhotoDelegate { [weak self] id, result in
+ let delegate = PhotoDelegate(comment: comment) { [weak self] id, result in
self?.queue.async {
self?.photoDelegates[id] = nil
switch result {
@@ -352,7 +355,9 @@ final class CameraEngine: NSObject, @unchecked Sendable {
}
}
- func toggleRecording() {
+ /// `comment`: basic dive information at the start of the recording, written as the QuickTime comment of
+ /// the movie, or nil.
+ func toggleRecording(comment: String? = nil) {
queue.async { [self] in
guard device != nil, session.isRunning else { return }
if movieOutput.isRecording {
@@ -363,6 +368,7 @@ final class CameraEngine: NSObject, @unchecked Sendable {
if let connection = movieOutput.connection(with: .video), movieOutput.availableVideoCodecTypes.contains(.hevc) {
movieOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: connection)
}
+ movieOutput.metadata = comment.map { [Self.movieComment($0)] }
let url = Roll.newBase().appendingPathExtension("mov")
movieOutput.startRecording(to: url, recordingDelegate: self)
state.recordingSince = Date()
@@ -370,6 +376,15 @@ final class CameraEngine: NSObject, @unchecked Sendable {
}
}
+ /// Top-level QuickTime metadata item `com.apple.quicktime.comment`.
+ static func movieComment(_ text: String) -> AVMetadataItem {
+ let item = AVMutableMetadataItem()
+ item.identifier = .quickTimeMetadataComment
+ item.dataType = kCMMetadataBaseDataType_UTF8 as String
+ item.value = text as NSString
+ return item
+ }
+
func stopForBackground() {
queue.async { [self] in
if movieOutput.isRecording { movieOutput.stopRecording() }
@@ -397,18 +412,37 @@ extension CameraEngine: AVCaptureFileOutputRecordingDelegate {
}
}
-private final class PhotoDelegate: NSObject, AVCapturePhotoCaptureDelegate, @unchecked Sendable {
+private final class PhotoDelegate: NSObject, AVCapturePhotoCaptureDelegate, AVCapturePhotoFileDataRepresentationCustomizer, @unchecked Sendable {
private let done: @Sendable (Int64, Result<Void, Error>) -> Void
+ private let comment: String?
private var processed: Data?
private var raw: Data?
- init(done: @escaping @Sendable (Int64, Result<Void, Error>) -> Void) { self.done = done }
+ init(comment: String?, done: @escaping @Sendable (Int64, Result<Void, Error>) -> Void) {
+ self.comment = comment
+ self.done = done
+ }
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
- guard error == nil, let data = photo.fileDataRepresentation() else { return }
+ guard error == nil else { return }
+ // With a comment, the file is written through the customizer below; should that fail, the plain
+ // representation is used: a shot is never lost for its metadata.
+ let customized = comment == nil ? nil : photo.fileDataRepresentation(with: self)
+ guard let data = customized ?? photo.fileDataRepresentation() else { return }
if photo.isRawPhoto { raw = data } else { processed = data }
}
+ /// Everything the camera wrote, plus the dive information as the Exif UserComment. (ImageIO has no key
+ /// for the Exif 2.31 WaterDepth, Temperature and Pressure tags, so they cannot be written this way.)
+ func replacementMetadata(for photo: AVCapturePhoto) -> [String: Any]? {
+ var metadata = photo.metadata
+ guard let comment else { return metadata }
+ var exif = metadata[kCGImagePropertyExifDictionary as String] as? [String: Any] ?? [:]
+ exif[kCGImagePropertyExifUserComment as String] = comment
+ metadata[kCGImagePropertyExifDictionary as String] = exif
+ return metadata
+ }
+
func photoOutput(_ output: AVCapturePhotoOutput, didFinishCaptureFor resolved: AVCaptureResolvedPhotoSettings, error: Error?) {
let id = resolved.uniqueID
guard error == nil, let processed else {
diff --git a/OpenMerou/Camera/CameraSettings.swift b/OpenMerou/Camera/CameraSettings.swift
@@ -204,7 +204,8 @@ extension CameraSettings {
/// Menu: right opens and confirms, up and down move, left goes up one level or closes.
struct CameraMenu: Equatable, Sendable {
enum RootItem: Sendable, CaseIterable {
- case photo, video, sleep, settings, brightness, info
+ // New entries go at the end: the positions of the others are known to the tests and to `-demoMenu`.
+ case photo, video, sleep, settings, brightness, info, computer
var title: String {
switch self {
@@ -214,6 +215,7 @@ struct CameraMenu: Equatable, Sendable {
case .settings: String(localized: "Settings")
case .brightness: String(localized: "Brightness")
case .info: String(localized: "Information")
+ case .computer: String(localized: "Dive computer")
}
}
}
@@ -224,7 +226,7 @@ struct CameraMenu: Equatable, Sendable {
case options(CameraSetting, Int)
}
- enum Action: Equatable, Sendable { case none, close, setMode(CaptureMode), sleepNow, changed, showInfo }
+ enum Action: Equatable, Sendable { case none, close, setMode(CaptureMode), sleepNow, changed, showInfo, showComputer }
private(set) var level: Level? = nil
var isOpen: Bool { level != nil }
@@ -258,6 +260,7 @@ struct CameraMenu: Equatable, Sendable {
let options = settings.options(for: .brightness, caps)
self.level = .options(.brightness, options.firstIndex(of: settings.current(.brightness)) ?? 0)
case .info: self.level = nil; return .showInfo
+ case .computer: self.level = nil; return .showComputer
}
}
case .settings(let i):
diff --git a/OpenMerou/Dive/DiveSession.swift b/OpenMerou/Dive/DiveSession.swift
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// The optional dive computer. The dive logic itself (start on submersion, decompression, alarms, depth held
+// when the reading is missing, end at the surface) is `DiveMonitor` from RemoraKit, shared with Open Rémora;
+// this adapter feeds it from the housing's pressure sensor and holds what belongs to this app: the on/off
+// setting, the terms to accept, and the basic dive information shown even when the computer is off.
+//
+// Off (the default): the monitor receives nothing, nothing is recorded or shared.
+import Foundation
+import Observation
+import RemoraDeco
+import RemoraUI
+
+@MainActor @Observable
+final class DiveSession {
+ /// Name written in the recorded dives and in the UDDF files.
+ static let computerName = "Open Mérou"
+ /// Depth of the "depth limit" warning (m): the engine is made for recreational dives to 40 m at most.
+ static let depthLimit = 40.0
+ /// UserDefaults keys.
+ static let enabledKey = "diveComputer"
+
+ /// Warning to accept before the dive computer can be turned on. Changing `version` asks again.
+ static let terms = Terms(
+ version: 1, acceptedKey: "termsAcceptedVersion", appName: computerName,
+ devicePoint: String(localized: "The depth comes from the housing's sensor, read through a reverse-engineered protocol. An iPhone that films can overheat and iOS can stop the app: the computation is then lost."),
+ link: URL(string: "https://agora.schurger.org/open-merou/")!)
+
+ let store: DiveStore
+ let monitor: DiveMonitor
+ private let defaults: UserDefaults
+ private let now: () -> Date
+ private(set) var source = HousingDepthSource()
+ /// The setting. The computer only runs once the terms are accepted (`isActive`).
+ var enabled: Bool { didSet { defaults.set(enabled, forKey: Self.enabledKey) } }
+ private(set) var acceptedTermsVersion: Int
+ /// Sound, flash and screen wake-up are the app's business.
+ @ObservationIgnored var onCue: ((DiveCue) -> Void)?
+ /// A dive ended; `saved` is nil when nothing was kept, `simulation` true for the simulated housing.
+ @ObservationIgnored var onDiveEnded: ((_ saved: DiveLog?, _ simulation: Bool) -> Void)?
+
+ init(store: DiveStore = DiveStore(), defaults: UserDefaults = .standard, now: @escaping () -> Date = { Date() }) {
+ self.store = store
+ self.defaults = defaults
+ self.now = now
+ enabled = defaults.bool(forKey: Self.enabledKey)
+ acceptedTermsVersion = defaults.integer(forKey: Self.terms.acceptedKey)
+ var cue: ((DiveCue) -> Void)?
+ monitor = DiveMonitor(store: store, feedback: { cue?($0) }, now: now)
+ monitor.computerModel = Self.computerName
+ monitor.configure = { $0.depthLimit = Self.depthLimit }
+ cue = { [weak self] in self?.onCue?($0) }
+ monitor.onDiveEnded = { [weak self] saved, _ in
+ guard let self else { return }
+ self.monitor.finishedDive = nil
+ self.onDiveEnded?(saved, self.store.simulated)
+ }
+ }
+
+ var termsAccepted: Bool {
+ acceptedTermsVersion >= Self.terms.version || CommandLine.arguments.contains("-acceptTerms")
+ }
+
+ /// The dive computer runs: turned on, and terms accepted.
+ var isActive: Bool { enabled && termsAccepted }
+
+ /// The diver accepted the terms: the computer is turned on.
+ func acceptTerms() {
+ acceptedTermsVersion = Self.terms.version
+ defaults.set(acceptedTermsVersion, forKey: Self.terms.acceptedKey)
+ enabled = true
+ }
+
+ // MARK: Basic dive information (computer on or off)
+
+ /// Depth to display (m): the computer's during a dive it follows, otherwise the estimate of the source.
+ var depth: Double? { isActive && monitor.isDiving ? monitor.status?.depth : source.depth }
+ /// Start of the current dive (nil at the surface), from the source: an estimate.
+ var diveStart: Date? { source.diveStart }
+ /// The dive computer is on and following a dive.
+ var isComputing: Bool { isActive && monitor.isDiving }
+ /// The pressure sensor reports values that cannot be a pressure: no depth, no dive computer.
+ var sensorImplausible: Bool { source.implausible }
+
+ // MARK: Depth source
+
+ /// One sample of the housing's external pressure (Pa). `time`: clock of the source, in seconds.
+ func pressure(pa: Double, time: Double, simulated: Bool) {
+ let wasUnder = source.diveStart != nil
+ let reading = source.pressure(pa, time: time, now: now())
+ if (source.diveStart != nil) != wasUnder {
+ DevLog.shared.event(wasUnder ? String(localized: "dive end (estimated)") : String(localized: "dive start (estimated)"))
+ }
+ guard isActive, let reading else { return }
+ store.simulated = simulated
+ monitor.receive(reading)
+ }
+
+ /// The Bluetooth link to the housing was lost: underwater, the depth becomes unknown at once.
+ func linkLost() {
+ guard isActive, let reading = source.linkLost(time: now().timeIntervalSinceReferenceDate) else { return }
+ monitor.receive(reading)
+ }
+
+ /// A new housing session starts (reconnection asked by the user, simulation started or stopped):
+ /// the surface pressure is measured afresh. A dive in progress is ended.
+ func reset() {
+ if monitor.isDiving { monitor.end() }
+ source = HousingDepthSource()
+ }
+
+ // MARK: Photo and video metadata
+
+ /// Basic dive information for the metadata of a shot (plain English, not localized: it is data).
+ /// Nil at the surface. The temperature is the one inside the housing, and says so.
+ func shotComment(housingTemperature: Double?) -> String? {
+ guard let start = source.diveStart, let depth else { return nil }
+ let seconds = max(0, Int(now().timeIntervalSince(start)))
+ var text = String(format: "Open Mérou: depth %.1f m%@, dive time %d:%02d", depth,
+ isComputing ? "" : " (estimated)", seconds / 60, seconds % 60)
+ if let housingTemperature { text += String(format: ", temperature inside the housing %.1f °C", housingTemperature) }
+ return text
+ }
+}
diff --git a/OpenMerou/Dive/DiveStore.swift b/OpenMerou/Dive/DiveStore.swift
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// Settings and logbook of the dive computer, saved as JSON in Documents/DiveComputer, and the hand-over
+// of every real dive to Sub Rascasse (see docs/SHARING.md). Simulated dives are never saved nor shared.
+import Foundation
+import Observation
+import RemoraDeco
+
+@MainActor @Observable
+final class DiveStore: DiveLogStore {
+ /// App group shared with Sub Rascasse (same team) and folder of the dives waiting to be imported:
+ /// one `<uuid>.json` (DiveLog) and one `<uuid>.uddf` per dive. Part of the contract: do not rename.
+ static let appGroup = "group.org.schurger.dive"
+ static let outboxPath = "OpenMerou/Dives"
+
+ private(set) var logbook = Logbook()
+ var settings = UserSettings()
+ /// The depth source is the simulated housing: dives ending now are simulations.
+ var simulated = false
+ /// Dives waiting for Sub Rascasse (files still in the outbox).
+ private(set) var pending = 0
+ /// False when the app group is not available: the dives then stay in the app's Documents.
+ let sharedFolderAvailable: Bool
+ private(set) var lastError: String?
+
+ private let folder: URL
+ /// Where the dive files are dropped: the shared folder, or Documents/DiveComputer/Dives without it.
+ let outbox: URL
+ private var demo = false
+ private var logbookURL: URL { folder.appendingPathComponent("logbook.json") }
+ private var settingsURL: URL { folder.appendingPathComponent("settings.json") }
+
+ static let encoder: JSONEncoder = {
+ let e = JSONEncoder()
+ e.dateEncodingStrategy = .iso8601
+ e.outputFormatting = [.sortedKeys]
+ return e
+ }()
+
+ static let decoder: JSONDecoder = {
+ let d = JSONDecoder()
+ d.dateDecodingStrategy = .iso8601
+ return d
+ }()
+
+ static var defaultFolder: URL {
+ FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("DiveComputer")
+ }
+
+ static var sharedContainer: URL? {
+ FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)
+ }
+
+ /// `sharedContainer`: root of the app group (nil when the app does not belong to it).
+ init(folder: URL = DiveStore.defaultFolder, sharedContainer: URL? = DiveStore.sharedContainer) {
+ self.folder = folder
+ let fallback = folder.appendingPathComponent("Dives", isDirectory: true)
+ sharedFolderAvailable = sharedContainer != nil
+ outbox = sharedContainer?.appendingPathComponent(Self.outboxPath, isDirectory: true) ?? fallback
+ try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ if let data = try? Data(contentsOf: logbookURL),
+ let book = try? Self.decoder.decode(Logbook.self, from: data) { logbook = book }
+ if let data = try? Data(contentsOf: settingsURL),
+ let saved = try? Self.decoder.decode(UserSettings.self, from: data) { settings = saved }
+ // Dives kept in Documents while the shared folder was missing move there once it exists.
+ if sharedFolderAvailable, let kept = try? FileManager.default.contentsOfDirectory(at: fallback, includingPropertiesForKeys: nil), !kept.isEmpty {
+ try? FileManager.default.createDirectory(at: outbox, withIntermediateDirectories: true)
+ for file in kept { try? FileManager.default.moveItem(at: file, to: outbox.appendingPathComponent(file.lastPathComponent)) }
+ }
+ refreshOutbox()
+ }
+
+ /// Last real dive.
+ var lastDive: DiveLog? { logbook.realDives.last }
+
+ /// Hours before flying according to the recorded dives (0 = no more restriction).
+ func noFlyHours(at date: Date = Date()) -> Double {
+ SurfaceAdvice.noFlyHours(logbook: logbook, at: date, surfacePressure: standardSurfacePressure)
+ }
+
+ func add(_ dive: DiveLog) -> DiveLog {
+ guard !simulated, !demo else {
+ var copy = dive
+ copy.source = .simulation
+ return copy
+ }
+ logbook.add(dive)
+ saveLogbook()
+ let saved = logbook.dives.first { $0.id == dive.id } ?? dive
+ share(saved)
+ return saved
+ }
+
+ func saveSettings() {
+ guard !demo, settings.problems.isEmpty, let data = try? Self.encoder.encode(settings) else { return }
+ try? data.write(to: settingsURL, options: .atomic)
+ }
+
+ func refreshOutbox() {
+ guard !demo else { return }
+ let files = (try? FileManager.default.contentsOfDirectory(atPath: outbox.path)) ?? []
+ pending = files.filter { $0.hasSuffix(".json") }.count
+ }
+
+ private func saveLogbook() {
+ guard let data = try? Self.encoder.encode(logbook) else { return }
+ try? data.write(to: logbookURL, options: .atomic)
+ }
+
+ private func share(_ dive: DiveLog) {
+ do {
+ try FileManager.default.createDirectory(at: outbox, withIntermediateDirectories: true)
+ let base = outbox.appendingPathComponent(dive.id.uuidString)
+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0"
+ try Self.encoder.encode(dive).write(to: base.appendingPathExtension("json"), options: .atomic)
+ try UDDF.export([dive], generatorName: DiveSession.computerName, generatorVersion: version)
+ .write(to: base.appendingPathExtension("uddf"), atomically: true, encoding: .utf8)
+ } catch {
+ lastError = String(localized: "Shared folder: \(error.localizedDescription)")
+ }
+ refreshOutbox()
+ }
+
+ /// Screenshots (`-demoLogbook`): one dive an hour and a half ago, in memory only; nothing is written.
+ func seedDemo() {
+ demo = true
+ var dive = DemoProfile.reef.record(start: Date().addingTimeInterval(-2.2 * 3600), settings: settings, logbook: Logbook())
+ dive.computerModel = DiveSession.computerName
+ logbook = Logbook()
+ logbook.add(dive)
+ pending = 1
+ }
+}
diff --git a/OpenMerou/Dive/HousingDepthSource.swift b/OpenMerou/Dive/HousingDepthSource.swift
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// Turns the external pressure of the housing (characteristic 1625) into what the dive logic of RemoraKit
+// expects: `DiveReading` values with the absolute pressure, the surface pressure captured before the
+// dive and a "submerged" decision. Pure logic (no Bluetooth, no clock), so that it can be tested.
+//
+// 1625 is still a HYPOTHESIS (external absolute pressure, never seen underwater): every value is checked
+// for plausibility before it is used, and nothing is emitted for a value that cannot be a pressure.
+import Foundation
+import RemoraDeco
+
+struct HousingDepthSource: Equatable, Sendable {
+ /// Absolute pressures the sensor can plausibly report (Pa): from a high mountain lake to about 100 m.
+ static let plausiblePa = 50_000.0...1_100_000.0
+ /// Pressures that can be a surface pressure (Pa): up to about 4000 m of altitude.
+ static let plausibleSurfacePa = 60_000.0...110_000.0
+ /// Above the surface pressure by this much (Pa; 3 kPa ≈ 30 cm of water), the housing is underwater.
+ static let submergedOverPa = 3_000.0
+ /// Link lost deeper than this (Pa above the surface; 15 kPa ≈ 1.5 m): still underwater, depth unknown.
+ /// Shallower, the housing is considered out of the water (same rule as the watchdog of RemoraKit).
+ static let shallowOverPa = 15_000.0
+
+ /// Surface pressure: the lowest plausible pressure seen since the housing session started.
+ private(set) var surfacePa: Double?
+ /// True when the first values were already above any surface pressure (app started underwater):
+ /// the standard atmosphere is assumed.
+ private(set) var surfaceAssumed = false
+ private(set) var lastPa: Double?
+ /// The last value received cannot be a pressure.
+ private(set) var implausible = false
+
+ /// Basic dive information, shown whether the dive computer is on or off: estimated depth (m, fresh
+ /// water) and the time the housing went below 0.5 m (nil at the surface).
+ private(set) var depth: Double?
+ private(set) var diveStart: Date?
+
+ var submerged: Bool {
+ guard let surfacePa, let lastPa else { return false }
+ return lastPa - surfacePa > Self.submergedOverPa
+ }
+
+ /// One sample of the external pressure, in Pa. `time` is the clock of the source in seconds (only
+ /// differences matter), `now` the wall clock. Returns nil when the value is not usable.
+ mutating func pressure(_ pa: Double, time: Double, now: Date) -> DiveReading? {
+ guard Self.plausiblePa.contains(pa) else {
+ implausible = true
+ return nil
+ }
+ implausible = false
+ if Self.plausibleSurfacePa.contains(pa) {
+ if surfaceAssumed {
+ // Back in the range of a surface pressure after starting underwater: a real measurement at last.
+ if pa < (surfacePa ?? pa) { surfacePa = pa; surfaceAssumed = false }
+ } else {
+ surfacePa = min(surfacePa ?? pa, pa)
+ }
+ } else if surfacePa == nil {
+ surfacePa = standardSurfacePressure * 100_000
+ surfaceAssumed = true
+ }
+ guard let surfacePa else { return nil }
+ lastPa = pa
+ let over = pa - surfacePa
+ let metres = max(0, over / 9_806.65)
+ depth = metres
+ if metres > 0.5, diveStart == nil { diveStart = now }
+ if metres < 0.2, diveStart != nil { diveStart = nil }
+ return .pressure(time: time, surface: surfacePa / 100_000, absolute: pa / 100_000,
+ submerged: over > Self.submergedOverPa)
+ }
+
+ /// The Bluetooth link to the housing was lost. Underwater, the reading says so: no measurement, still
+ /// submerged (the dive logic then holds the last depth and flags it as unknown). Near the surface, nothing
+ /// is emitted: the silence is handled by the watchdog of the dive logic.
+ func linkLost(time: Double) -> DiveReading? {
+ guard let surfacePa, let lastPa, lastPa - surfacePa > Self.shallowOverPa else { return nil }
+ return .pressure(time: time, surface: surfacePa / 100_000, absolute: nil, submerged: true)
+ }
+}
diff --git a/OpenMerou/Housing/HousingClient.swift b/OpenMerou/Housing/HousingClient.swift
@@ -43,6 +43,16 @@ final class HousingClient: NSObject {
/// Called at each press, whoever it is meant for (to silence an alarm).
@ObservationIgnored var anyButton: (() -> Void)?
+ /// Every sample of the external pressure (characteristic 1625), in Pa, with its time in seconds: the wall
+ /// clock for a real housing, the clock of the simulated dive for the simulated one.
+ @ObservationIgnored var externalPressure: ((_ pa: Double, _ time: Double) -> Void)?
+ /// The Bluetooth link to a real housing was just lost.
+ @ObservationIgnored var linkLost: (() -> Void)?
+ /// A new housing session starts (reconnection asked by the user, simulation started or stopped).
+ @ObservationIgnored var sessionStarted: (() -> Void)?
+ /// Time of the sample being ingested, when it is not the wall clock (simulated dive).
+ @ObservationIgnored private var sampleTime: Double?
+
func bypassVacuum() { vacuum.bypass() }
@ObservationIgnored private var central: CBCentralManager!
@@ -77,6 +87,44 @@ final class HousingClient: NSObject {
var temperatureC = 21.0
var pumpOn = false
var battery = 92.0
+ /// Simulated dive: depth at every second (empty: at the surface), time since its start, and the
+ /// time of its start on the clock given with the samples.
+ var diveDepths: [Double] = []
+ var diveTime = 0.0
+ var diveBase = 0.0
+ }
+
+ /// External pressure of the simulated housing at the surface, and what a metre of water adds
+ /// (units of the characteristic: tens of Pa; EN 13319 water).
+ private static let simulatedSurface = 9_940.0
+ private static let simulatedPerMetre = 1_000.28
+
+ private static func littleEndian(_ value: UInt32) -> Data {
+ Data([UInt8(value & 0xFF), UInt8(value >> 8 & 0xFF), UInt8(value >> 16 & 0xFF), UInt8(value >> 24)])
+ }
+
+ /// A simulated dive is in progress on the simulated housing.
+ var simulatedDiveRunning: Bool { simulation?.diveDepths.isEmpty == false }
+
+ /// Simulated housing only: plays a dive on the external pressure sensor, `depths` being the depth at every
+ /// second. `skip` seconds of it are fed at once (screenshots of a given moment), the rest in real time.
+ func startSimulatedDive(depths: [Double], skip: Double = 0) {
+ guard var sim = simulation, sim.diveDepths.isEmpty, !depths.isEmpty else { return }
+ let skip = max(0, min(skip, Double(depths.count - 1)))
+ let base = Date().timeIntervalSinceReferenceDate - skip
+ var t = 0.0
+ while t < skip {
+ sampleTime = base + t
+ ingest(HousingUUID.externalPressure,
+ Self.littleEndian(UInt32(Self.simulatedSurface + depths[Int(t)] * Self.simulatedPerMetre)))
+ t += 1
+ }
+ sampleTime = nil
+ sim.diveDepths = depths
+ sim.diveTime = skip
+ sim.diveBase = base
+ simulation = sim
+ note(String(localized: "Simulated dive started"))
}
@ObservationIgnored private var simulation: Simulation?
@@ -97,6 +145,7 @@ final class HousingClient: NSObject {
readings = HousingReadings()
status = .connected(String(localized: "simulated housing"))
deviceInfo = [.model: String(localized: "Simulated housing")]
+ sessionStarted?()
note(String(localized: "Simulation started"))
ingest(HousingUUID.alarm, Data([0x00]))
ingest(HousingUUID.pumpState, Data([0x02]))
@@ -139,9 +188,22 @@ final class HousingClient: NSObject {
sim.temperatureC = min(26, sim.temperatureC + 0.002)
}
sim.pressurePa += Double.random(in: -8...8)
+ var external = Self.simulatedSurface
+ if !sim.diveDepths.isEmpty {
+ sim.diveTime += 0.35
+ let i = Int(sim.diveTime)
+ if i + 1 < sim.diveDepths.count {
+ let a = sim.diveDepths[i], b = sim.diveDepths[i + 1]
+ external += (a + (b - a) * (sim.diveTime - Double(i))) * Self.simulatedPerMetre
+ sampleTime = sim.diveBase + sim.diveTime
+ } else {
+ sim.diveDepths = []
+ }
+ }
simulation = sim
- func le(_ value: UInt32) -> Data { Data([UInt8(value & 0xFF), UInt8(value >> 8 & 0xFF), UInt8(value >> 16 & 0xFF), UInt8(value >> 24)]) }
- ingest(HousingUUID.externalPressure, le(9_940))
+ func le(_ value: UInt32) -> Data { Self.littleEndian(value) }
+ ingest(HousingUUID.externalPressure, le(UInt32(external)))
+ sampleTime = nil
ingest(HousingUUID.temperature, le(UInt32(sim.temperatureC * 100)))
ingest(HousingUUID.internalPressure, le(UInt32(sim.pressurePa)))
if Int(sim.battery) != readings.batteryPercent { ingest(HousingUUID.batteryLevel, Data([UInt8(sim.battery)])) }
@@ -175,6 +237,9 @@ final class HousingClient: NSObject {
run(vacuum.sensors(pressurePa: readings.internalPressurePa, temperatureC: readings.temperatureC, now: .now))
}
if uuid == HousingUUID.internalPressure { DevLog.shared.sensors(readings, vacuum) }
+ if uuid == HousingUUID.externalPressure, let pa = readings.externalPressurePa {
+ externalPressure?(pa, sampleTime ?? Date().timeIntervalSinceReferenceDate)
+ }
// Pump running although we did not ask for it (connection lost while pumping): stop it.
if uuid == HousingUUID.pumpState, readings.pumpState == .running, !pumpRequested, simulation == nil {
stopPump(reason: String(localized: "found running"))
@@ -203,6 +268,7 @@ final class HousingClient: NSObject {
released = false
vacuum = VacuumSequence()
peripheral = nil
+ sessionStarted?()
startScan()
}
@@ -326,6 +392,7 @@ extension HousingClient: CBCentralManagerDelegate {
pumpTimeout?.cancel()
pumpRequested = false
vacuum.connectionLost()
+ linkLost?()
status = .disconnected(why)
note(String(localized: "Disconnected: \(why)"))
// A pending connection request does not expire: the housing is picked up as soon as it comes back.
diff --git a/OpenMerou/Info.plist b/OpenMerou/Info.plist
@@ -31,6 +31,10 @@
<true/>
<key>UIFileSharingEnabled</key>
<true/>
+ <key>LSApplicationQueriesSchemes</key>
+ <array>
+ <string>subrascasse</string>
+ </array>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSBluetoothAlwaysUsageDescription</key>
diff --git a/OpenMerou/Localizable.xcstrings b/OpenMerou/Localizable.xcstrings
@@ -51,6 +51,46 @@
}
}
},
+ "%lld dives waiting for Sub Rascasse": {
+ "localizations": {
+ "en": {
+ "variations": {
+ "plural": {
+ "one": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld dive waiting for Sub Rascasse"
+ }
+ },
+ "other": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld dives waiting for Sub Rascasse"
+ }
+ }
+ }
+ }
+ },
+ "fr": {
+ "variations": {
+ "plural": {
+ "one": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld plongée en attente pour Sub Rascasse"
+ }
+ },
+ "other": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld plongées en attente pour Sub Rascasse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"%lld/%lld": {
"localizations": {
"fr": {
@@ -171,6 +211,16 @@
}
}
},
+ "All dives are in Sub Rascasse": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Toutes les plongées sont dans Sub Rascasse"
+ }
+ }
+ }
+ },
"Allow camera access in Settings → Open Mérou.": {
"localizations": {
"fr": {
@@ -181,6 +231,16 @@
}
}
},
+ "Altitude: the surface pressure is measured by the housing, nothing to set. Underwater the settings can only be read (Menu → Information).": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Altitude : la pression de surface est mesurée par le boîtier, rien à régler. Sous l'eau, les réglages peuvent seulement être lus (Menu → Informations)."
+ }
+ }
+ }
+ },
"Any button: close": {
"localizations": {
"fr": {
@@ -271,6 +331,16 @@
}
}
},
+ "Cancel": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Annuler"
+ }
+ }
+ }
+ },
"Check the plug, the O-ring and the latch.": {
"localizations": {
"fr": {
@@ -301,6 +371,16 @@
}
}
},
+ "Clock": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Heure"
+ }
+ }
+ }
+ },
"Colors": {
"localizations": {
"fr": {
@@ -381,6 +461,16 @@
}
}
},
+ "Conservatism": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Prudence"
+ }
+ }
+ }
+ },
"Corrected rise: %@ Pa": {
"localizations": {
"fr": {
@@ -471,6 +561,56 @@
}
}
},
+ "Dive computer": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ordinateur de plongée"
+ }
+ }
+ }
+ },
+ "Dive computer off: estimated depth and dive time only. Nothing is computed or recorded.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ordinateur de plongée désactivé : profondeur estimée et durée de plongée seulement. Rien n'est calculé ni enregistré."
+ }
+ }
+ }
+ },
+ "Dive computer on: %@ · %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ordinateur de plongée activé : %@ · %@"
+ }
+ }
+ }
+ },
+ "Dive no. %@ saved": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée nº %@ enregistrée"
+ }
+ }
+ }
+ },
+ "Done": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "OK"
+ }
+ }
+ }
+ },
"Down": {
"localizations": {
"fr": {
@@ -541,6 +681,26 @@
}
}
},
+ "Flying: no more restriction": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avion : plus de restriction"
+ }
+ }
+ }
+ },
+ "Flying: wait another %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avion : attendre encore %@"
+ }
+ }
+ }
+ },
"Focus and exposure automatic": {
"localizations": {
"fr": {
@@ -561,6 +721,26 @@
}
}
},
+ "Gas": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mélange"
+ }
+ }
+ }
+ },
+ "Get in the water: the dive starts by itself": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Entrez dans l'eau : la plongée démarre seule"
+ }
+ }
+ }
+ },
"HOT": {
"localizations": {
"fr": {
@@ -651,6 +831,16 @@
}
}
},
+ "Housing mode": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mode boîtier"
+ }
+ }
+ }
+ },
"Housing vented": {
"localizations": {
"fr": {
@@ -661,6 +851,26 @@
}
}
},
+ "In the housing": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Dans le boîtier"
+ }
+ }
+ }
+ },
+ "In the housing: %@ °C": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Dans le boîtier : %@ °C"
+ }
+ }
+ }
+ },
"Information": {
"localizations": {
"fr": {
@@ -761,6 +971,16 @@
}
}
},
+ "Last dive: %@ · %@ m · %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Dernière plongée : %@ · %@ m · %@"
+ }
+ }
+ }
+ },
"Leak test": {
"localizations": {
"fr": {
@@ -811,6 +1031,16 @@
}
}
},
+ "Left or long press up: back to the camera": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Gauche ou appui long en haut : retour à la caméra"
+ }
+ }
+ }
+ },
"Log": {
"localizations": {
"fr": {
@@ -871,6 +1101,16 @@
}
}
},
+ "Max": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Max"
+ }
+ }
+ }
+ },
"Model": {
"localizations": {
"fr": {
@@ -881,6 +1121,26 @@
}
}
},
+ "NDL alarm · maximum ppO2": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Alarme de NDL · ppO2 maximale"
+ }
+ }
+ }
+ },
+ "NDL: time left without a mandatory stop. Below this threshold the value blinks and a sound is played.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "NDL : temps restant sans palier obligatoire. Sous ce seuil, la valeur clignote et un son est joué."
+ }
+ }
+ }
+ },
"Never": {
"localizations": {
"fr": {
@@ -941,6 +1201,16 @@
}
}
},
+ "Off: the app only shows the depth, the dive time and the temperature inside the housing. Nothing is recorded.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Désactivé : l'app affiche seulement la profondeur, la durée de plongée et la température dans le boîtier. Rien n'est enregistré."
+ }
+ }
+ }
+ },
"Once disconnected, hold the right button of the housing for 2 seconds to turn it off.": {
"localizations": {
"fr": {
@@ -961,6 +1231,16 @@
}
}
},
+ "Open Sub Rascasse": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ouvrir Sub Rascasse"
+ }
+ }
+ }
+ },
"Open the plug": {
"localizations": {
"fr": {
@@ -1181,6 +1461,16 @@
}
}
},
+ "Read and accept the terms": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lire et accepter les conditions"
+ }
+ }
+ }
+ },
"Reconnect": {
"localizations": {
"fr": {
@@ -1311,6 +1601,16 @@
}
}
},
+ "Secondary computer, not certified. To be used with a primary dive computer.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ordinateur secondaire, non certifié. À utiliser avec un ordinateur de plongée principal."
+ }
+ }
+ }
+ },
"Sequence: %@": {
"localizations": {
"fr": {
@@ -1331,6 +1631,16 @@
}
}
},
+ "Set everything here before closing the housing: once it is closed, only its five buttons work.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Réglez tout ici avant de fermer le boîtier : une fois fermé, seuls ses cinq boutons servent."
+ }
+ }
+ }
+ },
"Settings": {
"localizations": {
"fr": {
@@ -1341,6 +1651,26 @@
}
}
},
+ "Shared folder unavailable: dives stay in this app.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Dossier partagé indisponible : les plongées restent dans cette app."
+ }
+ }
+ }
+ },
+ "Shared folder: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Dossier partagé : %@"
+ }
+ }
+ }
+ },
"Shots": {
"localizations": {
"fr": {
@@ -1361,6 +1691,16 @@
}
}
},
+ "Simulate a dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Simuler une plongée"
+ }
+ }
+ }
+ },
"Simulate a housing": {
"localizations": {
"fr": {
@@ -1371,6 +1711,26 @@
}
}
},
+ "Simulated dive over: nothing is saved": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée simulée terminée : rien n'est enregistré"
+ }
+ }
+ }
+ },
+ "Simulated dive started": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée simulée démarrée"
+ }
+ }
+ }
+ },
"Simulated housing": {
"localizations": {
"fr": {
@@ -1451,6 +1811,16 @@
}
}
},
+ "Start housing mode": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Démarrer le mode boîtier"
+ }
+ }
+ }
+ },
"Stop the pump": {
"localizations": {
"fr": {
@@ -1461,6 +1831,16 @@
}
}
},
+ "Surface": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Surface"
+ }
+ }
+ }
+ },
"Surface and take the housing out of the water": {
"localizations": {
"fr": {
@@ -1471,6 +1851,16 @@
}
}
},
+ "Terms of use": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conditions d'utilisation"
+ }
+ }
+ }
+ },
"Testing": {
"localizations": {
"fr": {
@@ -1481,6 +1871,26 @@
}
}
},
+ "The depth comes from the housing's sensor, read through a reverse-engineered protocol. An iPhone that films can overheat and iOS can stop the app: the computation is then lost.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La profondeur vient du capteur du boîtier, lu par un protocole obtenu par rétro-ingénierie. Un iPhone qui filme peut surchauffer et iOS peut arrêter l'app : le calcul est alors perdu."
+ }
+ }
+ }
+ },
+ "The depth sensor of the housing gives implausible values: no dive computer.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le capteur de profondeur du boîtier donne des valeurs invraisemblables : pas d'ordinateur de plongée."
+ }
+ }
+ }
+ },
"The housing is already under vacuum: the leak test will start right away.": {
"localizations": {
"fr": {
@@ -1521,6 +1931,16 @@
}
}
},
+ "Time": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Temps"
+ }
+ }
+ }
+ },
"Turn the housing on: it will be detected automatically.": {
"localizations": {
"fr": {
@@ -1851,6 +2271,16 @@
}
}
},
+ "dive no. %@ saved": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "plongée nº %@ enregistrée"
+ }
+ }
+ }
+ },
"dive start (estimated)": {
"localizations": {
"fr": {
@@ -2031,6 +2461,26 @@
}
}
},
+ "max %@ m": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "max %@ m"
+ }
+ }
+ }
+ },
+ "max %@ m for this gas": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "max %@ m pour ce mélange"
+ }
+ }
+ }
+ },
"microphone (videos without sound)": {
"localizations": {
"fr": {
@@ -2091,6 +2541,16 @@
}
}
},
+ "ppO2": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ppO2"
+ }
+ }
+ }
+ },
"pump %@ 1628 %@ batt %@ %%": {
"localizations": {
"fr": {
diff --git a/OpenMerou/UI/CameraScreen.swift b/OpenMerou/UI/CameraScreen.swift
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: GPL-2.0-only
import AVFoundation
+import RemoraDeco
+import RemoraUI
import SwiftUI
struct PreviewView: UIViewRepresentable {
@@ -42,8 +44,13 @@ struct CameraScreen: View {
// Shutter blink: the image goes dark for an instant at each photo.
Color.black.ignoresSafeArea().opacity(flashing ? 1 : 0).allowsHitTesting(false)
+ // Dive computer alarm: the whole screen flashes red, under the read-outs.
+ if diveAlarm { AlarmFlash().allowsHitTesting(false) }
+ if showingComputer { ComputerPage(model: model) }
+
VStack {
topBar
+ if model.dive.isComputing, !showingComputer { DiveBand(model: model) }
if model.settings.developer { devOverlay }
Spacer()
if let message = model.toast, !model.menu.isOpen {
@@ -57,7 +64,11 @@ struct CameraScreen: View {
if !model.camera.authorized {
card { Text("Allow camera access in Settings → Open Mérou.") }
} else if housing.vacuum.step == .prepare, !housing.simulated {
- card { HomeView(model: model) }
+ if model.housingMode {
+ card { HousingStartView(model: model) }
+ } else {
+ HomeScreen(model: model)
+ }
} else if !housing.vacuum.cameraHasButtons {
card {
VacuumView(vacuum: housing.vacuum)
@@ -85,11 +96,14 @@ struct CameraScreen: View {
.padding(.top, 50)
}
+ if diveAlarm, !showingComputer { DiveAlarmLabel(monitor: model.dive.monitor) }
+
+ // The leak alarm keeps priority over everything else.
if case .failed(.leak(let rise)) = housing.vacuum.step {
LeakAlarm(risePa: rise)
}
- if housing.simulated { SimulatedButtons(housing: housing) }
+ if housing.simulated { SimulatedButtons(housing: housing) { model.startSimulatedDive() } }
if model.sleeping {
Color.black.ignoresSafeArea().onTapGesture { model.wake() }
@@ -112,6 +126,11 @@ struct CameraScreen: View {
}
}
+ /// The dive computer is following a dive and raises an alarm (violation, depth unknown).
+ private var diveAlarm: Bool { model.dive.isComputing && model.dive.monitor.isAlarming }
+ /// The computer page is a camera-mode page: never over the vacuum sequence.
+ private var showingComputer: Bool { model.showingComputer && housing.vacuum.cameraHasButtons }
+
private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {
VStack(alignment: .leading, spacing: 8) { content() }
.padding(20)
@@ -128,7 +147,8 @@ struct CameraScreen: View {
if let b = housing.readings.batteryPercent { Text("Housing \(b) %").foregroundStyle(b <= 20 ? .orange : .white) }
if let b = model.phoneBattery { Text("iPhone \(b) %").foregroundStyle(b <= 20 ? .orange : .white) }
if model.hot { Label("HOT", systemImage: "thermometer.high").foregroundStyle(.orange) }
- if let depth = model.depth, depth > 0.3 {
+ // Basic dive information (the band of the dive computer replaces it when it is on).
+ if !model.dive.isComputing, let depth = model.depth, depth > 0.3 {
Text(String(format: "≈ %.1f m", depth))
if let start = model.diveStart { Text(start, style: .timer) }
}
@@ -295,6 +315,8 @@ struct MenuView: View {
/// Buttons of the simulated housing: same layout as the real one (cross at the back, shutter on top).
struct SimulatedButtons: View {
let housing: HousingClient
+ /// Plays a dive on the simulated pressure sensor.
+ let startDive: () -> Void
var body: some View {
VStack {
@@ -310,8 +332,14 @@ struct SimulatedButtons: View {
key("chevron.right", .right)
}
Text("Simulation · long press available").font(.caption2)
- Button("Leave the simulation") { housing.stopSimulation() }
- .font(.caption).padding(6).background(.black.opacity(0.6), in: Capsule())
+ HStack(spacing: 6) {
+ if !housing.simulatedDiveRunning {
+ Button("Simulate a dive", action: startDive)
+ .font(.caption).padding(6).background(.black.opacity(0.6), in: Capsule())
+ }
+ Button("Leave the simulation") { housing.stopSimulation() }
+ .font(.caption).padding(6).background(.black.opacity(0.6), in: Capsule())
+ }
}
}
}
@@ -348,6 +376,17 @@ struct InfoPanel: View {
(CameraSetting.color.title, model.camera.gains?.label ?? "iPhone"),
(String(localized: "Shots"), String(localized: "\(String(model.roll.count)) this session · \(videoLeft)")),
(DeviceInfoField.firmware.label, housing.deviceInfo[.firmware] ?? "—"),
+ ] + computerRows
+ }
+
+ /// The settings of the dive computer, read-only: underwater they can only be displayed.
+ private var computerRows: [(String, String)] {
+ let title = CameraMenu.RootItem.computer.title
+ guard model.dive.isActive else { return [(title, String(localized: "Disabled"))] }
+ let s = model.dive.store.settings
+ return [
+ (title, "\(s.gas.description) · \(SettingsText.conservatism(s)) · \(s.water.label)"),
+ (String(localized: "NDL alarm · maximum ppO2"), "\(SettingsText.ndlAlarm(s.ndlAlarmMinutes)) · \(SettingsText.ppO2(s.ppO2Max))"),
]
}
@@ -371,8 +410,9 @@ struct InfoPanel: View {
}
}
-/// Home: simulate a housing, or use the real one as soon as it is detected.
-struct HomeView: View {
+/// Housing mode, first step: the housing is searched, detected, then its right button starts the vacuum
+/// sequence. Reached from the home screen ("Start housing mode"); "Back" returns there.
+struct HousingStartView: View {
let model: AppModel
/// What is worth fixing before closing the housing.
@@ -390,19 +430,21 @@ struct HomeView: View {
var body: some View {
let housing = model.housing
VStack(alignment: .leading, spacing: 12) {
- Text("Open Mérou").font(.title2.bold())
-
- Button { housing.startSimulation() } label: {
- Label("Simulate a housing", systemImage: "play.rectangle.fill").frame(maxWidth: .infinity)
+ HStack {
+ Text("Housing mode").font(.title2.bold())
+ Spacer()
+ Button { model.housingMode = false } label: { Label("Back", systemImage: "chevron.left") }
+ .buttonStyle(.bordered)
}
- .buttonStyle(.borderedProminent)
- .tint(.yellow)
- .foregroundStyle(.black)
- .disabled(housing.isConnected)
if housing.isConnected {
VStack(alignment: .leading, spacing: 6) {
Label("Housing detected", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(.green)
+ if model.dive.isActive {
+ let s = model.dive.store.settings
+ Label("Dive computer on: \(s.gas.description) · \(SettingsText.conservatism(s))", systemImage: "gauge.with.dots.needle.bottom.50percent")
+ .font(.footnote).foregroundStyle(.cyan)
+ }
if let p = housing.vacuum.pressurePa, p < VacuumSequence.alreadyUnderVacuumPa {
Text("It is already under vacuum: the leak test will start right away.")
} else {
diff --git a/OpenMerou/UI/DiveViews.swift b/OpenMerou/UI/DiveViews.swift
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// What the dive computer shows over the camera. Words, colours and alarm styles are those of the watch app
+// (components of RemoraUI); the layout is this app's: landscape, over the preview, driven by the housing buttons.
+import RemoraDeco
+import RemoraUI
+import SwiftUI
+
+/// Permanent band under the top bar during a dive: ascent rate, depth, dive time, and what to do now
+/// (NDL, stop with its countdown, safety stop, warning).
+struct DiveBand: View {
+ let model: AppModel
+
+ var body: some View {
+ let monitor = model.dive.monitor
+ VStack(alignment: .leading, spacing: 6) {
+ if let s = monitor.status {
+ HStack(spacing: 16) {
+ AscentScale(rate: s.ascentRate, scale: 1.1)
+ .blinking(monitor.activeWarnings.contains(.ascentFast))
+ DepthReadout(depth: s.depth, size: 46, limit: monitor.activeWarnings.contains(.depthLimit))
+ VStack(alignment: .leading, spacing: 0) {
+ Text(Format.clock(s.elapsed * 60))
+ .font(.system(size: 22, weight: .semibold, design: .rounded)).monospacedDigit()
+ Text("max \(Format.depth(s.maxDepth)) m").font(.caption).foregroundStyle(.secondary)
+ }
+ DiveInstruction(status: s, scale: 1.25)
+ }
+ .padding(.horizontal, 14).padding(.vertical, 6)
+ .background(.black.opacity(0.55), in: RoundedRectangle(cornerRadius: 14))
+ }
+ if monitor.depthUnknown { DepthUnknownBanner(scale: 1.4).frame(maxWidth: 420) }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+/// The depth in large type; orange and blinking at the depth limit, as on the watch.
+struct DepthReadout: View {
+ let depth: Double
+ let size: CGFloat
+ var limit = false
+
+ var body: some View {
+ HStack(alignment: .firstTextBaseline, spacing: 3) {
+ Text(Format.depth(depth))
+ .font(.system(size: size, weight: .semibold, design: .rounded))
+ .monospacedDigit()
+ .lineLimit(1).fixedSize()
+ .foregroundStyle(limit ? .orange : .white)
+ .blinking(limit)
+ Text(verbatim: "m").font(.system(size: size * 0.4)).foregroundStyle(.secondary)
+ }
+ }
+}
+
+/// Alarm in the middle of the screen, over the red flash: what is wrong, in very large type.
+struct DiveAlarmLabel: View {
+ let monitor: DiveMonitor
+
+ var body: some View {
+ VStack(spacing: 10) {
+ if monitor.depthUnknown {
+ DepthUnknownBanner(scale: 2.2).frame(maxWidth: 560)
+ } else if let warning = monitor.warnings.filter(\.isViolation).sorted(by: { $0.rawValue < $1.rawValue }).first {
+ Text(warning.label.uppercased())
+ .font(.system(size: 52, weight: .black, design: .rounded))
+ .minimumScaleFactor(0.5).lineLimit(1)
+ }
+ }
+ .foregroundStyle(.white)
+ .shadow(radius: 4)
+ .padding()
+ .allowsHitTesting(false)
+ }
+}
+
+/// Full-screen page of the dive computer (long press up, or Menu → Dive computer; left goes back).
+/// During a dive: the same read-outs as the watch, larger, with the details. At the surface: the settings,
+/// read-only. Computer off: the basic dive information only.
+struct ComputerPage: View {
+ let model: AppModel
+
+ private var dive: DiveSession { model.dive }
+ /// Simulated housing: the on-screen buttons take the right of the screen, everything is smaller.
+ private var compact: Bool { model.housing.simulated }
+
+ var body: some View {
+ let monitor = dive.monitor
+ ZStack {
+ // During an alarm the red flash stays visible through the page.
+ Color.black.opacity(dive.isComputing && monitor.isAlarming ? 0.35 : 0.92).ignoresSafeArea()
+ VStack(spacing: 8) {
+ if !dive.isActive {
+ off
+ } else if dive.isComputing, let status = monitor.status {
+ if monitor.depthUnknown { DepthUnknownBanner(scale: 1.6).frame(maxWidth: 520) }
+ diving(status)
+ } else {
+ ready
+ }
+ Text("Left or long press up: back to the camera").font(.caption2).foregroundStyle(.secondary)
+ }
+ // In simulation the page leaves the simulated buttons visible, as the other panels do.
+ .padding(.leading, 24).padding(.trailing, model.housing.simulated ? 300 : 24).padding(.vertical, 46)
+ }
+ }
+
+ private func diving(_ s: DiveComputer.Status) -> some View {
+ let settings = dive.store.settings, monitor = dive.monitor
+ return HStack(spacing: compact ? 12 : 24) {
+ VStack(spacing: 4) {
+ HStack(spacing: 14) {
+ AscentScale(rate: s.ascentRate, scale: compact ? 1.4 : 2)
+ .blinking(monitor.activeWarnings.contains(.ascentFast))
+ DepthReadout(depth: s.depth, size: compact ? 62 : 92, limit: monitor.activeWarnings.contains(.depthLimit))
+ }
+ DiveInstruction(status: s, scale: compact ? 1.3 : 2).fixedSize()
+ }
+ .frame(maxWidth: .infinity)
+
+ Grid(horizontalSpacing: 18, verticalSpacing: 8) {
+ GridRow {
+ cell("Time", Format.clock(s.elapsed * 60))
+ cell("Max", "\(Format.depth(s.maxDepth)) m")
+ }
+ GridRow {
+ cell("Surface", "\(Int(s.plan.timeToSurface.rounded(.up))) min")
+ cell("ppO2", Format.decimal(s.ppO2, digits: 2), color: s.ppO2 > settings.ppO2Max ? .orange : .white)
+ }
+ GridRow {
+ cell("Gas", settings.gas.description)
+ cell("Conservatism", settings.gradientFactors.description)
+ }
+ GridRow {
+ cell("Clock", Date().formatted(date: .omitted, time: .shortened))
+ cell("In the housing", model.housing.readings.temperatureC.map { "\(Format.decimal($0, digits: 1)) °C" } ?? "—")
+ }
+ }
+ .frame(maxWidth: .infinity)
+ }
+ }
+
+ /// At the surface: the settings as they will be used, read-only.
+ private var ready: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Dive computer").font(.title2.bold())
+ if dive.sensorImplausible {
+ Label("The depth sensor of the housing gives implausible values: no dive computer.", systemImage: "exclamationmark.triangle.fill")
+ .foregroundStyle(.orange)
+ } else {
+ Label("Get in the water: the dive starts by itself", systemImage: "water.waves").foregroundStyle(.cyan)
+ }
+ SettingsSummary(settings: dive.store.settings)
+ Text("Secondary computer, not certified. To be used with a primary dive computer.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: 460)
+ }
+
+ /// Computer off: depth, dive time and the temperature inside the housing, nothing else.
+ private var off: some View {
+ VStack(spacing: 8) {
+ HStack(spacing: 28) {
+ Text(verbatim: "≈").font(.system(size: 48, weight: .semibold, design: .rounded)).foregroundStyle(.secondary)
+ DepthReadout(depth: dive.depth ?? 0, size: compact ? 62 : 92)
+ VStack(alignment: .leading, spacing: 6) {
+ if let start = dive.diveStart {
+ Text(start, style: .timer).font(.system(size: 34, weight: .semibold, design: .rounded)).monospacedDigit()
+ }
+ if let t = model.housing.readings.temperatureC {
+ Text("In the housing: \(Format.decimal(t, digits: 1)) °C").font(.title3)
+ }
+ }
+ }
+ Text("Dive computer off: estimated depth and dive time only. Nothing is computed or recorded.")
+ .font(.footnote).foregroundStyle(.secondary).multilineTextAlignment(.center)
+ }
+ }
+
+ private func cell(_ title: LocalizedStringKey, _ value: String, color: Color = .white) -> some View {
+ VStack(spacing: 0) {
+ Text(title).font(.caption).foregroundStyle(.secondary)
+ Text(value).font(.system(size: compact ? 19 : 26, weight: .semibold, design: .rounded)).monospacedDigit()
+ .foregroundStyle(color).minimumScaleFactor(0.6).lineLimit(1)
+ }
+ .frame(maxWidth: .infinity)
+ }
+}
diff --git a/OpenMerou/UI/HomeScreen.swift b/OpenMerou/UI/HomeScreen.swift
@@ -0,0 +1,177 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import RemoraDeco
+import RemoraUI
+import SwiftUI
+
+/// Home screen, the only one made for touch: everything is set here before the housing is closed.
+/// One side starts the housing mode (search, vacuum sequence, camera) or its simulation; the other is the home
+/// of the optional dive computer, as on the watch: gas and conservatism, settings, last dive and waiting
+/// time before flying, dives pending for Sub Rascasse.
+struct HomeScreen: View {
+ let model: AppModel
+ @Environment(\.openURL) private var openURL
+ @State private var showSettings = CommandLine.arguments.contains("-showDiveSettings")
+ @State private var showTerms = CommandLine.arguments.contains("-showTerms")
+ @State private var subRascasseInstalled = false
+
+ /// Sub Rascasse imports the pending dives when it is opened with this URL.
+ static let subRascasseURL = URL(string: "subrascasse://open-merou")!
+
+ private var dive: DiveSession { model.dive }
+
+ var body: some View {
+ GeometryReader { geometry in
+ let layout = geometry.size.width > geometry.size.height
+ ? AnyLayout(HStackLayout(alignment: .top, spacing: 28))
+ : AnyLayout(VStackLayout(alignment: .leading, spacing: 20))
+ ScrollView {
+ layout {
+ housingColumn.frame(maxWidth: .infinity, alignment: .leading)
+ computerColumn.frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(20)
+ }
+ }
+ .background(.black.opacity(0.8), in: RoundedRectangle(cornerRadius: 20))
+ .padding(.horizontal, 12).padding(.vertical, 40)
+ .sheet(isPresented: $showSettings) { settingsSheet }
+ .sheet(isPresented: $showTerms) { termsSheet }
+ .task {
+ subRascasseInstalled = UIApplication.shared.canOpenURL(Self.subRascasseURL)
+ dive.store.refreshOutbox()
+ }
+ }
+
+ // MARK: Housing
+
+ private var housingColumn: some View {
+ let housing = model.housing
+ return VStack(alignment: .leading, spacing: 12) {
+ Text("Open Mérou").font(.title2.bold())
+
+ Button { model.housingMode = true } label: {
+ Label("Start housing mode", systemImage: "camera.aperture")
+ .font(.title3.bold()).frame(maxWidth: .infinity).padding(.vertical, 10)
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(.yellow)
+ .foregroundStyle(.black)
+
+ Button { housing.startSimulation() } label: {
+ Label("Simulate a housing", systemImage: "play.rectangle.fill").frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.bordered)
+ .disabled(housing.isConnected)
+
+ if housing.isConnected {
+ Label("Housing detected", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(.green)
+ }
+ ForEach(model.camera.denied, id: \.self) { item in
+ Label("Permission denied: \(item). Settings → Open Mérou.", systemImage: "exclamationmark.triangle.fill")
+ .font(.footnote).foregroundStyle(.orange)
+ }
+ Text("Set everything here before closing the housing: once it is closed, only its five buttons work.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ }
+
+ // MARK: Dive computer
+
+ private var enabled: Binding<Bool> {
+ Binding(get: { dive.enabled }, set: { on in
+ // Turning it on goes through the terms the first time (and again when they change).
+ if on, !dive.termsAccepted { showTerms = true } else { dive.enabled = on }
+ })
+ }
+
+ private var computerColumn: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Toggle(isOn: enabled) { Text("Dive computer").font(.title2.bold()) }
+ .tint(.cyan)
+
+ if dive.isActive {
+ computerOn
+ } else if dive.enabled {
+ Button { showTerms = true } label: { Label("Read and accept the terms", systemImage: "doc.text") }
+ .buttonStyle(.bordered)
+ } else {
+ Text("Off: the app only shows the depth, the dive time and the temperature inside the housing. Nothing is recorded.")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ @ViewBuilder private var computerOn: some View {
+ let store = dive.store, settings = store.settings
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: "\(settings.gas.description) · \(SettingsText.conservatism(settings))").font(.headline)
+ Text("max \(Format.depth(settings.maximumOperatingDepth())) m for this gas")
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+ Button { showSettings = true } label: { Label("Settings", systemImage: "gearshape") }
+ .buttonStyle(.bordered)
+
+ if model.housing.isConnected, dive.sensorImplausible {
+ Label("The depth sensor of the housing gives implausible values: no dive computer.", systemImage: "exclamationmark.triangle.fill")
+ .font(.footnote).foregroundStyle(.orange)
+ }
+
+ if let last = store.lastDive {
+ let fly = store.noFlyHours()
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Last dive: \(Format.dayTime(last.start)) · \(Format.depth(last.maxDepth)) m · \(Format.minutes(last.duration))")
+ Label(fly > 0 ? "Flying: wait another \(Format.hours(fly))" : "Flying: no more restriction", systemImage: "airplane")
+ if store.pending > 0 {
+ // Plural forms are in the String Catalog.
+ Label("\(store.pending) dives waiting for Sub Rascasse", systemImage: "tray.and.arrow.up")
+ } else if store.sharedFolderAvailable {
+ Label("All dives are in Sub Rascasse", systemImage: "checkmark.circle")
+ }
+ if subRascasseInstalled {
+ Button { openURL(Self.subRascasseURL) } label: { Label("Open Sub Rascasse", systemImage: "book.pages") }
+ .buttonStyle(.bordered)
+ }
+ }
+ .font(.footnote)
+ }
+ if !store.sharedFolderAvailable {
+ Text("Shared folder unavailable: dives stay in this app.").font(.footnote).foregroundStyle(.orange)
+ }
+ if let error = store.lastError { Text(error).font(.footnote).foregroundStyle(.red) }
+
+ Text("Secondary computer, not certified. To be used with a primary dive computer.")
+ .font(.footnote).foregroundStyle(.secondary)
+ Link(destination: DiveSession.terms.link) { Text("Terms of use").font(.footnote) }
+ }
+
+ // MARK: Sheets
+
+ /// The settings screens are those of RemoraKit, shared with the watch; the app saves every change.
+ private var settingsSheet: some View {
+ @Bindable var store = dive.store
+ return NavigationStack {
+ DiveSettingsView(
+ settings: $store.settings,
+ ndlAlarmNote: String(localized: "NDL: time left without a mandatory stop. Below this threshold the value blinks and a sound is played."),
+ altitudeNote: String(localized: "Altitude: the surface pressure is measured by the housing, nothing to set. Underwater the settings can only be read (Menu → Information)."))
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) { Button("Done") { showSettings = false } }
+ }
+ }
+ .onChange(of: store.settings) { store.saveSettings() }
+ .preferredColorScheme(.dark)
+ }
+
+ private var termsSheet: some View {
+ NavigationStack {
+ TermsView(terms: DiveSession.terms) {
+ dive.acceptTerms()
+ showTerms = false
+ }
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { showTerms = false } }
+ }
+ }
+ .preferredColorScheme(.dark)
+ }
+}
diff --git a/OpenMerouTests/CameraMenuTests.swift b/OpenMerouTests/CameraMenuTests.swift
@@ -77,6 +77,18 @@ struct CameraMenuTests {
#expect(menu.level == .root(4))
}
+ @Test func diveComputerIsTheLastEntryOfTheRootMenu() {
+ // Added at the end: the entries before it keep their place.
+ #expect(CameraMenu.RootItem.allCases.last == .computer)
+ #expect(CameraMenu.RootItem.allCases.firstIndex(of: .settings) == 3)
+ var menu = CameraMenu(), settings = CameraSettings()
+ menu.open()
+ _ = menu.handle(.up, settings: &settings, caps: caps) // wraps to the last entry
+ #expect(menu.level == .root(6))
+ #expect(menu.handle(.right, settings: &settings, caps: caps) == .showComputer)
+ #expect(!menu.isOpen)
+ }
+
@Test func rawOnlyWhenSupported() {
var noRaw = caps
noRaw.proRAW = false
diff --git a/OpenMerouTests/DiveSessionTests.swift b/OpenMerouTests/DiveSessionTests.swift
@@ -0,0 +1,232 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+import RemoraDeco
+import Testing
+@testable import OpenMerou
+
+/// The optional dive computer: off, nothing is computed, recorded or shared; on, a real dive is recorded
+/// and handed over to Sub Rascasse; a simulated one never is.
+@MainActor
+struct DiveSessionTests {
+ /// Wall clock of the tests: thirds of a second counted as integers, so that times are exact.
+ final class Clock {
+ var ticks = 0
+ var offset = 0.0
+ var date: Date { Date(timeIntervalSinceReferenceDate: 800_000_000 + offset + Double(ticks) / 3) }
+ }
+
+ let clock = Clock()
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("merou-tests-\(UUID().uuidString)")
+ let surfacePa = 99_400.0
+ /// Pa per metre in the default water of the computer (EN 13319).
+ let perMetre = 10_002.783
+
+ func session(enabled: Bool, termsAccepted: Bool = true, shared: URL? = nil) -> DiveSession {
+ let name = "merou-tests-\(UUID().uuidString)"
+ let defaults = UserDefaults(suiteName: name)!
+ defaults.removePersistentDomain(forName: name)
+ defaults.set(enabled, forKey: DiveSession.enabledKey)
+ if termsAccepted { defaults.set(DiveSession.terms.version, forKey: DiveSession.terms.acceptedKey) }
+ let clock = clock
+ return DiveSession(store: DiveStore(folder: folder, sharedContainer: shared), defaults: defaults, now: { clock.date })
+ }
+
+ /// `seconds` at `depth`, three samples per second as the housing sends them.
+ func stay(_ session: DiveSession, at depth: Double, seconds: Int, simulated: Bool = false) {
+ for _ in 0..<(seconds * 3) {
+ session.pressure(pa: surfacePa + depth * perMetre, time: clock.date.timeIntervalSinceReferenceDate, simulated: simulated)
+ clock.ticks += 1
+ }
+ }
+
+ func files(in url: URL) -> [String] {
+ ((try? FileManager.default.contentsOfDirectory(atPath: url.path)) ?? []).sorted()
+ }
+
+ @Test func offByDefault() {
+ let name = "merou-tests-\(UUID().uuidString)"
+ let defaults = UserDefaults(suiteName: name)!
+ defaults.removePersistentDomain(forName: name)
+ let fresh = DiveSession(store: DiveStore(folder: folder, sharedContainer: nil), defaults: defaults)
+ #expect(!fresh.enabled)
+ #expect(!fresh.isActive)
+ }
+
+ @Test func offNothingIsComputedRecordedOrShared() {
+ let s = session(enabled: false)
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 8, seconds: 120)
+ // Basic information only: an estimated depth and a dive time.
+ #expect(abs((s.depth ?? 0) - 8.16) < 0.01) // fresh water estimate
+ #expect(s.diveStart != nil)
+ #expect(!s.monitor.isDiving)
+ #expect(s.monitor.status == nil)
+ #expect(!s.isComputing)
+ stay(s, at: 0, seconds: 70)
+ #expect(s.diveStart == nil)
+ #expect(s.store.logbook.dives.isEmpty)
+ #expect(s.store.pending == 0)
+ #expect(files(in: s.store.outbox).isEmpty)
+ #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("logbook.json").path))
+ }
+
+ @Test func turnedOnWithoutAcceptedTermsIsStillOff() {
+ let s = session(enabled: true, termsAccepted: false)
+ #expect(!s.isActive)
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 8, seconds: 30)
+ #expect(!s.monitor.isDiving)
+ s.acceptTerms()
+ #expect(s.isActive)
+ }
+
+ @Test func onARealDiveIsRecordedAndHandedOver() throws {
+ let s = session(enabled: true)
+ var ended: [(DiveLog?, Bool)] = []
+ s.onDiveEnded = { ended.append(($0, $1)) }
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 8, seconds: 120)
+ #expect(s.isComputing)
+ #expect(abs((s.depth ?? 0) - 8) < 0.01) // the computer's depth, in its water setting
+ stay(s, at: 0, seconds: 62)
+ #expect(!s.monitor.isDiving)
+
+ let dive = try #require(s.store.logbook.dives.first)
+ #expect(dive.computerModel == "Open Mérou")
+ #expect(dive.source == .remora)
+ #expect(abs(dive.maxDepth - 8) < 0.01)
+ // 1626 is the temperature inside the housing: it is not recorded as the water temperature.
+ #expect(dive.minTemperature == nil)
+ #expect(ended.count == 1)
+ #expect(ended.first?.0?.id == dive.id)
+ #expect(ended.first?.1 == false)
+
+ // Without the app group, the pair of files stays in the app's Documents.
+ #expect(!s.store.sharedFolderAvailable)
+ #expect(s.store.outbox == folder.appendingPathComponent("Dives", isDirectory: true))
+ #expect(files(in: s.store.outbox) == ["\(dive.id.uuidString).json", "\(dive.id.uuidString).uddf"])
+ #expect(s.store.pending == 1)
+ let json = try Data(contentsOf: s.store.outbox.appendingPathComponent("\(dive.id.uuidString).json"))
+ #expect(try DiveStore.decoder.decode(DiveLog.self, from: json) == dive)
+ let uddf = try String(contentsOf: s.store.outbox.appendingPathComponent("\(dive.id.uuidString).uddf"), encoding: .utf8)
+ #expect(uddf.contains("<name>Open Mérou</name>"))
+
+ // The logbook survives a relaunch (tissues for a repetitive dive).
+ let again = DiveStore(folder: folder, sharedContainer: nil)
+ #expect(again.logbook.dives.map(\.id) == [dive.id])
+ #expect(again.lastDive?.tissuesAfter != nil)
+ }
+
+ @Test func divesGoToTheSharedFolderWhenItExists() throws {
+ // A dive kept in Documents while the app group was missing…
+ let first = session(enabled: true)
+ stay(first, at: 0, seconds: 3)
+ stay(first, at: 6, seconds: 60)
+ stay(first, at: 0, seconds: 62)
+ #expect(files(in: folder.appendingPathComponent("Dives")).count == 2)
+
+ // …moves to the shared folder once the group is there, and new dives go straight to it.
+ let group = FileManager.default.temporaryDirectory.appendingPathComponent("merou-group-\(UUID().uuidString)")
+ let s = session(enabled: true, shared: group)
+ let outbox = group.appendingPathComponent("OpenMerou/Dives", isDirectory: true)
+ #expect(s.store.sharedFolderAvailable)
+ #expect(s.store.outbox == outbox)
+ #expect(files(in: outbox).count == 2)
+ #expect(files(in: folder.appendingPathComponent("Dives")).isEmpty)
+ clock.offset += 3 * 3600
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 6, seconds: 60)
+ stay(s, at: 0, seconds: 62)
+ #expect(files(in: outbox).count == 4)
+ #expect(s.store.pending == 2)
+ #expect(s.store.logbook.dives.count == 2)
+ #expect(s.store.logbook.dives.last?.surfaceIntervalBefore != nil) // repetitive dive: tissues carried over
+ }
+
+ @Test func aSimulatedDiveIsNeverSavedNorShared() {
+ let s = session(enabled: true)
+ var ended: [(DiveLog?, Bool)] = []
+ s.onDiveEnded = { ended.append(($0, $1)) }
+ stay(s, at: 0, seconds: 3, simulated: true)
+ stay(s, at: 8, seconds: 120, simulated: true)
+ #expect(s.isComputing) // the simulation does show the computer
+ stay(s, at: 0, seconds: 62, simulated: true)
+ #expect(!s.monitor.isDiving)
+ #expect(ended.count == 1)
+ #expect(ended.first?.0?.source == .simulation)
+ #expect(ended.first?.1 == true)
+ #expect(s.store.logbook.dives.isEmpty)
+ #expect(files(in: s.store.outbox).isEmpty)
+ #expect(s.store.pending == 0)
+ }
+
+ @Test func linkLostUnderwaterMakesTheDepthUnknownUntilTheHousingIsBack() {
+ let s = session(enabled: true)
+ var cues: [DiveCue] = []
+ s.onCue = { cues.append($0) }
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 15, seconds: 60)
+ #expect(!s.monitor.isAlarming)
+ s.linkLost()
+ #expect(s.monitor.depthUnknown)
+ #expect(s.monitor.isAlarming)
+ #expect(cues.contains(.depthLost))
+ #expect(abs((s.monitor.status?.depth ?? 0) - 15) < 0.01) // last known depth held
+ #expect(s.monitor.isDiving)
+ stay(s, at: 14, seconds: 2)
+ #expect(!s.monitor.depthUnknown)
+ }
+
+ @Test func linkLostWithTheComputerOffDoesNothing() {
+ let s = session(enabled: false)
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 15, seconds: 10)
+ s.linkLost()
+ #expect(!s.monitor.isDiving)
+ #expect(!s.monitor.depthUnknown)
+ }
+
+ @Test func depthLimitWarningIsAtFortyMetres() {
+ let s = session(enabled: true)
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 39, seconds: 5)
+ #expect(!s.monitor.warnings.contains(.depthLimit)) // the watch warns at 38 m
+ stay(s, at: 40.2, seconds: 5)
+ #expect(s.monitor.warnings.contains(.depthLimit))
+ }
+
+ @Test func implausibleSensorNeverStartsADive() {
+ let s = session(enabled: true)
+ for value in [0.0, 12.0, 9_940, 3_000_000] {
+ s.pressure(pa: value, time: clock.date.timeIntervalSinceReferenceDate, simulated: false)
+ clock.ticks += 3
+ }
+ #expect(s.sensorImplausible)
+ #expect(!s.monitor.isDiving)
+ #expect(s.depth == nil)
+ }
+
+ @Test func aNewHousingSessionEndsTheDiveAndMeasuresTheSurfaceAgain() {
+ let s = session(enabled: true)
+ stay(s, at: 0, seconds: 3)
+ stay(s, at: 8, seconds: 60)
+ s.reset()
+ #expect(!s.monitor.isDiving)
+ #expect(s.source.surfacePa == nil)
+ #expect(s.store.logbook.dives.count == 1) // what was dived is kept
+ }
+
+ @Test func shotCommentCarriesTheBasicDiveInformation() {
+ let off = session(enabled: false)
+ stay(off, at: 0, seconds: 3)
+ #expect(off.shotComment(housingTemperature: 21) == nil) // at the surface: nothing to write
+ stay(off, at: 8, seconds: 65)
+ #expect(off.shotComment(housingTemperature: 21.26)
+ == "Open Mérou: depth 8.2 m (estimated), dive time 1:05, temperature inside the housing 21.3 °C")
+
+ let on = session(enabled: true)
+ stay(on, at: 0, seconds: 3)
+ stay(on, at: 8, seconds: 65)
+ #expect(on.shotComment(housingTemperature: nil) == "Open Mérou: depth 8.0 m, dive time 1:05")
+ }
+}
diff --git a/OpenMerouTests/HousingDepthSourceTests.swift b/OpenMerouTests/HousingDepthSourceTests.swift
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+import RemoraDeco
+import Testing
+@testable import OpenMerou
+
+/// The adapter between the housing's external pressure (1625, Pa) and the dive logic of RemoraKit.
+struct HousingDepthSourceTests {
+ let t0 = Date(timeIntervalSince1970: 1_000_000)
+ /// Pa per metre of fresh water, as the basic depth estimate uses.
+ let perMetre = 9_806.65
+
+ @Test func surfaceIsTheLowestPressureSeenAndReadingsAreInBar() throws {
+ var source = HousingDepthSource()
+ _ = source.pressure(99_450, time: 0, now: t0)
+ _ = source.pressure(99_400, time: 1, now: t0 + 1)
+ let sample = source.pressure(99_400 + 10 * perMetre, time: 2, now: t0 + 2)
+ let reading = try #require(sample)
+ guard case .pressure(let time, let surface, let absolute, let submerged) = reading else {
+ Issue.record("not a pressure reading")
+ return
+ }
+ #expect(time == 2)
+ #expect(abs(surface - 0.994) < 1e-9)
+ #expect(abs((absolute ?? 0) - 1.974665) < 1e-6)
+ #expect(submerged)
+ #expect(source.surfacePa == 99_400)
+ #expect(!source.surfaceAssumed)
+ // The surface does not follow the pressure down the water column.
+ _ = source.pressure(250_000, time: 3, now: t0 + 3)
+ #expect(source.surfacePa == 99_400)
+ }
+
+ @Test func atTheSurfaceTheReadingIsNotSubmerged() throws {
+ var source = HousingDepthSource()
+ let sample = source.pressure(99_400, time: 0, now: t0)
+ let reading = try #require(sample)
+ #expect(reading == .pressure(time: 0, surface: 0.994, absolute: 0.994, submerged: false))
+ // A few centimetres of water or a weather change is not a dive.
+ _ = source.pressure(99_400 + 2_000, time: 1, now: t0 + 1)
+ #expect(!source.submerged)
+ }
+
+ @Test func valuesThatCannotBeAPressureAreIgnored() {
+ var source = HousingDepthSource()
+ // 1625 is a hypothesis: zero, a counter, anything out of range must never reach the dive computer.
+ for value in [0.0, 120.0, 49_999, 5_000_000] {
+ #expect(source.pressure(value, time: 0, now: t0) == nil)
+ #expect(source.implausible)
+ }
+ #expect(source.surfacePa == nil)
+ #expect(source.depth == nil)
+ #expect(source.pressure(99_400, time: 1, now: t0) != nil)
+ #expect(!source.implausible)
+ }
+
+ @Test func startedUnderwaterAssumesTheStandardAtmosphere() throws {
+ var source = HousingDepthSource()
+ // First value at about 10 m: it cannot be a surface pressure (the kit refuses one above 1.2 bar).
+ let sample = source.pressure(200_000, time: 0, now: t0)
+ let reading = try #require(sample)
+ #expect(source.surfaceAssumed)
+ #expect(reading == .pressure(time: 0, surface: standardSurfacePressure, absolute: 2.0, submerged: true))
+ // Back at the surface, the real pressure replaces the assumption.
+ _ = source.pressure(99_400, time: 600, now: t0 + 600)
+ #expect(source.surfacePa == 99_400)
+ #expect(!source.surfaceAssumed)
+ }
+
+ @Test func linkLostUnderwaterSaysSubmergedWithoutMeasurement() {
+ var source = HousingDepthSource()
+ _ = source.pressure(99_400, time: 0, now: t0)
+ #expect(source.linkLost(time: 1) == nil) // at the surface: nothing to say
+ _ = source.pressure(99_400 + 1 * perMetre, time: 2, now: t0 + 2)
+ #expect(source.linkLost(time: 3) == nil) // 1 m: out of the water for the watchdog
+ _ = source.pressure(99_400 + 12 * perMetre, time: 4, now: t0 + 4)
+ #expect(source.linkLost(time: 5) == .pressure(time: 5, surface: 0.994, absolute: nil, submerged: true))
+ }
+
+ @Test func basicDepthAndDiveTime() {
+ var source = HousingDepthSource()
+ _ = source.pressure(99_400, time: 0, now: t0)
+ #expect(source.depth == 0)
+ #expect(source.diveStart == nil)
+ _ = source.pressure(99_400 + 0.4 * perMetre, time: 1, now: t0 + 1)
+ #expect(source.diveStart == nil)
+ _ = source.pressure(99_400 + 6 * perMetre, time: 2, now: t0 + 2)
+ #expect(abs((source.depth ?? 0) - 6) < 1e-9)
+ #expect(source.diveStart == t0 + 2)
+ _ = source.pressure(99_400 + 0.3 * perMetre, time: 3, now: t0 + 3)
+ #expect(source.diveStart == t0 + 2) // hysteresis: still in the dive
+ _ = source.pressure(99_400, time: 4, now: t0 + 4)
+ #expect(source.diveStart == nil)
+ }
+}
diff --git a/README.md b/README.md
@@ -1,7 +1,8 @@
# Open Mérou
A free, open-source iOS app for the Oceanic+ dive housing: buttons, vacuum pump, sensors and camera with
-color correction, without a subscription.
+color correction, without a subscription. It can also act as a secondary dive computer (optional, off by
+default).
The Bluetooth protocol of the housing was reverse-engineered, for interoperability, from the exchanges
between the housing and the official app: see [docs/PROTOCOL.md](docs/PROTOCOL.md).
@@ -15,11 +16,36 @@ Version 0.4: automatic connection to the housing ("HUISH"); vacuum sequence guid
test corrected for temperature, continuous monitoring; camera driven by the buttons (full-resolution photo,
ProRAW, video up to what the iPhone can do, lenses, exposure, stabilization, sleep).
+## Dive computer (optional)
+
+Off by default: the app then only shows basic dive information (estimated depth, dive time, temperature
+inside the housing) and records nothing.
+
+Turned on from the home screen, after accepting its terms, it is the same computer as
+[Open Rémora](https://git.schurger.org/open-remora/) (Apple Watch): Bühlmann ZHL-16C with gradient factors, air
+or nitrox, from the shared [RemoraKit](https://git.schurger.org/remora-kit/) library, with the same settings,
+words, colours and alarms. **It is not a certified dive computer**: a secondary instrument, to be used with a
+primary dive computer. The depth comes from the housing's external pressure sensor, which has not been
+validated underwater yet.
+
+- Home screen (touch, before the housing is closed): gas and conservatism, settings, last dive and waiting
+ time before flying, dives pending for Sub Rascasse; "Start housing mode" starts the search, the vacuum
+ sequence and the camera.
+- Underwater (housing buttons only): a band over the camera shows depth, dive time, ascent rate and the NDL
+ or the stop to do. A long press up, or Menu → Dive computer, opens a full-screen page (left goes back).
+ The settings can be read in Menu → Information, not changed.
+- Alarms flash the whole screen red with a sound and wake the screen; the first button press silences the
+ sound. The leak alarm keeps priority.
+- Real dives are handed over to the Sub Rascasse logbook: see [docs/SHARING.md](docs/SHARING.md).
+- The basic dive information is written in the metadata of the photos and videos taken during a dive, whether
+ the computer is on or off (see docs/SHARING.md).
+
## Development
-XcodeGen project (`project.yml`), Swift 6, iOS 17. The Makefile assumes the author's setup: the sources are
-edited on a Linux host and synced with `rsync` to a Mac reachable over SSH as `chunga`, which runs Xcode. Set
-`CHUNGA` (the SSH host) and `REMOTE` (the directory on the Mac) to adapt it:
+XcodeGen project (`project.yml`), Swift 6, iOS 17. RemoraKit is a separate repository, expected next to this
+one (`../remora-kit`). The Makefile assumes the author's setup: the sources are edited on a Linux host and
+synced with `rsync` to a Mac reachable over SSH as `chunga`, which runs Xcode. Set `CHUNGA` (the SSH host),
+`REMOTE` (the directory on the Mac), `KIT` (RemoraKit here) and `REMOTE_KIT` (RemoraKit on the Mac) to adapt it:
```bash
make build # rsync to the Mac, xcodegen, build
@@ -33,6 +59,11 @@ English is the source language of the interface; the French translation lives in
`OpenMerou/Localizable.xcstrings` and `OpenMerou/InfoPlist.xcstrings`.
Launch options: `-simulation` (simulated housing from the start), `-demoMenu` (opens the settings menu).
+For the dive computer: `-diveComputer YES -acceptTerms` (on for this launch), `-simulateDive reef|deep|shallow`
+(simulated housing playing a dive on its pressure sensor; `-diveSkip <seconds>` jumps into it), `-computerPage`,
+`-testAlarm`, `-demoLogbook` (a past dive on the home screen), `-showDiveSettings`, `-showTerms`,
+`-noPermissionPrompts` (screenshots in the simulator). In the simulated housing, "Simulate a dive" does the
+same by touch.
Tools: `tools/pklg.py` decodes an iOS Bluetooth log (PacketLogger, sysdiagnose).
diff --git a/docs/SHARING.md b/docs/SHARING.md
@@ -0,0 +1,64 @@
+# Dives from Open Mérou to Sub Rascasse
+
+Sub Rascasse is the logbook. When its optional dive computer is on, Open Mérou records each dive and drops
+it in a folder shared with Sub Rascasse, exactly as Open Rémora (the watch app) does: same app group, same
+pair of files, another folder.
+
+## What is shared, and when
+
+- Only with the dive computer **on** (terms accepted) and only **real** dives. With the computer off nothing
+ is recorded at all. Dives played on the simulated housing are never saved nor shared.
+- A dive is recorded once the housing went below 1 m, and ends after one minute at the surface (or when the
+ housing session is restarted). Its files are written at that moment.
+
+## Where
+
+App group `group.org.schurger.dive` (team CM5RQKJH56), folder `OpenMerou/Dives/`, two files per dive:
+
+- `<uuid>.json`: the complete dive, a `DiveLog` from `RemoraDeco` (RemoraKit), ISO 8601 dates, sorted keys;
+- `<uuid>.uddf`: the same dive in UDDF 3.2 (profile, stops, alarms), readable without RemoraKit; its
+ generator name is "Open Mérou".
+
+The folder name is part of the contract: do not rename it. (Open Rémora uses `OpenRemora/Plongees/` in the
+same group.)
+
+The group is declared in `project.yml` (`com.apple.security.application-groups`) and must be attached to
+`org.schurger.openmerou` on the developer portal. When the container is not available (simulator, unsigned
+build, profile without the group), the same two files are written to the app's own
+`Documents/DiveComputer/Dives/` instead, visible in the Files app; they are moved to the shared folder at
+the first launch that finds it.
+
+## What Sub Rascasse has to do (other repository)
+
+- At launch, when returning to the foreground, and when opened with `subrascasse://open-merou` (the
+ "Open Sub Rascasse" button of the home screen): read `OpenMerou/Dives/*.json` (or `*.uddf`), add the dives to
+ the logbook, then **delete both files**. Open Mérou counts the remaining `.json` files as "pending".
+- A diver may wear the watch and carry the housing on the same dive: both apps then hand over a dive with
+ about the same start time. Merging them is Sub Rascasse's decision (Open Rémora has priority).
+
+## Useful JSON fields
+
+`id` (UUID), `number`, `start`, `surfacePressure` (bar), `surfaceIntervalBefore` (min), `gas.o2`,
+`gradientFactors.low|high`, `water`, `samples[]` (`time` s, `depth` m, `ceiling` m, `noDecompressionLimit`
+min, `stopDepth`, `stopMinutes`), `events[]` (`time`, `warning`), `tissuesAfter` (16 nitrogen pressures, bar),
+`computerModel` = "Open Mérou", `source` = "remora" (recorded by the RemoraKit engine).
+
+Differences from an Open Rémora dive:
+
+- `samples[].temperature` is absent: the housing only measures the temperature **inside** itself, which is
+ not the water temperature.
+- `surfacePressure` is the lowest pressure the housing's external sensor reported before the dive. That
+ sensor (characteristic 1625, see `docs/PROTOCOL.md`) is read through a reverse-engineered protocol and has
+ not been validated underwater yet.
+
+## Photos and videos
+
+Independently of the logbook, and whether the dive computer is on or off, each photo or video taken during a
+dive carries the basic dive information as text, in English:
+
+ Open Mérou: depth 12.3 m, dive time 12:34, temperature inside the housing 21.0 °C
+
+("depth 12.3 m (estimated)" when the dive computer is off). Photos (HEIC and ProRAW DNG): Exif `UserComment`.
+Videos: QuickTime metadata `com.apple.quicktime.comment`, with the values at the start of the recording.
+ImageIO offers no key for the Exif 2.31 `WaterDepth`, `Temperature` and `Pressure` tags, so they are not
+written.
diff --git a/project.yml b/project.yml
@@ -7,6 +7,11 @@ options:
developmentLanguage: en
deploymentTarget:
iOS: "17.0"
+# RemoraKit (decompression engine, dive logic, shared dive interface) is a separate repository, checked out
+# next to this one.
+packages:
+ RemoraKit:
+ path: ../remora-kit
settings:
base:
DEVELOPMENT_TEAM: CM5RQKJH56
@@ -20,6 +25,19 @@ targets:
platform: iOS
sources:
- path: OpenMerou
+ dependencies:
+ - package: RemoraKit
+ product: RemoraDeco
+ - package: RemoraKit
+ product: RemoraUI
+ entitlements:
+ path: OpenMerou/OpenMerou.entitlements
+ properties:
+ # Folder shared with Sub Rascasse (same team), where the dive computer drops its dives: see
+ # docs/SHARING.md. The group is attached to org.schurger.openmerou by hand on the developer portal
+ # (the API key cannot do it). Without the container (simulator, unsigned build) the dives stay in
+ # Documents/DiveComputer/Dives.
+ com.apple.security.application-groups: [group.org.schurger.dive]
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: org.schurger.openmerou