open-merou

Open Mérou, a free iOS app for the Oceanic+ underwater iPhone housing
git clone https://git.schurger.org/open-merou.git
Log | Files | Refs | README | LICENSE

commit fea430125a3f8b6e901ab9c22c5235395c1c114c
parent c2bef33b4659da42fe428bfac02ad16debdbcbb4
Author: Jean Schurger <jean@schurger.org>
Date:   Fri, 13 Nov 2026 14:41:40 -0500

0.4: camera driven by the buttons (photo, video, lenses, menu, settings, sleep), dry run

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYGSNhtY1AmBH7DQGNs

Diffstat:
AOpenMerou/App/AppModel.swift | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MOpenMerou/App/OpenMerouApp.swift | 5+++--
AOpenMerou/Camera/CameraEngine.swift | 340+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenMerou/Camera/CameraSettings.swift | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MOpenMerou/Housing/HousingClient.swift | 6++++++
MOpenMerou/Housing/VacuumSequence.swift | 16++++++++++++++++
MOpenMerou/Info.plist | 6++++++
AOpenMerou/UI/CameraScreen.swift | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MOpenMerou/UI/HousingView.swift | 4----
MOpenMerou/UI/VacuumView.swift | 5++++-
AOpenMerouTests/CameraMenuTests.swift | 49+++++++++++++++++++++++++++++++++++++++++++++++++
MREADME.md | 5+++--
Mfastlane/Fastfile | 4++--
Mproject.yml | 2+-
14 files changed, 901 insertions(+), 12 deletions(-)

diff --git a/OpenMerou/App/AppModel.swift b/OpenMerou/App/AppModel.swift @@ -0,0 +1,85 @@ +// Relie le boîtier à la caméra : les boutons que la séquence de mise sous vide laisse libres +// pilotent la prise de vue, le menu et la veille de l'écran. +import Observation +import SwiftUI +import UIKit + +@MainActor +@Observable +final class AppModel { + let housing = HousingClient() + @ObservationIgnored let engine = CameraEngine() + private(set) var camera = CameraState() + private(set) var settings = CameraSettings.load() + private(set) var menu = CameraMenu() + private(set) var sleeping = false + @ObservationIgnored private var lastActivity = Date() + @ObservationIgnored private var awakeBrightness: CGFloat = 0.5 + @ObservationIgnored private var sleepTask: Task<Void, Never>? + + func start() { + UIApplication.shared.isIdleTimerDisabled = true // l'écran ne se verrouille jamais tout seul + engine.onState = { [weak self] state in self?.camera = state } + engine.start(settings) + housing.cameraButton = { [weak self] event in self?.button(event) } + sleepTask = Task { [weak self] in + while !Task.isCancelled { + try? await Task.sleep(for: .seconds(1)) + self?.checkSleep() + } + } + } + + private func checkSleep() { + guard !sleeping, settings.sleepAfter > 0, camera.recordingSince == nil, housing.vacuum.cameraHasButtons, + Date().timeIntervalSince(lastActivity) > Double(settings.sleepAfter) else { return } + sleep() + } + + private func sleep() { + awakeBrightness = UIScreen.main.brightness + UIScreen.main.brightness = 0 + sleeping = true + } + + func wake() { + lastActivity = Date() + guard sleeping else { return } + UIScreen.main.brightness = awakeBrightness + sleeping = false + } + + func button(_ event: ButtonEvent) { + if sleeping { wake(); return } // le premier appui ne fait que réveiller l'écran + lastActivity = Date() + if menu.isOpen { + guard !event.isLong else { return } + let before = settings + switch menu.handle(event.button, settings: &settings, caps: camera.capabilities) { + case .setMode(let mode): + settings.mode = mode + if mode == .video { engine.requestMicrophone() } + case .sleepNow: sleep() + case .none, .close, .changed: break + } + if settings != before { + settings.save() + engine.apply(settings) + } + return + } + guard !event.isLong else { return } + switch event.button { + case .shutter: settings.mode == .photo ? engine.capturePhoto() : engine.toggleRecording() + case .up: engine.cycleLens(1) + case .down: engine.cycleLens(-1) + case .right: if camera.recordingSince == nil { menu.open() } + case .left: break + } + } + + func background() { + engine.stopForBackground() + if sleeping { wake() } + } +} diff --git a/OpenMerou/App/OpenMerouApp.swift b/OpenMerou/App/OpenMerouApp.swift @@ -2,11 +2,12 @@ import SwiftUI @main struct OpenMerouApp: App { - @State private var housing = HousingClient() + @State private var model = AppModel() var body: some Scene { WindowGroup { - HousingView(housing: housing) + CameraScreen(model: model) + .task { model.start() } } } } diff --git a/OpenMerou/Camera/CameraEngine.swift b/OpenMerou/Camera/CameraEngine.swift @@ -0,0 +1,340 @@ +// Prise de vue : interroge l'iPhone présent et utilise ce qu'il sait faire (objectifs, pleine +// résolution, ProRAW, formats vidéo, stabilisation). Tout le travail AVFoundation se fait sur une +// file série ; l'état remonte par `onState` sur la file principale. +@preconcurrency import AVFoundation +import Photos +import UIKit + +struct CameraState: Equatable, Sendable { + var authorized = true + var running = false + var capabilities = CameraCapabilities() + var zoomIndex = 0 + var recordingSince: Date? + var shots = 0 + var message: String? +} + +final class CameraEngine: NSObject, @unchecked Sendable { + let session = AVCaptureSession() + let previewLayer: AVCaptureVideoPreviewLayer + var onState: (@MainActor @Sendable (CameraState) -> Void)? + + private let queue = DispatchQueue(label: "org.schurger.openmerou.camera") + private var device: AVCaptureDevice? + private var photoOutput = AVCapturePhotoOutput() + private var movieOutput = AVCaptureMovieFileOutput() + private var audioInput: AVCaptureDeviceInput? + private var zoomFactors: [CGFloat] = [1] + private var settings = CameraSettings() + private var state = CameraState() + private var photoDelegates: [Int64: PhotoDelegate] = [:] + private var rotation: AVCaptureDevice.RotationCoordinator? + private var rotationObservation: NSKeyValueObservation? + + override init() { + previewLayer = AVCaptureVideoPreviewLayer(session: session) + previewLayer.videoGravity = .resizeAspect + super.init() + } + + private func publish() { + let snapshot = state, sink = onState + DispatchQueue.main.async { MainActor.assumeIsolated { sink?(snapshot) } } + } + + private func say(_ text: String) { + state.message = text + publish() + } + + // MARK: Démarrage + + func start(_ settings: CameraSettings) { + AVCaptureDevice.requestAccess(for: .video) { [self] granted in + queue.async { [self] in + self.settings = settings + guard granted else { state.authorized = false; publish(); return } + configure() + session.startRunning() + state.running = session.isRunning + publish() + } + } + } + + private func configure() { + // Le périphérique virtuel le plus complet : il change d'objectif tout seul selon le zoom. + let types: [AVCaptureDevice.DeviceType] = [.builtInTripleCamera, .builtInDualWideCamera, .builtInDualCamera, .builtInWideAngleCamera] + guard let device = AVCaptureDevice.DiscoverySession(deviceTypes: types, mediaType: .video, position: .back).devices.first, + let input = try? AVCaptureDeviceInput(device: device) else { + say("Aucun appareil photo") + return + } + self.device = device + session.beginConfiguration() + if session.canAddInput(input) { session.addInput(input) } + if session.canAddOutput(photoOutput) { session.addOutput(photoOutput) } + if session.canAddOutput(movieOutput) { session.addOutput(movieOutput) } + session.commitConfiguration() + + // Crans de zoom : chaque objectif, plus le recadrage ×2 du grand-angle et du téléobjectif. + let switchOvers = device.virtualDeviceSwitchOverVideoZoomFactors.map { CGFloat(truncating: $0) } + let hasUltraWide = device.deviceType == .builtInTripleCamera || device.deviceType == .builtInDualWideCamera + let wide = hasUltraWide ? (switchOvers.first ?? 1) : 1 + let natives = [1] + switchOvers + var stops = natives + natives.filter { $0 >= wide }.map { $0 * 2 } + stops = stops.filter { $0 <= device.maxAvailableVideoZoomFactor }.sorted() + zoomFactors = stops.reduce(into: [CGFloat]()) { kept, stop in + if let last = kept.last, abs(stop - last) <= 0.05 { return } + kept.append(stop) + } + state.capabilities.zoomLabels = zoomFactors.map { + let shown = Double($0 / wide) + return (shown == shown.rounded() ? String(format: "%.0f", shown) : String(format: "%.1f", shown)) + "×" + } + state.zoomIndex = zoomFactors.firstIndex { abs($0 - wide) < 0.05 } ?? 0 + + state.capabilities.qualities = VideoQuality.all.filter { format(for: $0, on: device) != nil } + state.capabilities.minBias = Double(device.minExposureTargetBias) + state.capabilities.maxBias = Double(device.maxExposureTargetBias) + + let coordinator = AVCaptureDevice.RotationCoordinator(device: device, previewLayer: previewLayer) + rotation = coordinator + let layer = previewLayer + rotationObservation = coordinator.observe(\.videoRotationAngleForHorizonLevelPreview, options: [.initial, .new]) { coordinator, _ in + let angle = coordinator.videoRotationAngleForHorizonLevelPreview + DispatchQueue.main.async { layer.connection?.videoRotationAngle = angle } + } + applyMode() + } + + private func format(for quality: VideoQuality, on device: AVCaptureDevice) -> AVCaptureDevice.Format? { + device.formats.last { format in + let dims = CMVideoFormatDescriptionGetDimensions(format.formatDescription) + let pixel = CMFormatDescriptionGetMediaSubType(format.formatDescription) + return dims.width == quality.width && dims.height == quality.height + && (pixel == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || pixel == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) + && format.videoSupportedFrameRateRanges.contains { $0.maxFrameRate >= Double(quality.fps) } + } + } + + // MARK: Réglages + + func apply(_ settings: CameraSettings) { + queue.async { [self] in + let modeChanged = settings.mode != self.settings.mode || settings.videoQuality != self.settings.videoQuality + || settings.photoFormat != self.settings.photoFormat + self.settings = settings + guard device != nil, !movieOutput.isRecording else { return } + if modeChanged { applyMode() } else { applyLight() } + publish() + } + } + + private func applyMode() { + guard let device else { return } + session.beginConfiguration() + switch settings.mode { + case .photo: + session.sessionPreset = .photo + case .video: + let quality = state.capabilities.qualities.contains(settings.videoQuality) + ? settings.videoQuality : (state.capabilities.qualities.last ?? settings.videoQuality) + if let format = format(for: quality, on: device), (try? device.lockForConfiguration()) != nil { + session.sessionPreset = .inputPriority + device.activeFormat = format + let duration = CMTime(value: 1, timescale: CMTimeScale(quality.fps)) + device.activeVideoMinFrameDuration = duration + device.activeVideoMaxFrameDuration = duration + device.unlockForConfiguration() + } + addMicrophone() + } + session.commitConfiguration() + + // Pleine résolution du capteur (48 Mpx quand l'iPhone l'offre) et ProRAW. + if let largest = device.activeFormat.supportedMaxPhotoDimensions.max(by: { $0.width * $0.height < $1.width * $1.height }) { + photoOutput.maxPhotoDimensions = largest + } + photoOutput.maxPhotoQualityPrioritization = .quality + state.capabilities.proRAW = photoOutput.isAppleProRAWSupported + photoOutput.isAppleProRAWEnabled = photoOutput.isAppleProRAWSupported && settings.photoFormat == .rawHeif + + let modes: [(Stabilization, AVCaptureVideoStabilizationMode)] = [(.off, .off), (.standard, .standard), (.cinematic, .cinematic), (.extended, .cinematicExtended)] + state.capabilities.stabilizations = modes.filter { $0.1 == .off || device.activeFormat.isVideoStabilizationModeSupported($0.1) }.map(\.0) + applyLight() + } + + /// Réglages qui ne demandent pas de reconfigurer la session. + private func applyLight() { + guard let device else { return } + if (try? device.lockForConfiguration()) != nil { + let bias = Float(settings.exposureBias) + device.setExposureTargetBias(min(max(bias, device.minExposureTargetBias), device.maxExposureTargetBias)) + device.videoZoomFactor = zoomFactors[state.zoomIndex] + device.unlockForConfiguration() + } + if let connection = movieOutput.connection(with: .video), connection.isVideoStabilizationSupported { + let wanted: AVCaptureVideoStabilizationMode = switch settings.stabilization { + case .off: .off + case .standard: .standard + case .cinematic: .cinematic + case .extended: .cinematicExtended + } + connection.preferredVideoStabilizationMode = device.activeFormat.isVideoStabilizationModeSupported(wanted) ? wanted : .standard + } + } + + private func addMicrophone() { + guard audioInput == nil, AVCaptureDevice.authorizationStatus(for: .audio) != .denied, + let mic = AVCaptureDevice.default(for: .audio), let input = try? AVCaptureDeviceInput(device: mic), + session.canAddInput(input) else { return } + session.addInput(input) + audioInput = input + } + + func requestMicrophone() { + AVCaptureDevice.requestAccess(for: .audio) { _ in } + } + + // MARK: Commandes + + func cycleLens(_ step: Int) { + queue.async { [self] in + guard device != nil, zoomFactors.count > 1 else { return } + state.zoomIndex = (state.zoomIndex + step + zoomFactors.count) % zoomFactors.count + applyLight() + publish() + } + } + + func capturePhoto() { + queue.async { [self] in + guard device != nil, session.isRunning else { return } + let heif: [String: Any] = [AVVideoCodecKey: AVVideoCodecType.hevc] + let raw = photoOutput.isAppleProRAWEnabled + ? photoOutput.availableRawPhotoPixelFormatTypes.first { AVCapturePhotoOutput.isAppleProRAWPixelFormat($0) } : nil + let photoSettings = raw.map { AVCapturePhotoSettings(rawPixelFormatType: $0, processedFormat: heif) } + ?? AVCapturePhotoSettings(format: heif) + photoSettings.maxPhotoDimensions = photoOutput.maxPhotoDimensions + photoSettings.photoQualityPrioritization = .quality + if let angle = rotation?.videoRotationAngleForHorizonLevelCapture, + let connection = photoOutput.connection(with: .video), connection.isVideoRotationAngleSupported(angle) { + connection.videoRotationAngle = angle + } + let delegate = PhotoDelegate { [weak self] id, result in + self?.queue.async { + self?.photoDelegates[id] = nil + switch result { + case .success: self?.state.shots += 1; self?.say("Photo enregistrée") + case .failure(let error): self?.say("Photo : \(error.localizedDescription)") + } + } + } + photoDelegates[photoSettings.uniqueID] = delegate + photoOutput.capturePhoto(with: photoSettings, delegate: delegate) + } + } + + func toggleRecording() { + queue.async { [self] in + guard device != nil, session.isRunning else { return } + if movieOutput.isRecording { + movieOutput.stopRecording() + return + } + if let angle = rotation?.videoRotationAngleForHorizonLevelCapture, + let connection = movieOutput.connection(with: .video), connection.isVideoRotationAngleSupported(angle) { + connection.videoRotationAngle = angle + } + if let connection = movieOutput.connection(with: .video), movieOutput.availableVideoCodecTypes.contains(.hevc) { + movieOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: connection) + } + let url = FileManager.default.temporaryDirectory.appendingPathComponent("merou-\(UUID().uuidString).mov") + movieOutput.startRecording(to: url, recordingDelegate: self) + state.recordingSince = Date() + publish() + } + } + + func stopForBackground() { + queue.async { [self] in + if movieOutput.isRecording { movieOutput.stopRecording() } + } + } +} + +extension CameraEngine: AVCaptureFileOutputRecordingDelegate { + func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo url: URL, from connections: [AVCaptureConnection], error: Error?) { + // Un enregistrement interrompu (disque plein, appel) laisse souvent un fichier valide : on le garde. + let usable = (error as NSError?)?.userInfo[AVErrorRecordingSuccessfullyFinishedKey] as? Bool ?? (error == nil) + queue.async { [self] in + state.recordingSince = nil + publish() + } + guard usable else { + queue.async { [self] in say("Vidéo : \(error?.localizedDescription ?? "échec")") } + return + } + Library.save { request in + let options = PHAssetResourceCreationOptions() + options.shouldMoveFile = true + request.addResource(with: .video, fileURL: url, options: options) + } done: { [weak self] problem in + self?.queue.async { + if problem == nil { self?.state.shots += 1 } + self?.say(problem.map { "Vidéo : \($0)" } ?? "Vidéo enregistrée") + } + } + } +} + +private final class PhotoDelegate: NSObject, AVCapturePhotoCaptureDelegate, @unchecked Sendable { + private let done: @Sendable (Int64, Result<Void, Error>) -> Void + private var processed: Data? + private var raw: Data? + + init(done: @escaping @Sendable (Int64, Result<Void, Error>) -> Void) { self.done = done } + + func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { + guard error == nil, let data = photo.fileDataRepresentation() else { return } + if photo.isRawPhoto { raw = data } else { processed = data } + } + + func photoOutput(_ output: AVCapturePhotoOutput, didFinishCaptureFor resolved: AVCaptureResolvedPhotoSettings, error: Error?) { + let id = resolved.uniqueID + guard error == nil, let processed else { + done(id, .failure(error ?? CocoaError(.fileWriteUnknown))) + return + } + let raw = raw, done = done + Library.save { request in + request.addResource(with: .photo, data: processed, options: nil) + if let raw { + let options = PHAssetResourceCreationOptions() + options.uniformTypeIdentifier = "com.adobe.raw-image" + request.addResource(with: .alternatePhoto, data: raw, options: options) + } + } done: { problem in + done(id, problem.map { .failure(NSError(domain: "OpenMerou", code: 1, userInfo: [NSLocalizedDescriptionKey: $0])) } ?? .success(())) + } + } +} + +/// Enregistrement dans la photothèque, avec le seul droit d'y ajouter. +enum Library { + static func save(_ fill: @escaping @Sendable (PHAssetCreationRequest) -> Void, done: @escaping @Sendable (String?) -> Void) { + PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in + guard status == .authorized || status == .limited else { + done("accès à la photothèque refusé") + return + } + PHPhotoLibrary.shared().performChanges { + fill(PHAssetCreationRequest.forAsset()) + } completionHandler: { ok, error in + done(ok ? nil : (error?.localizedDescription ?? "échec")) + } + } + } +} diff --git a/OpenMerou/Camera/CameraSettings.swift b/OpenMerou/Camera/CameraSettings.swift @@ -0,0 +1,190 @@ +// Réglages et menu de la caméra : logique pure, pilotée par les boutons du boîtier. +import Foundation + +enum CaptureMode: String, Codable, Sendable { case photo, video } +enum PhotoFormat: String, Codable, Sendable, CaseIterable { case heif, rawHeif } +enum Stabilization: String, Codable, Sendable, CaseIterable { case off, standard, cinematic, extended } + +struct VideoQuality: Codable, Equatable, Hashable, Sendable { + let height: Int + let fps: Int + + var width: Int { height == 720 ? 1280 : height == 1080 ? 1920 : 3840 } + var label: String { (height == 2160 ? "4K" : "\(height)p") + " · \(fps) i/s" } + + /// Du plus modeste au plus exigeant ; l'app ne propose que ce que l'iPhone sait faire. + static let all = [ + VideoQuality(height: 720, fps: 30), VideoQuality(height: 1080, fps: 30), VideoQuality(height: 1080, fps: 60), + VideoQuality(height: 2160, fps: 30), VideoQuality(height: 2160, fps: 60), VideoQuality(height: 2160, fps: 120), + ] +} + +struct CameraSettings: Codable, Equatable, Sendable { + var mode = CaptureMode.photo + var photoFormat = PhotoFormat.heif + var exposureBias = 0.0 + var stabilization = Stabilization.standard + var videoQuality = VideoQuality(height: 2160, fps: 30) + /// Secondes sans bouton avant la veille de l'écran ; 0 = jamais. + var sleepAfter = 120 + + static let key = "cameraSettings" + static func load() -> CameraSettings { + guard let data = UserDefaults.standard.data(forKey: key), + let value = try? JSONDecoder().decode(CameraSettings.self, from: data) else { return CameraSettings() } + return value + } + func save() { + if let data = try? JSONEncoder().encode(self) { UserDefaults.standard.set(data, forKey: Self.key) } + } +} + +/// Ce que l'iPhone présent sait faire (rempli par la caméra au démarrage). +struct CameraCapabilities: Equatable, Sendable { + var zoomLabels: [String] = [] + var proRAW = false + var qualities: [VideoQuality] = [] + var stabilizations: [Stabilization] = [.off] + var minBias = -2.0 + var maxBias = 2.0 +} + +enum CameraSetting: Sendable, CaseIterable { + case photoFormat, exposure, stabilization, videoQuality, sleep + + var title: String { + switch self { + case .photoFormat: "Format photo" + case .exposure: "Exposition" + case .stabilization: "Stabilisation vidéo" + case .videoQuality: "Qualité vidéo" + case .sleep: "Veille de l'écran" + } + } +} + +enum SettingValue: Equatable, Sendable { + case photoFormat(PhotoFormat), exposure(Double), stabilization(Stabilization), videoQuality(VideoQuality), sleep(Int) + + var label: String { + switch self { + case .photoFormat(.heif): "HEIF" + case .photoFormat(.rawHeif): "ProRAW + HEIF" + case .exposure(let v): v == 0 ? "0" : String(format: "%+.1f", v) + case .stabilization(.off): "Désactivée" + case .stabilization(.standard): "Standard" + case .stabilization(.cinematic): "Cinématique" + case .stabilization(.extended): "Cinématique étendue" + case .videoQuality(let q): q.label + case .sleep(0): "Jamais" + case .sleep(let s): s < 60 ? "\(s) s" : "\(s / 60) min" + } + } +} + +extension CameraSettings { + static let biasSteps = [-2, -1.7, -1.3, -1, -0.7, -0.3, 0, 0.3, 0.7, 1, 1.3, 1.7, 2.0] + static let sleepSteps = [15, 30, 60, 120, 300, 0] + + func options(for setting: CameraSetting, _ caps: CameraCapabilities) -> [SettingValue] { + switch setting { + case .photoFormat: (caps.proRAW ? PhotoFormat.allCases : [.heif]).map { .photoFormat($0) } + case .exposure: Self.biasSteps.filter { $0 >= caps.minBias && $0 <= caps.maxBias }.map { .exposure($0) } + case .stabilization: caps.stabilizations.map { .stabilization($0) } + case .videoQuality: caps.qualities.map { .videoQuality($0) } + case .sleep: Self.sleepSteps.map { .sleep($0) } + } + } + + func current(_ setting: CameraSetting) -> SettingValue { + switch setting { + case .photoFormat: .photoFormat(photoFormat) + case .exposure: .exposure(exposureBias) + case .stabilization: .stabilization(stabilization) + case .videoQuality: .videoQuality(videoQuality) + case .sleep: .sleep(sleepAfter) + } + } + + mutating func set(_ value: SettingValue) { + switch value { + case .photoFormat(let v): photoFormat = v + case .exposure(let v): exposureBias = v + case .stabilization(let v): stabilization = v + case .videoQuality(let v): videoQuality = v + case .sleep(let v): sleepAfter = v + } + } +} + +/// Menu : droite ouvre et valide, haut et bas déplacent, gauche remonte d'un niveau ou ferme. +struct CameraMenu: Equatable, Sendable { + enum RootItem: Sendable, CaseIterable { + case photo, video, sleep, settings + + var title: String { + switch self { + case .photo: "Photo" + case .video: "Vidéo" + case .sleep: "Veille" + case .settings: "Réglages" + } + } + } + + enum Level: Equatable, Sendable { + case root(Int) + case settings(Int) + case options(CameraSetting, Int) + } + + enum Action: Equatable, Sendable { case none, close, setMode(CaptureMode), sleepNow, changed } + + private(set) var level: Level? = nil + var isOpen: Bool { level != nil } + + mutating func open() { level = .root(0) } + mutating func close() { level = nil } + + /// Applique un bouton ; modifie `settings` quand une option est validée. + mutating func handle(_ button: HousingButton, settings: inout CameraSettings, caps: CameraCapabilities) -> Action { + guard let level else { return .none } + let step = button == .down ? 1 : button == .up ? -1 : 0 + func wrap(_ i: Int, _ n: Int) -> Int { n == 0 ? 0 : (i + step + n) % n } + switch level { + case .root(let i): + switch button { + case .up, .down: self.level = .root(wrap(i, RootItem.allCases.count)) + case .left: self.level = nil; return .close + case .right, .shutter: + switch RootItem.allCases[i] { + case .photo: self.level = nil; return .setMode(.photo) + case .video: self.level = nil; return .setMode(.video) + case .sleep: self.level = nil; return .sleepNow + case .settings: self.level = .settings(0) + } + } + case .settings(let i): + switch button { + case .up, .down: self.level = .settings(wrap(i, CameraSetting.allCases.count)) + case .left: self.level = .root(RootItem.allCases.firstIndex(of: .settings)!) + case .right, .shutter: + let setting = CameraSetting.allCases[i] + let options = settings.options(for: setting, caps) + guard !options.isEmpty else { break } + self.level = .options(setting, options.firstIndex(of: settings.current(setting)) ?? 0) + } + case .options(let setting, let i): + let options = settings.options(for: setting, caps) + switch button { + case .up, .down: self.level = .options(setting, wrap(i, options.count)) + case .left: self.level = .settings(CameraSetting.allCases.firstIndex(of: setting)!) + case .right, .shutter: + if options.indices.contains(i) { settings.set(options[i]) } + self.level = .settings(CameraSetting.allCases.firstIndex(of: setting)!) + return .changed + } + } + return .none + } +} diff --git a/OpenMerou/Housing/HousingClient.swift b/OpenMerou/Housing/HousingClient.swift @@ -37,6 +37,10 @@ final class HousingClient: NSObject { private(set) var log: [LogLine] = [] private(set) var lastSensorUpdate: Date? private(set) var vacuum = VacuumSequence() + /// Boutons laissés à la caméra par la séquence de mise sous vide. + @ObservationIgnored var cameraButton: ((ButtonEvent) -> Void)? + + func bypassVacuum() { vacuum.bypass() } @ObservationIgnored private var central: CBCentralManager! @ObservationIgnored private var peripheral: CBPeripheral? @@ -240,7 +244,9 @@ extension HousingClient: CBPeripheralDelegate { let before = vacuum.step if let line = readings.apply(uuid, data) { note(line) } if uuid == HousingUUID.button, let event = ButtonEvent(data) { + let forCamera = vacuum.cameraHasButtons && !(event.button == .right && event.isLong) run(vacuum.button(event, now: .now)) + if forCamera { cameraButton?(event) } } if uuid == HousingUUID.internalPressure || uuid == HousingUUID.temperature { run(vacuum.sensors(pressurePa: readings.internalPressurePa, temperatureC: readings.temperatureC, now: .now)) diff --git a/OpenMerou/Housing/VacuumSequence.swift b/OpenMerou/Housing/VacuumSequence.swift @@ -27,6 +27,7 @@ struct VacuumSequence: Equatable, Sendable { case failed(Failure) case opening(fromPa: Double) // ouvrir le bouchon pour remettre à l'air case opened // à l'air : on peut ouvrir, puis éteindre + case bypassed // essai à sec, sans mise sous vide (choisi à l'écran tactile) } enum Effect: Equatable, Sendable { @@ -65,6 +66,19 @@ struct VacuumSequence: Equatable, Sendable { return max(0, Self.testSeconds - now.timeIntervalSince(baseline.date)) } + /// Vrai quand les boutons vont à la caméra (sauf l'appui long à droite, gardé pour l'ouverture). + var cameraHasButtons: Bool { + switch step { + case .testing, .sealed, .bypassed: true + default: false + } + } + + /// Essai à sec : seulement depuis le début de la séquence, pompe arrêtée. + mutating func bypass() { + if step == .prepare { step = .bypassed } + } + private func baseline(now: Date) -> Baseline? { guard let pressurePa else { return nil } return Baseline(date: now, pressurePa: pressurePa, temperatureK: temperatureC.map { $0 + 273.15 }) @@ -95,6 +109,8 @@ struct VacuumSequence: Equatable, Sendable { step = .prepare case (.testing, .right, true), (.sealed, .right, true), (.failed, .right, true): step = .opening(fromPa: pressurePa ?? 0) + case (.bypassed, .right, true): + step = .prepare case (.opening, .right, false): step = .opened // confirmation manuelle si la détection ne suffit pas case (.opening, .left, false): diff --git a/OpenMerou/Info.plist b/OpenMerou/Info.plist @@ -26,6 +26,12 @@ <true/> <key>NSBluetoothAlwaysUsageDescription</key> <string>Open Mérou se connecte en Bluetooth au boîtier de plongée pour lire ses boutons, sa pression et commander sa pompe à vide.</string> + <key>NSCameraUsageDescription</key> + <string>Open Mérou utilise l'appareil photo pour prendre des photos et des vidéos sous l'eau.</string> + <key>NSMicrophoneUsageDescription</key> + <string>Open Mérou utilise le micro pour le son des vidéos.</string> + <key>NSPhotoLibraryAddUsageDescription</key> + <string>Open Mérou enregistre vos photos et vidéos dans la photothèque.</string> <key>UIApplicationSceneManifest</key> <dict> <key>UIApplicationSupportsMultipleScenes</key> diff --git a/OpenMerou/UI/CameraScreen.swift b/OpenMerou/UI/CameraScreen.swift @@ -0,0 +1,196 @@ +import AVFoundation +import SwiftUI + +struct PreviewView: UIViewRepresentable { + let layer: AVCaptureVideoPreviewLayer + + final class Host: UIView { + var preview: AVCaptureVideoPreviewLayer? + override func layoutSubviews() { + super.layoutSubviews() + preview?.frame = bounds + } + } + + func makeUIView(context: Context) -> Host { + let view = Host() + view.backgroundColor = .black + view.preview = layer + view.layer.addSublayer(layer) + return view + } + + func updateUIView(_ view: Host, context: Context) {} +} + +/// Écran principal : l'image en plein écran, les informations autour, et par-dessus la séquence +/// de mise sous vide tant qu'elle garde les boutons. +struct CameraScreen: View { + let model: AppModel + @Environment(\.scenePhase) private var scenePhase + @State private var showDiagnostics = false + + private var housing: HousingClient { model.housing } + + var body: some View { + ZStack { + Color.black.ignoresSafeArea() + PreviewView(layer: model.engine.previewLayer).ignoresSafeArea() + + VStack { + topBar + Spacer() + if let message = model.camera.message, !model.menu.isOpen { + Text(message).font(.footnote).padding(8).background(.black.opacity(0.5), in: Capsule()) + } + bottomBar + } + .padding() + + if !model.camera.authorized { + card { Text("Autorisez l'appareil photo dans Réglages → Open Mérou.") } + } else if !housing.vacuum.cameraHasButtons { + card { + VacuumView(vacuum: housing.vacuum) + if housing.vacuum.step == .prepare { + Button("Essai à sec (sans mise sous vide)") { housing.bypassVacuum() } + .font(.footnote).padding(.top, 4) + } + Text(housing.status.label).font(.footnote).foregroundStyle(.secondary) + } + } else if model.menu.isOpen { + MenuView(model: model) + } + + if model.sleeping { + Color.black.ignoresSafeArea().onTapGesture { model.wake() } + } + } + .foregroundStyle(.white) + .preferredColorScheme(.dark) + .statusBarHidden() + .persistentSystemOverlays(.hidden) + .sheet(isPresented: $showDiagnostics) { HousingView(housing: housing) } + .onChange(of: scenePhase) { _, phase in + if phase != .active { + model.background() + if housing.pumpRequested { housing.stopPump(reason: "app en arrière-plan") } + } + } + } + + private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View { + VStack(alignment: .leading, spacing: 8) { content() } + .padding(20) + .frame(maxWidth: 460) + .background(.black.opacity(0.75), in: RoundedRectangle(cornerRadius: 20)) + .padding() + } + + private var topBar: some View { + HStack(spacing: 12) { + sealChip + if let p = housing.readings.internalPressurePa { Text(String(format: "%.0f hPa", p / 100)) } + if let t = housing.readings.temperatureC { Text(String(format: "%.0f °C", t)) } + if let b = housing.readings.batteryPercent { Label("\(b) %", systemImage: "battery.75percent") } + Spacer() + if let since = model.camera.recordingSince { + HStack(spacing: 6) { + Circle().fill(.red).frame(width: 12, height: 12) + Text(since, style: .timer) + } + .font(.headline) + } + Button { showDiagnostics = true } label: { Image(systemName: "info.circle") } + } + .font(.subheadline.weight(.semibold)) + .monospacedDigit() + .shadow(radius: 3) + } + + private var sealChip: some View { + let (text, color): (String, Color) = switch housing.vacuum.step { + case .sealed: ("Étanche", .green) + case .testing: ("Test en cours", .orange) + case .bypassed: ("À sec", .yellow) + case .failed: ("Alerte", .red) + default: ("Non vérifié", .gray) + } + return HStack(spacing: 6) { + Text(text) + if case .testing = housing.vacuum.step { + TimelineView(.periodic(from: .now, by: 1)) { context in + let left = Int((housing.vacuum.testRemaining(now: context.date) ?? 0).rounded(.up)) + Text(String(format: "%d:%02d", left / 60, left % 60)) + } + } + } + .padding(.horizontal, 10).padding(.vertical, 4) + .background(color.opacity(0.85), in: Capsule()) + .foregroundStyle(.black) + } + + private var bottomBar: some View { + HStack { + Text(model.settings.mode == .photo ? "PHOTO" : "VIDÉO") + if model.settings.mode == .video { Text(model.settings.videoQuality.label) } + if model.settings.mode == .photo, model.settings.photoFormat == .rawHeif { Text("RAW") } + if model.settings.exposureBias != 0 { Text(String(format: "%+.1f EV", model.settings.exposureBias)) } + Spacer() + let labels = model.camera.capabilities.zoomLabels + ForEach(labels.indices, id: \.self) { i in + Text(labels[i]) + .padding(.horizontal, 8).padding(.vertical, 4) + .background(i == model.camera.zoomIndex ? Color.yellow : .black.opacity(0.4), in: Capsule()) + .foregroundStyle(i == model.camera.zoomIndex ? .black : .white) + } + } + .font(.subheadline.weight(.semibold)) + .shadow(radius: 3) + } +} + +struct MenuView: View { + let model: AppModel + + var body: some View { + let (title, rows, selected) = content + VStack(alignment: .leading, spacing: 4) { + Text(title).font(.headline).padding(.bottom, 6) + ForEach(rows.indices, id: \.self) { i in + HStack { + Text(rows[i].0) + Spacer() + if let value = rows[i].1 { Text(value).foregroundStyle(i == selected ? .black : .secondary) } + } + .padding(.horizontal, 12).padding(.vertical, 8) + .background(i == selected ? Color.yellow : .clear, in: RoundedRectangle(cornerRadius: 10)) + .foregroundStyle(i == selected ? .black : .white) + } + Text("Haut, bas : choisir · droite : valider · gauche : retour") + .font(.caption).foregroundStyle(.secondary).padding(.top, 6) + } + .padding(20) + .frame(maxWidth: 420) + .background(.black.opacity(0.8), in: RoundedRectangle(cornerRadius: 20)) + .padding() + } + + private var content: (String, [(String, String?)], Int) { + let settings = model.settings, caps = model.camera.capabilities + switch model.menu.level { + case nil: + return ("Menu", [], 0) + case .root(let i): + return ("Menu", CameraMenu.RootItem.allCases.map { item in + let mark: String? = (item == .photo && settings.mode == .photo) || (item == .video && settings.mode == .video) ? "●" : nil + return (item.title, mark) + }, i) + case .settings(let i): + return ("Réglages", CameraSetting.allCases.map { ($0.title, settings.current($0).label) }, i) + case .options(let setting, let i): + let current = settings.current(setting) + return (setting.title, settings.options(for: setting, caps).map { ($0.label, $0 == current ? "●" : nil) }, i) + } + } +} diff --git a/OpenMerou/UI/HousingView.swift b/OpenMerou/UI/HousingView.swift @@ -3,7 +3,6 @@ import SwiftUI /// Écran de diagnostic du prototype : tout ce que le boîtier envoie, en direct. struct HousingView: View { let housing: HousingClient - @Environment(\.scenePhase) private var scenePhase var body: some View { NavigationStack { @@ -70,9 +69,6 @@ struct HousingView: View { } } .navigationTitle("Open Mérou") - .onChange(of: scenePhase) { _, phase in - if phase != .active, housing.pumpRequested { housing.stopPump(reason: "app en arrière-plan") } - } } } diff --git a/OpenMerou/UI/VacuumView.swift b/OpenMerou/UI/VacuumView.swift @@ -59,6 +59,7 @@ struct VacuumView: View { case .failed(.connectionLost): "Boîtier déconnecté" case .opening: "Ouvrez le bouchon" case .opened: "Boîtier à l'air" + case .bypassed: "Essai à sec" } } @@ -68,7 +69,7 @@ struct VacuumView: View { if let p = vacuum.pressurePa, p < VacuumSequence.alreadyUnderVacuumPa { "Le boîtier est déjà sous vide : le test d'étanchéité va démarrer directement." } else { - "iPhone en place, boîtier fermé, verrou verrouillé." + "iPhone en place (mode avion conseillé, Bluetooth allumé), boîtier fermé, verrou verrouillé." } case .openPlug: "Le bouchon doit être ouvert avant de démarrer la pompe." case .pumping: "La pompe s'arrête toute seule sous 800 hPa." @@ -80,6 +81,7 @@ struct VacuumView: View { case .failed(.connectionLost): "Sans le boîtier, l'étanchéité n'est plus surveillée." case .opening: "La pression va revenir à la normale." case .opened: "Vous pouvez ouvrir le boîtier." + case .bypassed: "Pas de mise sous vide : ne mettez pas le boîtier à l'eau." } } @@ -92,6 +94,7 @@ struct VacuumView: View { case .testing, .sealed: "Appui long à droite : ouvrir le boîtier" case .failed: "Bouton droit : recommencer · appui long à droite : ouvrir le boîtier" case .opening: "Bouton droit : c'est fait · gauche : annuler" + case .bypassed: "Appui long à droite : revenir à la mise sous vide" case .opened: "Bouton droit : se déconnecter, puis maintenez-le 2 s pour éteindre le boîtier" } } diff --git a/OpenMerouTests/CameraMenuTests.swift b/OpenMerouTests/CameraMenuTests.swift @@ -0,0 +1,49 @@ +import Testing +@testable import OpenMerou + +struct CameraMenuTests { + let caps = CameraCapabilities(zoomLabels: ["0,5", "1"], proRAW: true, + qualities: [VideoQuality(height: 1080, fps: 30), VideoQuality(height: 2160, fps: 60)], + stabilizations: [.off, .standard, .cinematic], minBias: -2, maxBias: 2) + + @Test func chooseVideoMode() { + var menu = CameraMenu(), settings = CameraSettings() + menu.open() + #expect(menu.handle(.down, settings: &settings, caps: caps) == .none) + #expect(menu.handle(.right, settings: &settings, caps: caps) == .setMode(.video)) + #expect(!menu.isOpen) + } + + @Test func changeVideoQualityThenBackOut() { + var menu = CameraMenu(), settings = CameraSettings() + settings.videoQuality = VideoQuality(height: 1080, fps: 30) + menu.open() + _ = menu.handle(.up, settings: &settings, caps: caps) // boucle vers Réglages + _ = menu.handle(.right, settings: &settings, caps: caps) + for _ in 0..<3 { _ = menu.handle(.down, settings: &settings, caps: caps) } // Qualité vidéo + _ = menu.handle(.right, settings: &settings, caps: caps) + #expect(menu.level == .options(.videoQuality, 0)) + _ = menu.handle(.down, settings: &settings, caps: caps) + #expect(menu.handle(.right, settings: &settings, caps: caps) == .changed) + #expect(settings.videoQuality == VideoQuality(height: 2160, fps: 60)) + _ = menu.handle(.left, settings: &settings, caps: caps) + #expect(menu.handle(.left, settings: &settings, caps: caps) == .close) + } + + @Test func leftCancelsAnOption() { + var menu = CameraMenu(), settings = CameraSettings() + menu.open() + _ = menu.handle(.up, settings: &settings, caps: caps) + _ = menu.handle(.right, settings: &settings, caps: caps) + _ = menu.handle(.right, settings: &settings, caps: caps) // Format photo + _ = menu.handle(.down, settings: &settings, caps: caps) + _ = menu.handle(.left, settings: &settings, caps: caps) + #expect(settings.photoFormat == .heif) + } + + @Test func rawOnlyWhenSupported() { + var noRaw = caps + noRaw.proRAW = false + #expect(CameraSettings().options(for: .photoFormat, noRaw) == [.photoFormat(.heif)]) + } +} diff --git a/README.md b/README.md @@ -9,8 +9,9 @@ Ce projet n'est ni affilié à Huish Outdoors ni approuvé par eux ; « Oceanic ## État -Prototype 0.2 : connexion automatique au boîtier (« HUISH »), boutons, batterie, pressions, température, -état de la pompe, journal ; commande de la pompe (arrêt automatique sous 80 kPa ou après 15 s) et déconnexion. +Version 0.4 : connexion automatique au boîtier (« HUISH ») ; mise sous vide guidée par les boutons, test +d'étanchéité corrigé par la température, surveillance continue ; caméra pilotée par les boutons (photo pleine +résolution, ProRAW, vidéo jusqu'à ce que l'iPhone sait faire, objectifs, exposition, stabilisation, veille). ## Développement diff --git a/fastlane/Fastfile b/fastlane/Fastfile @@ -122,9 +122,9 @@ platform :ios do end texts = { "fr-CA" => ["App libre et gratuite pour boîtier de plongée compatible : boutons, pompe à vide, capteurs, caméra.", - "0.3 : mise sous vide guidée par les boutons du boîtier (bouchon ouvert, pompe, bouchon fermé), test d'étanchéité de 3 minutes corrigé par la température, surveillance continue, ouverture par appui long à droite. À essayer : la séquence complète, puis une fuite provoquée (bouchon mal fermé)."], + "0.4 : caméra. Déclencheur = photo ou vidéo, haut et bas = objectif, droite = menu (Photo, Vidéo, Veille, Réglages), gauche = retour. Réglages : format (ProRAW), exposition, stabilisation, qualité vidéo, veille. Bouton « Essai à sec » à l'écran pour essayer sans mise sous vide. À vérifier : les objectifs proposés, la résolution des photos, chaque qualité vidéo, la veille."], "en-CA" => ["Free, open-source app for compatible dive housings: buttons, vacuum pump, sensors, camera.", - "0.3: guided vacuum sequence with the housing buttons (open plug, pump, close plug), 3-minute temperature-compensated leak test, continuous monitoring, opening with a long right press. Please try the full sequence, then a deliberate leak (plug not closed)."], + "0.4: camera. Shutter = photo or video, up and down = lens, right = menu (Photo, Video, Sleep, Settings), left = back. Settings: format (ProRAW), exposure, stabilization, video quality, sleep. On-screen Dry run button to try without the vacuum sequence. Please check the lenses offered, photo resolution, each video quality, and sleep."], } _, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations") texts.each do |locale, (description, _)| diff --git a/project.yml b/project.yml @@ -9,7 +9,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: