commit a55e5a48497424db4895230e3b2fdb4d89bb1906
parent 1495d1360b16578291e02027e0931de1bb677f87
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 09:11:09 -0500
Action button while diving (StartDiveIntent + next action: next page, heading set on the compass, test counter), "Ready to dive" starts Apple's dive session (screen locked, long press on the crown), system session adopted on submersion, last-test diagnostics on the home screen; version 0.4
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYJa9LG8PgUSQ5UR5LY
Diffstat:
7 files changed, 256 insertions(+), 10 deletions(-)
diff --git a/OpenRemoraWatch/DiveIntents.swift b/OpenRemoraWatch/DiveIntents.swift
@@ -0,0 +1,38 @@
+import AppIntents
+
+/// Bouton Action de l'Apple Watch Ultra (Réglages > Bouton Action > Plongée > Open Rémora).
+/// Première pression : lance l'app et fait « Prêt à plonger ». Pressions suivantes, y compris sous l'eau
+/// où l'écran tactile est verrouillé : `DiveActionIntent`.
+struct StartDiveSessionIntent: StartDiveIntent {
+ static let title: LocalizedStringResource = "Prêt à plonger"
+
+ @MainActor
+ func perform() async throws -> some IntentResult {
+ DiveSession.current?.getReady()
+ return .result(actionButtonIntent: DiveActionIntent())
+ }
+}
+
+/// Pression du bouton Action pendant la séance de plongée.
+struct DiveActionIntent: AppIntent {
+ static let title: LocalizedStringResource = "Action de plongée"
+
+ @MainActor
+ func perform() async throws -> some IntentResult {
+ DiveSession.current?.actionPressed()
+ return .result()
+ }
+}
+
+enum ActionButton {
+ /// Séance démarrée depuis l'écran (pas depuis le bouton Action) : on donne quand même l'action suivante
+ /// au système, pour que le bouton Action arrive à l'app pendant la plongée.
+ static func offerNextAction() async -> String? {
+ do {
+ try await StartDiveSessionIntent().donate(result: .result(actionButtonIntent: DiveActionIntent()))
+ return nil
+ } catch {
+ return error.localizedDescription
+ }
+ }
+}
diff --git a/OpenRemoraWatch/DiveRuntime.swift b/OpenRemoraWatch/DiveRuntime.swift
@@ -0,0 +1,69 @@
+import Foundation
+import WatchKit
+
+/// Session de plongée d'Apple (`WKExtendedRuntimeSession`, mode `underwater-depth`) : garde l'app au premier
+/// plan pendant toute la plongée et verrouille l'écran tactile (Water Lock, « mode immergé »). Le plongeur en
+/// sort par un appui long sur la couronne, ce qui termine la session ; elle expire aussi après 10 min hors de
+/// l'eau. Si l'app n'en démarre pas, le système en démarre une sous 1 m et la passe au délégué de l'app.
+@MainActor
+final class DiveRuntime: NSObject, @preconcurrency WKExtendedRuntimeSessionDelegate {
+ private var session: WKExtendedRuntimeSession?
+ /// Changement d'état (true = session en cours, donc écran verrouillé), avec un texte pour le diagnostic.
+ var onChange: ((Bool, String) -> Void)?
+
+ var isRunning: Bool { session?.state == .running }
+
+ func start() {
+ guard session == nil || session?.state == .invalid else { return }
+ let session = WKExtendedRuntimeSession()
+ session.delegate = self
+ self.session = session
+ session.start()
+ onChange?(false, "demandée")
+ }
+
+ /// Session démarrée par le système à l'immersion.
+ func adopt(_ session: WKExtendedRuntimeSession) {
+ session.delegate = self
+ self.session = session
+ onChange?(session.state == .running, "démarrée par le système")
+ }
+
+ func stop() {
+ session?.invalidate()
+ session = nil
+ }
+
+ func extendedRuntimeSessionDidStart(_ extendedRuntimeSession: WKExtendedRuntimeSession) {
+ onChange?(true, "en cours")
+ }
+
+ func extendedRuntimeSessionWillExpire(_ extendedRuntimeSession: WKExtendedRuntimeSession) {
+ onChange?(true, "va expirer")
+ }
+
+ func extendedRuntimeSession(_ extendedRuntimeSession: WKExtendedRuntimeSession,
+ didInvalidateWith reason: WKExtendedRuntimeSessionInvalidationReason,
+ error: (any Error)?) {
+ guard extendedRuntimeSession === session || session == nil else { return }
+ session = nil
+ let why: String
+ switch reason {
+ case .none: why = "terminée"
+ case .sessionInProgress: why = "refusée : une autre session tourne"
+ case .expired: why = "expirée"
+ case .resignedFrontmost: why = "terminée : l'app a quitté le premier plan"
+ case .suppressedBySystem: why = "refusée par le système"
+ case .error: why = "erreur"
+ @unknown default: why = "terminée (raison \(reason.rawValue))"
+ }
+ onChange?(false, error.map { "\(why) (\($0.localizedDescription))" } ?? why)
+ }
+}
+
+/// Reçoit la session que le système démarre seul quand la montre passe sous 1 m.
+final class AppDelegate: NSObject, WKApplicationDelegate {
+ func handle(_ extendedRuntimeSession: WKExtendedRuntimeSession) {
+ Task { @MainActor in DiveSession.current?.runtime.adopt(extendedRuntimeSession) }
+ }
+}
diff --git a/OpenRemoraWatch/DiveSession.swift b/OpenRemoraWatch/DiveSession.swift
@@ -41,11 +41,30 @@ final class DiveSession {
/// Avertissements en cours (sans les violations) : seule la valeur concernée clignote.
var activeWarnings: Set<DiveComputer.Warning> { warnings.filter { !$0.isViolation } }
let workout = DiveWorkout()
+ /// Session de plongée d'Apple : app au premier plan et écran tactile verrouillé.
+ let runtime = DiveRuntime()
+ /// Écran tactile verrouillé par la session de plongée (appui long sur la couronne pour en sortir).
+ private(set) var screenLocked = false
+ /// Page de l'écran de plongée (0 principale, 1 détails, 2 boussole) : couronne ou bouton Action.
+ var divePage = 0
+ /// Bandeau affiché quelques secondes après une pression du bouton Action.
+ private(set) var actionMessage: String?
+ private var actionMessageTask: Task<Void, Never>?
+ /// Boussole (le bouton Action y fixe le cap).
+ var compass: Compass?
+ let diagnostics = Diagnostics()
+ /// La session de l'app, pour les intentions du bouton Action et le délégué de l'app.
+ static weak var current: DiveSession?
/// Appelé après chaque plongée enregistrée (envoi vers l'iPhone).
var onDiveSaved: (() -> Void)?
init(store: LogStore) {
self.store = store
+ Self.current = self
+ runtime.onChange = { [weak self] locked, text in
+ self?.screenLocked = locked
+ self?.diagnostics.runtime = text
+ }
}
/// Niveau de batterie (0 à 1) ; nil si inconnu.
@@ -59,12 +78,47 @@ final class DiveSession {
func getReady() {
guard !isDiving, !isReady else { return }
isReady = true
+ diagnostics.reset()
workout.start()
+ startDiveSession()
+ }
+
+ /// Session de plongée d'Apple (écran verrouillé) et bouton Action branché sur l'app.
+ private func startDiveSession() {
+ guard SubmersionSource.isAvailable else { return }
+ runtime.start()
+ Task { [diagnostics] in
+ diagnostics.donation = await ActionButton.offerNextAction() ?? "donnée"
+ }
+ }
+
+ /// Bouton Action pendant la séance. Sur la page boussole : fixe le cap ; ailleurs : page suivante.
+ /// Chaque pression vibre, s'affiche et est comptée (essai : le bouton arrive-t-il à l'app sous l'eau ?).
+ func actionPressed() {
+ guard isReady || isDiving else { return }
+ WKInterfaceDevice.current().play(.click)
+ diagnostics.notePress(depth: isDiving ? status?.depth : nil)
+ var text = "BOUTON ACTION \(diagnostics.presses)"
+ if isDiving {
+ if divePage == 2, let compass, let heading = compass.heading {
+ compass.setBearing()
+ text = "CAP FIXÉ \(Int(heading.rounded()) % 360)°"
+ } else {
+ divePage = (divePage + 1) % 3
+ }
+ }
+ actionMessage = text
+ actionMessageTask?.cancel()
+ actionMessageTask = Task { [weak self] in
+ try? await Task.sleep(for: .seconds(3))
+ if !Task.isCancelled { self?.actionMessage = nil }
+ }
}
func cancelReady() {
guard isReady, !isDiving else { return }
isReady = false
+ runtime.stop()
Task { await workout.finish(with: nil) }
}
@@ -134,9 +188,14 @@ final class DiveSession {
start: Date(), logbook: store.logbook)
isSimulation = simulation
isDiving = true
- isReady = false
// Plongée réelle sans « Prêt à plonger » : la séance démarre à l'immersion.
- if !simulation { workout.start() }
+ if !simulation, !isReady {
+ diagnostics.reset()
+ workout.start()
+ startDiveSession()
+ }
+ isReady = false
+ divePage = 0
self.surfacePressure = surfacePressure
lastPressure = nil
lastReadingAt = Date()
@@ -206,6 +265,7 @@ final class DiveSession {
guard let r = recorder else { return }
recorder = nil
isDiving = false
+ if !isSimulation { runtime.stop() }
guard wentUnder else {
if !isSimulation { Task { await workout.finish(with: nil) } }
return
@@ -238,3 +298,41 @@ final class DiveSession {
}
}
}
+
+/// Ce qu'on veut savoir après un essai dans l'eau : le bouton Action est-il arrivé à l'app, et la session de
+/// plongée d'Apple (écran verrouillé) a-t-elle tourné. Gardé d'un lancement à l'autre.
+@MainActor @Observable
+final class Diagnostics {
+ private let defaults = UserDefaults.standard
+ private(set) var presses: Int
+ private(set) var deepestPress: Double?
+ var runtime: String { didSet { defaults.set(runtime, forKey: "diag.runtime") } }
+ var donation: String { didSet { defaults.set(donation, forKey: "diag.donation") } }
+ private(set) var startedAt: Date?
+
+ init() {
+ presses = defaults.integer(forKey: "diag.presses")
+ deepestPress = defaults.object(forKey: "diag.deepest") as? Double
+ runtime = defaults.string(forKey: "diag.runtime") ?? "jamais demandée"
+ donation = defaults.string(forKey: "diag.donation") ?? "jamais donnée"
+ startedAt = defaults.object(forKey: "diag.start") as? Date
+ }
+
+ func reset() {
+ presses = 0
+ deepestPress = nil
+ startedAt = Date()
+ defaults.set(0, forKey: "diag.presses")
+ defaults.removeObject(forKey: "diag.deepest")
+ defaults.set(startedAt, forKey: "diag.start")
+ }
+
+ func notePress(depth: Double?) {
+ presses += 1
+ defaults.set(presses, forKey: "diag.presses")
+ if let depth, depth > (deepestPress ?? -1) {
+ deepestPress = depth
+ defaults.set(depth, forKey: "diag.deepest")
+ }
+ }
+}
diff --git a/OpenRemoraWatch/DiveView.swift b/OpenRemoraWatch/DiveView.swift
@@ -8,15 +8,15 @@ import RemoraDeco
struct DiveView: View {
@Environment(DiveSession.self) private var session
@Environment(\.isLuminanceReduced) private var dimmed
- @State private var page = 0
var body: some View {
let s = session.status
+ @Bindable var session = session
Group {
if dimmed {
DimmedDivePage(status: s)
} else {
- TabView(selection: $page) {
+ TabView(selection: $session.divePage) {
MainDivePage(status: s).tag(0)
DetailsDivePage(status: s).tag(1)
CompassView(compact: true).tag(2)
@@ -41,13 +41,17 @@ struct DiveView: View {
}
}
.overlay(alignment: .top) {
- if let message = session.sensorMessage {
+ if let action = session.actionMessage {
+ Text(action).font(.system(size: 14, weight: .heavy, design: .rounded))
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .background(.cyan, in: Capsule()).foregroundStyle(.black)
+ } else if let message = session.sensorMessage {
Text(message).font(.caption2).padding(3).background(.orange, in: Capsule())
}
}
.task {
- if CommandLine.arguments.contains("-page2") { page = 1 }
- if CommandLine.arguments.contains("-page3") { page = 2 }
+ if CommandLine.arguments.contains("-page2") { session.divePage = 1 }
+ if CommandLine.arguments.contains("-page3") { session.divePage = 2 }
}
}
diff --git a/OpenRemoraWatch/OpenRemoraApp.swift b/OpenRemoraWatch/OpenRemoraApp.swift
@@ -5,13 +5,17 @@ import RemoraDeco
struct OpenRemoraApp: App {
@State private var store: LogStore
@State private var session: DiveSession
- @State private var compass = Compass()
+ @State private var compass: Compass
+ @WKApplicationDelegateAdaptor private var delegate: AppDelegate
private let phone: PhoneLink
init() {
let store = LogStore()
if CommandLine.arguments.contains("-demo") { store.seedDemo() }
let session = DiveSession(store: store)
+ let compass = Compass()
+ session.compass = compass
+ _compass = State(initialValue: compass)
let phone = PhoneLink(store: store)
session.onDiveSaved = { phone.sendPendingDives() }
store.onSettingsSaved = { phone.sendSettings() }
diff --git a/OpenRemoraWatch/RootView.swift b/OpenRemoraWatch/RootView.swift
@@ -18,7 +18,7 @@ struct RootView: View {
}
.listItemTint(.cyan)
} footer: {
- Text("Garde l'app ouverte jusqu'à la mise à l'eau. Sans ça, la plongée démarre quand même à l'immersion.")
+ Text("Démarre la séance de plongée et verrouille l'écran (appui long sur la couronne pour déverrouiller). Sans ça, la plongée démarre quand même à l'immersion.")
}
}
@@ -58,6 +58,10 @@ struct RootView: View {
} footer: {
Text("Ordinateur secondaire, non certifié. À utiliser avec un ordinateur de plongée principal.")
}
+
+ if session.sensorAvailable || CommandLine.arguments.contains("-demo") {
+ Section("Dernier essai") { DiagnosticsRows() }
+ }
}
.navigationTitle("Open Rémora")
.navigationDestination(for: DiveLog.self) { dive in
@@ -119,6 +123,14 @@ struct ReadyView: View {
Text("Prêt").font(.title3.bold())
Text("La plongée démarre à l'immersion").font(.footnote).foregroundStyle(.secondary)
.multilineTextAlignment(.center)
+ if let action = session.actionMessage {
+ Text(action).font(.system(size: 14, weight: .heavy, design: .rounded))
+ .padding(.horizontal, 8).padding(.vertical, 2)
+ .background(.cyan, in: Capsule()).foregroundStyle(.black)
+ } else if session.screenLocked {
+ Label("Écran verrouillé : appui long sur la couronne", systemImage: "lock.fill")
+ .font(.caption2).foregroundStyle(.cyan).multilineTextAlignment(.center)
+ }
Text("\(store.settings.gas.description) · \(store.settings.gradientFactors.description)")
.font(.footnote)
let mod = store.settings.maximumOperatingDepth()
@@ -138,3 +150,24 @@ struct ReadyView: View {
}
}
}
+
+/// Résultat du dernier essai : bouton Action reçu par l'app, session de plongée d'Apple.
+struct DiagnosticsRows: View {
+ @Environment(DiveSession.self) private var session
+
+ var body: some View {
+ let d = session.diagnostics
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Bouton Action : \(d.presses) pression\(d.presses > 1 ? "s" : "") reçue\(d.presses > 1 ? "s" : "")")
+ if let depth = d.deepestPress {
+ Text("la plus profonde à \(Format.depth(depth)) m").foregroundStyle(.secondary)
+ }
+ Text("Action suivante : \(d.donation)").foregroundStyle(.secondary)
+ Text("Session de plongée : \(d.runtime)").foregroundStyle(.secondary)
+ if let start = d.startedAt {
+ Text(start.formatted(date: .abbreviated, time: .shortened)).foregroundStyle(.secondary)
+ }
+ }
+ .font(.caption2)
+ }
+}
diff --git a/project.yml b/project.yml
@@ -13,7 +13,7 @@ settings:
base:
DEVELOPMENT_TEAM: CM5RQKJH56
CODE_SIGN_STYLE: Automatic
- MARKETING_VERSION: "0.3"
+ MARKETING_VERSION: "0.4"
CURRENT_PROJECT_VERSION: "1"
SWIFT_VERSION: "6.0"
targets: