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 aeefed1c1a7cdd0125fc8c06a7ab9bd1ba632eee
parent 8572071f277d42be27c7c347025636b692c58194
Author: Jean Schurger <jean@schurger.org>
Date:   Fri, 13 Nov 2026 13:34:45 -0500

Read-only 0.1 prototype: Bluetooth client, diagnostic screen, protocol tests

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

Diffstat:
M.gitignore | 2++
AMakefile | 18++++++++++++++++++
AOpenMerou/App/OpenMerouApp.swift | 12++++++++++++
AOpenMerou/Housing/HousingClient.swift | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenMerou/Housing/HousingProtocol.swift | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenMerou/Info.plist | 45+++++++++++++++++++++++++++++++++++++++++++++
AOpenMerou/UI/HousingView.swift | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenMerouTests/HousingProtocolTests.swift | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AREADME.md | 24++++++++++++++++++++++++
Aproject.yml | 48++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 588 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -1 +1,3 @@ captures/ +*.xcodeproj +build/ diff --git a/Makefile b/Makefile @@ -0,0 +1,18 @@ +# Le code vit ici (hotrats) ; Xcode tourne sur chunga. +CHUNGA ?= chunga +REMOTE ?= src/perso/open-merou +DEST ?= platform=iOS Simulator,name=OpenMerou test iPhone + +.PHONY: sync project build test + +sync: + rsync -a --delete --exclude .git --exclude captures --exclude '*.xcodeproj' --exclude build ./ $(CHUNGA):$(REMOTE)/ + +project: sync + ssh $(CHUNGA) 'cd $(REMOTE) && xcodegen -q' + +build: project + ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme OpenMerou -destination "$(DEST)" build' + +test: project + ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme OpenMerou -destination "$(DEST)" test' diff --git a/OpenMerou/App/OpenMerouApp.swift b/OpenMerou/App/OpenMerouApp.swift @@ -0,0 +1,12 @@ +import SwiftUI + +@main +struct OpenMerouApp: App { + @State private var housing = HousingClient() + + var body: some Scene { + WindowGroup { + HousingView(housing: housing) + } + } +} diff --git a/OpenMerou/Housing/HousingClient.swift b/OpenMerou/Housing/HousingClient.swift @@ -0,0 +1,165 @@ +// Connexion Bluetooth au boîtier, en LECTURE SEULE pour ce prototype : aucune écriture, +// à part l'abonnement aux notifications. La commande de la pompe viendra après. +@preconcurrency import CoreBluetooth +import Foundation +import Observation + +@MainActor +@Observable +final class HousingClient: NSObject { + enum Status: Equatable { + case bluetoothUnavailable(String) + case scanning + case connecting(String) + case connected(String) + case disconnected(String) + + var label: String { + switch self { + case .bluetoothUnavailable(let why): "Bluetooth indisponible : \(why)" + case .scanning: "Recherche du boîtier…" + case .connecting(let name): "Connexion à \(name)…" + case .connected(let name): "Connecté à \(name)" + case .disconnected(let why): "Déconnecté (\(why)), reconnexion…" + } + } + } + + struct LogLine: Identifiable { + let id = UUID() + let date: Date + let text: String + } + + private(set) var status: Status = .bluetoothUnavailable("démarrage") + private(set) var readings = HousingReadings() + private(set) var deviceInfo: [String: String] = [:] + private(set) var log: [LogLine] = [] + private(set) var lastSensorUpdate: Date? + + @ObservationIgnored private var central: CBCentralManager! + @ObservationIgnored private var peripheral: CBPeripheral? + + override init() { + super.init() + central = CBCentralManager(delegate: self, queue: .main) + } + + private func note(_ text: String) { + log.insert(LogLine(date: .now, text: text), at: 0) + if log.count > 200 { log.removeLast(log.count - 200) } + } + + private func startScan() { + // Déjà connecté au système (par exemple par une autre app) ? + if let known = central.retrieveConnectedPeripherals(withServices: [HousingUUID.housingService]).first { + connect(known) + return + } + status = .scanning + // Le boîtier n'annonce pas ses services : on filtre sur le nom. + central.scanForPeripherals(withServices: nil, options: nil) + } + + private func connect(_ target: CBPeripheral) { + central.stopScan() + peripheral = target + target.delegate = self + status = .connecting(target.name ?? HousingUUID.advertisedName) + central.connect(target) + } +} + +extension HousingClient: CBCentralManagerDelegate { + nonisolated func centralManagerDidUpdateState(_ central: CBCentralManager) { + MainActor.assumeIsolated { + switch central.state { + case .poweredOn: + note("Bluetooth prêt") + startScan() + case .poweredOff: status = .bluetoothUnavailable("éteint") + case .unauthorized: status = .bluetoothUnavailable("accès refusé dans Réglages") + case .unsupported: status = .bluetoothUnavailable("non pris en charge") + default: status = .bluetoothUnavailable("en attente") + } + } + } + + nonisolated func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, + advertisementData: [String: Any], rssi RSSI: NSNumber) { + let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? peripheral.name + guard name == HousingUUID.advertisedName else { return } + MainActor.assumeIsolated { + note("Boîtier trouvé (\(RSSI) dBm)") + connect(peripheral) + } + } + + nonisolated func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { + MainActor.assumeIsolated { + status = .connected(peripheral.name ?? HousingUUID.advertisedName) + note("Connecté") + peripheral.discoverServices(HousingUUID.services) + } + } + + nonisolated func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, + error: Error?) { + MainActor.assumeIsolated { + note("Échec de connexion : \(error?.localizedDescription ?? "?")") + startScan() + } + } + + nonisolated func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, + error: Error?) { + MainActor.assumeIsolated { + let why = error?.localizedDescription ?? "fin de connexion" + status = .disconnected(why) + note("Déconnecté : \(why)") + // Une demande de connexion en attente n'expire pas : le boîtier sera repris dès son retour. + central.connect(peripheral) + } + } +} + +extension HousingClient: CBPeripheralDelegate { + nonisolated func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { + MainActor.assumeIsolated { + for service in peripheral.services ?? [] where HousingUUID.services.contains(service.uuid) { + peripheral.discoverCharacteristics(nil, for: service) + } + } + } + + nonisolated func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, + error: Error?) { + MainActor.assumeIsolated { + for characteristic in service.characteristics ?? [] { + // Lecture seule : on ne fait que lire et s'abonner. + if characteristic.properties.contains(.notify) { + peripheral.setNotifyValue(true, for: characteristic) + } + if characteristic.properties.contains(.read) { + peripheral.readValue(for: characteristic) + } + } + } + } + + nonisolated func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, + error: Error?) { + guard let data = characteristic.value else { return } + let uuid = characteristic.uuid + MainActor.assumeIsolated { + if let label = HousingUUID.deviceInfoStrings[uuid] { + deviceInfo[label] = String(decoding: data, as: UTF8.self) + return + } + if let line = readings.apply(uuid, data) { note(line) } + if [HousingUUID.internalPressure, HousingUUID.externalPressure, HousingUUID.temperature].contains(uuid) { + lastSensorUpdate = .now + } + } + } +} diff --git a/OpenMerou/Housing/HousingProtocol.swift b/OpenMerou/Housing/HousingProtocol.swift @@ -0,0 +1,142 @@ +// Protocole BLE du boîtier de plongée Oceanic+ (nom annoncé « HUISH »), obtenu par rétro-ingénierie +// pour l'interopérabilité : voir docs/PROTOCOLE.md. Valeurs brutes, petit-boutistes, sans chiffrement. +@preconcurrency import CoreBluetooth +import Foundation + +enum HousingUUID { + /// Base commune des services propres : 0000XXXX-1212-EFDE-1523-785FEABCD123. + static func custom(_ short: String) -> CBUUID { + CBUUID(string: "0000\(short)-1212-EFDE-1523-785FEABCD123") + } + + // Service « LED and Button » de l'exemple Nordic. + nonisolated(unsafe) static let buttonService = custom("1523") + nonisolated(unsafe) static let button = custom("1524") + + // Service propre du boîtier. + nonisolated(unsafe) static let housingService = custom("1623") + nonisolated(unsafe) static let pump = custom("1624") // écriture : 01 marche, 00 arrêt + nonisolated(unsafe) static let externalPressure = custom("1625") // hypothèse : pression extérieure, dizaines de Pa + nonisolated(unsafe) static let temperature = custom("1626") // centièmes de °C + nonisolated(unsafe) static let internalPressure = custom("1627") // Pa + nonisolated(unsafe) static let alarm = custom("1628") // inconnu, 00 au repos + nonisolated(unsafe) static let pumpState = custom("1629") // 01 en marche, 02 arrêtée + + nonisolated(unsafe) static let batteryService = CBUUID(string: "180F") + nonisolated(unsafe) static let batteryLevel = CBUUID(string: "2A19") + + nonisolated(unsafe) static let deviceInfoService = CBUUID(string: "180A") + nonisolated(unsafe) static let deviceInfoStrings: [CBUUID: String] = [ + CBUUID(string: "2A29"): "Fabricant", + CBUUID(string: "2A24"): "Modèle", + CBUUID(string: "2A25"): "N° de série", + CBUUID(string: "2A27"): "Matériel", + CBUUID(string: "2A26"): "Micrologiciel", + CBUUID(string: "2A28"): "Logiciel", + ] + + /// Services lus par l'app. Le service de mise à jour (FE59, DFU) n'en fait volontairement pas partie. + nonisolated(unsafe) static let services = [buttonService, housingService, batteryService, deviceInfoService] + + /// Nom annoncé par le boîtier. + static let advertisedName = "HUISH" +} + +enum HousingButton: UInt8, Sendable, CaseIterable { + case left = 1, shutter = 2, right = 3, up = 4, down = 5 + + var label: String { + switch self { + case .left: "Gauche" + case .shutter: "Déclencheur" + case .right: "Droite" + case .up: "Haut" + case .down: "Bas" + } + } +} + +struct ButtonEvent: Equatable, Sendable { + let button: HousingButton + let isLong: Bool + + /// Un octet : quartet haut = bouton, quartet bas = 0 (court) ou 1 (long). + init?(_ data: Data) { + guard data.count == 1, let byte = data.first, + let button = HousingButton(rawValue: byte >> 4), byte & 0x0F <= 1 else { return nil } + self.button = button + self.isLong = byte & 0x0F == 1 + } +} + +enum PumpState: Equatable, Sendable { + case running, stopped, other(UInt8) + + init?(_ data: Data) { + guard let byte = data.first else { return nil } + switch byte { + case 1: self = .running + case 2: self = .stopped + default: self = .other(byte) + } + } +} + +enum LittleEndian { + static func uint32(_ data: Data) -> UInt32? { + guard data.count == 4 else { return nil } + return data.reversed().reduce(0) { $0 << 8 | UInt32($1) } + } + + static func int32(_ data: Data) -> Int32? { + uint32(data).map { Int32(bitPattern: $0) } + } +} + +/// Dernières valeurs connues du boîtier. +struct HousingReadings: Equatable, Sendable { + var internalPressurePa: Double? + var externalPressurePa: Double? + var temperatureC: Double? + var batteryPercent: Int? + var pumpState: PumpState? + var alarmRaw: UInt8? + var lastButton: ButtonEvent? + + /// Applique une valeur reçue ; renvoie un libellé pour le journal, ou nil si la caractéristique est inconnue. + @discardableResult + mutating func apply(_ uuid: CBUUID, _ data: Data) -> String? { + switch uuid { + case HousingUUID.button: + guard let event = ButtonEvent(data) else { return "bouton ? \(data.hex)" } + lastButton = event + return "bouton \(event.button.label)\(event.isLong ? " (long)" : "")" + case HousingUUID.internalPressure: + internalPressurePa = LittleEndian.uint32(data).map(Double.init) + return nil // trop fréquent pour le journal + case HousingUUID.externalPressure: + externalPressurePa = LittleEndian.uint32(data).map { Double($0) * 10 } + return nil + case HousingUUID.temperature: + temperatureC = LittleEndian.int32(data).map { Double($0) / 100 } + return nil + case HousingUUID.batteryLevel: + batteryPercent = data.first.map(Int.init) + return "batterie \(batteryPercent.map(String.init) ?? "?") %" + case HousingUUID.pumpState: + pumpState = PumpState(data) + return "état de la pompe \(data.hex)" + case HousingUUID.alarm: + alarmRaw = data.first + return "1628 (alarme ?) \(data.hex)" + case HousingUUID.pump: + return "pompe (lecture) \(data.hex)" + default: + return nil + } + } +} + +extension Data { + var hex: String { map { String(format: "%02X", $0) }.joined(separator: " ") } +} diff --git a/OpenMerou/Info.plist b/OpenMerou/Info.plist @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>$(DEVELOPMENT_LANGUAGE)</string> + <key>CFBundleDisplayName</key> + <string>Open Mérou</string> + <key>CFBundleExecutable</key> + <string>$(EXECUTABLE_NAME)</string> + <key>CFBundleIdentifier</key> + <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>$(PRODUCT_NAME)</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleShortVersionString</key> + <string>$(MARKETING_VERSION)</string> + <key>CFBundleVersion</key> + <string>$(CURRENT_PROJECT_VERSION)</string> + <key>LSRequiresIPhoneOS</key> + <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>UIApplicationSceneManifest</key> + <dict> + <key>UIApplicationSupportsMultipleScenes</key> + <false/> + </dict> + <key>UILaunchScreen</key> + <dict/> + <key>UIRequiredDeviceCapabilities</key> + <array> + <string>bluetooth-le</string> + </array> + <key>UISupportedInterfaceOrientations</key> + <array> + <string>UIInterfaceOrientationPortrait</string> + <string>UIInterfaceOrientationLandscapeLeft</string> + <string>UIInterfaceOrientationLandscapeRight</string> + </array> +</dict> +</plist> diff --git a/OpenMerou/UI/HousingView.swift b/OpenMerou/UI/HousingView.swift @@ -0,0 +1,70 @@ +import SwiftUI + +/// Écran de diagnostic du prototype : tout ce que le boîtier envoie, en direct. +struct HousingView: View { + let housing: HousingClient + + var body: some View { + NavigationStack { + List { + Section { + Text(housing.status.label) + if let event = housing.readings.lastButton { + HStack { + Text("Dernier bouton") + Spacer() + Text(event.button.label + (event.isLong ? " (long)" : "")) + .font(.title2.bold()) + } + } + } + + Section("Boîtier") { + row("Pression intérieure", housing.readings.internalPressurePa.map { hPa($0) }) + row("Pression extérieure (hypothèse)", housing.readings.externalPressurePa.map { hPa($0) }) + row("Température intérieure", housing.readings.temperatureC.map { String(format: "%.2f °C", $0) }) + row("Batterie", housing.readings.batteryPercent.map { "\($0) %" }) + row("Pompe", housing.readings.pumpState.map(pumpLabel)) + row("1628 (alarme ?)", housing.readings.alarmRaw.map { String(format: "%02X", $0) }) + } + + if !housing.deviceInfo.isEmpty { + Section("Appareil") { + ForEach(housing.deviceInfo.keys.sorted(), id: \.self) { key in + row(key, housing.deviceInfo[key]) + } + } + } + + Section("Journal") { + ForEach(housing.log) { line in + HStack(alignment: .firstTextBaseline) { + Text(line.date, format: .dateTime.hour().minute().second()) + .foregroundStyle(.secondary) + .monospacedDigit() + Text(line.text) + } + .font(.footnote) + } + } + } + .navigationTitle("Open Mérou") + } + } + + private func row(_ title: String, _ value: String?) -> some View { + LabeledContent(title, value: value ?? "—") + } + + private func hPa(_ pa: Double) -> String { + String(format: "%.1f hPa", pa / 100) + } + + private func pumpLabel(_ state: PumpState) -> String { + switch state { + case .running: "en marche" + case .stopped: "arrêtée" + case .other(let byte): String(format: "inconnu (%02X)", byte) + } + } +} diff --git a/OpenMerouTests/HousingProtocolTests.swift b/OpenMerouTests/HousingProtocolTests.swift @@ -0,0 +1,62 @@ +@preconcurrency import CoreBluetooth +import Foundation +import Testing +@testable import OpenMerou + +/// Valeurs tirées de la capture du 2026-11-13 et des lectures nRF Connect (docs/PROTOCOLE.md). +struct HousingProtocolTests { + @Test(arguments: [ + (UInt8(0x10), HousingButton.left, false), + (0x20, .shutter, false), + (0x30, .right, false), + (0x40, .up, false), + (0x50, .down, false), + (0x31, .right, true), + ]) + func buttons(byte: UInt8, button: HousingButton, isLong: Bool) throws { + let event = try #require(ButtonEvent(Data([byte]))) + #expect(event.button == button) + #expect(event.isLong == isLong) + } + + @Test func unknownButtonsAreRejected() { + #expect(ButtonEvent(Data([0x00])) == nil) + #expect(ButtonEvent(Data([0x60])) == nil) + #expect(ButtonEvent(Data([0x32])) == nil) + #expect(ButtonEvent(Data()) == nil) + } + + @Test func sensors() { + var readings = HousingReadings() + readings.apply(HousingUUID.internalPressure, Data([0x1D, 0x86, 0x01, 0x00])) + readings.apply(HousingUUID.temperature, Data([0x3C, 0x09, 0x00, 0x00])) + readings.apply(HousingUUID.externalPressure, Data([0xD4, 0x26, 0x00, 0x00])) + readings.apply(HousingUUID.batteryLevel, Data([0x5C])) + #expect(readings.internalPressurePa == 99_869) + #expect(readings.temperatureC == 23.64) + #expect(readings.externalPressurePa == 99_400) + #expect(readings.batteryPercent == 92) + } + + @Test func vacuumDuringPumping() { + var readings = HousingReadings() + readings.apply(HousingUUID.internalPressure, Data([0xD6, 0x36, 0x01, 0x00])) + #expect(readings.internalPressurePa == 79_574) + } + + @Test func pumpState() { + #expect(PumpState(Data([0x01])) == .running) + #expect(PumpState(Data([0x02])) == .stopped) + #expect(PumpState(Data([0x07])) == .other(7)) + } + + @Test func negativeTemperature() { + var readings = HousingReadings() + readings.apply(HousingUUID.temperature, Data([0x38, 0xFF, 0xFF, 0xFF])) // -2,00 °C + #expect(readings.temperatureC == -2) + } + + @Test func dfuIsNeverDiscovered() { + #expect(!HousingUUID.services.contains(CBUUID(string: "FE59"))) + } +} diff --git a/README.md b/README.md @@ -0,0 +1,24 @@ +# Open Mérou + +App iOS libre et gratuite pour le boîtier de plongée Oceanic+ : boutons, pompe à vide, capteurs, +et bientôt la caméra avec correction des couleurs, sans abonnement. + +Le protocole Bluetooth du boîtier a été obtenu par rétro-ingénierie, pour l'interopérabilité, +à partir des échanges entre le boîtier et l'app officielle : voir [docs/PROTOCOLE.md](docs/PROTOCOLE.md). +Ce projet n'est ni affilié à Huish Outdoors ni approuvé par eux ; « Oceanic » est leur marque. + +## État + +Prototype 0.1, **lecture seule** : connexion automatique au boîtier (« HUISH »), boutons, batterie, +pressions, température, état de la pompe, journal. Aucune écriture vers le boîtier. + +## Développement + +Projet XcodeGen (`project.yml`), Swift 6, iOS 17. Le code vit sur hotrats, Xcode sur chunga : + +```bash +make build # rsync vers chunga, xcodegen, compilation +make test # tests unitaires du protocole (simulateur « OpenMerou test iPhone ») +``` + +Outils : `tools/pklg.py` décode un journal Bluetooth iOS (PacketLogger, sysdiagnose). diff --git a/project.yml b/project.yml @@ -0,0 +1,48 @@ +# Projet Xcode généré par XcodeGen (`xcodegen` sur chunga) : modifier ce fichier, pas le .xcodeproj. +name: OpenMerou +options: + bundleIdPrefix: org.schurger + developmentLanguage: fr + deploymentTarget: + iOS: "17.0" +settings: + base: + DEVELOPMENT_TEAM: CM5RQKJH56 + CODE_SIGN_STYLE: Automatic + MARKETING_VERSION: "0.1" + CURRENT_PROJECT_VERSION: "1" + SWIFT_VERSION: "6.0" +targets: + OpenMerou: + type: application + platform: iOS + sources: + - path: OpenMerou + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: org.schurger.openmerou + PRODUCT_NAME: OpenMerou + INFOPLIST_FILE: OpenMerou/Info.plist + TARGETED_DEVICE_FAMILY: "1" + SUPPORTS_MACCATALYST: NO + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD: NO + OpenMerouTests: + type: bundle.unit-test + platform: iOS + sources: + - path: OpenMerouTests + dependencies: + - target: OpenMerou + settings: + base: + GENERATE_INFOPLIST_FILE: YES + BUNDLE_LOADER: $(TEST_HOST) + TEST_HOST: $(BUILT_PRODUCTS_DIR)/OpenMerou.app/OpenMerou +schemes: + OpenMerou: + build: + targets: + OpenMerou: all + test: + targets: + - OpenMerouTests