commit b87d3090f039efb42a878d5106292e7f51f61797
parent 2829cd64c9c39a74df0515d67d22ca36b40202cd
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 10:00:04 -0500
RemoraKit: shared dive logic, RemoraUI library, GPL-2.0
The RemoraDeco package of Open Rémora becomes its own repository, as the
Swift package RemoraKit with two libraries.
RemoraDeco gains the platform-independent dive logic that lived in the
watch app: DiveTracker (start on submersion, depth held and flagged when
the reading is missing or the source goes silent, feedback cues with
their repeat periods, end after a minute at the surface, demo dives) and
DiveMonitor, its observable wrapper for an app (watchdog, demo dives,
saving through a DiveLogStore). A depth source feeds it DiveReading
values. A real dive can now start after a demo dive has ended: before,
the sensor stayed ignored until the app was relaunched.
RemoraUI holds what apps share visually: Format, labels and colours of
the warnings and settings, alarm styling (AlarmFlash, blinking,
DepthUnknownBanner), dive read-outs (DiveInstruction, AscentScale), the
settings screens and the terms view, with its own String Catalog
(English source, French translation).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYJwSV8KMFfnh7K4gJq
Diffstat:
17 files changed, 2148 insertions(+), 3 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,3 @@
+.build/
+.swiftpm/
+*.xcodeproj
diff --git a/LICENSE b/LICENSE
@@ -0,0 +1,338 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Moe Ghoul>, 1 April 1989
+ Moe Ghoul, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/Makefile b/Makefile
@@ -0,0 +1,12 @@
+# The sources are edited here (a Linux host); Swift runs on a Mac reachable over SSH.
+# CHUNGA is the SSH host, REMOTE the directory on the Mac (relative to the home directory).
+CHUNGA ?= chunga
+REMOTE ?= src/perso/remora-kit
+
+.PHONY: sync test
+
+sync:
+ rsync -a --delete --exclude .git --exclude .build --exclude .swiftpm ./ $(CHUNGA):$(REMOTE)/
+
+test: sync
+ ssh $(CHUNGA) 'cd $(REMOTE) && swift test 2>&1'
diff --git a/Package.swift b/Package.swift
@@ -1,13 +1,21 @@
-// SPDX-License-Identifier: GPL-2.0-only
// swift-tools-version: 6.0
+// SPDX-License-Identifier: GPL-2.0-only
import PackageDescription
let package = Package(
- name: "RemoraDeco",
+ name: "RemoraKit",
+ defaultLocalization: "en",
platforms: [.watchOS(.v10), .iOS(.v17), .macOS(.v14)],
- products: [.library(name: "RemoraDeco", targets: ["RemoraDeco"])],
+ products: [
+ // Decompression engine, logbook model and the platform-independent dive logic. No user interface.
+ .library(name: "RemoraDeco", targets: ["RemoraDeco"]),
+ // What the apps share visually: formatting, wording, alarm styling, settings screens, dive read-outs.
+ .library(name: "RemoraUI", targets: ["RemoraUI"]),
+ ],
targets: [
.target(name: "RemoraDeco"),
+ .target(name: "RemoraUI", dependencies: ["RemoraDeco"], resources: [.process("Resources")]),
.testTarget(name: "RemoraDecoTests", dependencies: ["RemoraDeco"]),
+ .testTarget(name: "RemoraUITests", dependencies: ["RemoraUI"]),
]
)
diff --git a/README.md b/README.md
@@ -0,0 +1,82 @@
+# RemoraKit
+
+The dive computer shared by Open Rémora (Apple Watch Ultra) and other apps: decompression
+engine, dive logic and the common parts of the interface, as one Swift package with two libraries.
+
+**This is not a certified dive computer.** Apps built on it are secondary instruments: always dive with a
+primary dive computer and follow it when the two disagree.
+
+## RemoraDeco
+
+No user interface, no platform framework (Foundation and Observation only); runs on iOS, watchOS and macOS.
+
+- **Engine**: Bühlmann ZHL-16C with gradient factors (`TissueState`, `AscentPlanner`), `DiveComputer` (no-stop
+ time, stops, ceiling, safety stop, ascent rate, warnings), air or nitrox up to EAN40.
+- **Logbook**: `DiveRecorder`, `DiveLog`, `Logbook` (tissues carried over to repetitive dives), `SurfaceAdvice`
+ (no-fly and altitude waiting times), `UserSettings`, UDDF export, Subsurface import.
+- **Dive logic**: `DiveTracker` and `DiveMonitor`, described below.
+
+### Plugging in a depth source
+
+The app owns the sensor. It turns what the sensor says into `DiveReading` values and hands them to a
+`DiveMonitor`:
+
+```swift
+let monitor = DiveMonitor(store: store) { cue in
+ // DiveCue: .depthLost, .safetyStopStarted, .safetyStopDone, .alarm, .warning, .diveSaved
+ // → a vibration, a sound, a flash…
+}
+monitor.onDiveStarted = { simulation in /* keep the app awake, start a workout… */ }
+monitor.onDiveEnded = { saved, simulation in /* saved == nil: the diver never went down */ }
+
+// For every sample of the sensor:
+monitor.receive(.pressure(time: seconds, surface: surfaceBar, absolute: ambientBar, submerged: true))
+monitor.receive(.temperature(celsius))
+```
+
+- `store` is a `DiveLogStore`: the diver's `UserSettings`, the `Logbook`, and `add(_:)` to save a dive.
+- `absolute` is the ambient pressure in bar and `surface` the pressure measured at the surface before the dive.
+ Pass `absolute: nil` when the sensor has no measurement: with `submerged: true` the last known depth is held
+ and `depthUnknown` is raised (an alarm); with `submerged: false` the diver is at the surface.
+- The dive starts by itself when `absolute` exceeds `surface` by 0.03 bar, and ends after a minute at the
+ surface (or with `end()`). A source that goes completely silent for more than 5 s is handled by a watchdog:
+ near the surface the dive ends, deeper the depth is held and flagged. These thresholds are in
+ `DiveTracker.Tuning` (`monitor.tuning`).
+- The monitor is `@Observable` and `@MainActor`: views read `status` (`DiveComputer.Status`), `warnings`,
+ `isAlarming`, `activeWarnings`, `depthUnknown`, `temperature`, `sourceMessage`, `finishedDive`.
+- `startSimulation(_:speed:)` runs a dry demo dive from a `DemoProfile`.
+
+`DiveTracker` is the same logic as a plain value type, with no clock and no timer: every call takes the
+wall-clock time and returns the events (`diveStarted`, `cue`, `diveEnded`). The tests script dives with it.
+
+## RemoraUI
+
+SwiftUI, for watchOS and iOS. Its texts are in its own String Catalog
+(`Sources/RemoraUI/Resources/Localizable.xcstrings`): English is the source language, French is translated.
+
+- `Format`: depths, durations, percentages, dates.
+- Labels and colours: `DiveComputer.Warning.label` / `.color`, `Water.label`, `UserSettings.Conservatism.label`,
+ `SettingsText` (every setting value as text).
+- Alarm styling: `AlarmFlash` (the whole screen flashes red), `.blinking(_:)` (a value blinks),
+ `DepthUnknownBanner`.
+- Dive read-outs: `DiveInstruction` (warning, stop with its countdown, safety stop or NDL) and `AscentScale`,
+ with a `scale` factor for screens larger than a watch.
+- Settings: `DiveSettingsView` (oxygen, water, NDL alarm) and `AdvancedDiveSettingsView` (conservatism, custom
+ gradient factors, maximum ppO2) on a binding to `UserSettings`; `SettingsSummary` for read-only rows.
+- `Terms`, `TermsView` and `.requiresTerms(_:)`: the warning to accept at first launch.
+
+## Tests
+
+ swift test
+
+runs on macOS (Swift 6). Two tests only run when given data:
+
+- `SHEARWATER_JSON=/path/to/dives.json swift test`: replays real dives and compares with what a Shearwater
+ displayed (see `docs/VALIDATION.md` in Open Rémora).
+- `SAMPLE_DIVE_DIR=/some/dir swift test`: writes a sample dive in the format shared with Sub Rascasse.
+
+`make test` does the same from a Linux host by syncing the sources to a Mac over SSH (`CHUNGA`, `REMOTE`).
+
+## License
+
+GPL-2.0-only. See [LICENSE](LICENSE).
diff --git a/Sources/RemoraDeco/DemoProfile.swift b/Sources/RemoraDeco/DemoProfile.swift
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+/// Simulated profiles: dry demo and screenshots.
+public struct DemoProfile: Sendable {
+ /// Segments: target depth (m), rate to get there (m/min), then time spent there (s).
+ public var segments: [(depth: Double, rate: Double, hold: Double)]
+
+ public init(segments: [(depth: Double, rate: Double, hold: Double)]) { self.segments = segments }
+
+ public static let shallow = DemoProfile(segments: [(8, 15, 600), (5, 6, 180), (0, 8, 0)])
+ public static let reef = DemoProfile(segments: [(22, 18, 720), (12, 16, 300), (5, 8, 180), (0, 8, 0)])
+ public static let deep = DemoProfile(segments: [(38, 20, 780), (15, 9, 120), (6, 9, 300), (0, 9, 0)])
+
+ /// Depth at every second, including the return to the surface.
+ public var depths: [Double] {
+ var out: [Double] = [0]
+ var d = 0.0
+ for s in segments {
+ while abs(d - s.depth) > 1e-9 {
+ let step = s.rate / 60
+ d = d < s.depth ? min(s.depth, d + step) : max(s.depth, d - step)
+ out.append(d)
+ }
+ out.append(contentsOf: Array(repeating: d, count: Int(s.hold)))
+ }
+ return out
+ }
+
+ public static func temperature(atDepth depth: Double) -> Double { 21 - min(depth, 30) * 0.4 }
+
+ /// Records the whole profile at once (demo logbook).
+ public func record(start: Date, settings: UserSettings, logbook: Logbook) -> DiveLog {
+ let configuration = (try? settings.configuration()) ?? DiveComputer.Configuration()
+ var recorder = DiveRecorder(configuration: configuration, surfacePressure: standardSurfacePressure,
+ start: start, logbook: logbook)
+ let scale = recorder.computer.scale
+ for (t, d) in depths.enumerated() {
+ recorder.record(time: Double(t), pressure: scale.pressure(atDepth: d),
+ temperature: Self.temperature(atDepth: d))
+ }
+ return recorder.finish()
+ }
+}
diff --git a/Sources/RemoraDeco/DiveMonitor.swift b/Sources/RemoraDeco/DiveMonitor.swift
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+import Observation
+
+/// Where the dive logic reads the diver's settings and logbook, and saves a finished dive.
+@MainActor
+public protocol DiveLogStore: AnyObject {
+ var settings: UserSettings { get }
+ var logbook: Logbook { get }
+ /// Adds the dive to the logbook and returns it as saved (with its number).
+ func add(_ dive: DiveLog) -> DiveLog
+}
+
+/// The dive in progress for an app: an observable wrapper around `DiveTracker` that runs the watchdog and the
+/// demo dives, saves finished dives in the store and passes the feedback cues on.
+///
+/// The app creates one, forwards the readings of its depth source to `receive`, and shows `status`,
+/// `warnings`, `depthUnknown`… What is specific to a platform (vibrations or sounds, keeping the app in the
+/// foreground, a workout session) stays in the app, driven by `feedback`, `onDiveStarted` and `onDiveEnded`.
+@MainActor @Observable
+public final class DiveMonitor {
+ public private(set) var tracker = DiveTracker()
+ /// Dive that just ended and was saved: the app opens its summary, then sets this back to nil.
+ public var finishedDive: DiveLog?
+ /// Site name given to demo dives.
+ public var simulationSite: String?
+ /// Called when a dive starts, before its first cue.
+ public var onDiveStarted: ((_ simulation: Bool) -> Void)?
+ /// Called when a dive ends; `saved` is nil when nothing was kept (the diver never went down).
+ public var onDiveEnded: ((_ saved: DiveLog?, _ simulation: Bool) -> Void)?
+
+ private let store: any DiveLogStore
+ private let feedback: (DiveCue) -> Void
+ private let now: () -> Date
+ @ObservationIgnored private var simulation: Task<Void, Never>?
+ @ObservationIgnored private var watchdog: Task<Void, Never>?
+
+ public init(store: any DiveLogStore, feedback: @escaping (DiveCue) -> Void,
+ now: @escaping () -> Date = { Date() }) {
+ self.store = store
+ self.feedback = feedback
+ self.now = now
+ }
+
+ public var isDiving: Bool { tracker.isDiving }
+ public var isSimulation: Bool { tracker.isSimulation }
+ public var status: DiveComputer.Status? { tracker.status }
+ public var temperature: Double? { tracker.temperature }
+ public var sourceMessage: String? { tracker.sourceMessage }
+ public var depthUnknown: Bool { tracker.depthUnknown }
+ public var warnings: Set<DiveComputer.Warning> { tracker.warnings }
+ public var isAlarming: Bool { tracker.isAlarming }
+ public var activeWarnings: Set<DiveComputer.Warning> { tracker.activeWarnings }
+ public var forcedAlarm: Bool {
+ get { tracker.forcedAlarm }
+ set { tracker.forcedAlarm = newValue }
+ }
+ public var tuning: DiveTracker.Tuning {
+ get { tracker.tuning }
+ set { tracker.tuning = newValue }
+ }
+
+ private var configuration: DiveComputer.Configuration {
+ (try? store.settings.configuration()) ?? DiveComputer.Configuration()
+ }
+
+ /// A reading from the depth source: the dive starts by itself on submersion.
+ public func receive(_ reading: DiveReading) {
+ let configuration = configuration, logbook = store.logbook
+ let events = tracker.handle(reading, now: now(), configuration: configuration, logbook: logbook)
+ apply(events)
+ }
+
+ /// Ends the dive and adds it to the logbook (nothing is kept when the diver never went down).
+ public func end() {
+ let events = tracker.end()
+ if events.isEmpty { stopTasks() }
+ apply(events)
+ }
+
+ /// Dry demo dive, accelerated `speed` times.
+ public func startSimulation(_ profile: DemoProfile = .reef, speed: Double = 30) {
+ guard !tracker.isDiving else { return }
+ let configuration = configuration, logbook = store.logbook
+ let events = tracker.startSimulation(now: now(), configuration: configuration, logbook: logbook)
+ apply(events)
+ let depths = profile.depths + Array(repeating: 0, count: 61)
+ simulation = Task { [weak self] in
+ for (t, d) in depths.enumerated() {
+ guard !Task.isCancelled, let self, self.tracker.isDiving else { return }
+ let events = self.tracker.simulate(time: Double(t), depth: d,
+ temperature: DemoProfile.temperature(atDepth: d), now: self.now())
+ self.apply(events)
+ try? await Task.sleep(for: .seconds(1 / speed))
+ }
+ }
+ }
+
+ private func apply(_ events: [DiveTracker.Event]) {
+ for event in events {
+ switch event {
+ case .diveStarted(let simulated):
+ if !simulated { startWatchdog() }
+ onDiveStarted?(simulated)
+ case .cue(let cue):
+ feedback(cue)
+ case .diveEnded(let dive, let simulated):
+ stopTasks()
+ guard var dive else {
+ onDiveEnded?(nil, simulated)
+ continue
+ }
+ if simulated { dive.site = simulationSite }
+ let saved = store.add(dive)
+ finishedDive = saved
+ feedback(.diveSaved)
+ onDiveEnded?(saved, simulated)
+ }
+ }
+ }
+
+ private func stopTasks() {
+ simulation?.cancel()
+ simulation = nil
+ watchdog?.cancel()
+ watchdog = nil
+ }
+
+ private func startWatchdog() {
+ watchdog?.cancel()
+ watchdog = Task { [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(2))
+ guard let self, self.tracker.isDiving, !self.tracker.isSimulation else { return }
+ let events = self.tracker.tick(now: self.now())
+ self.apply(events)
+ }
+ }
+ }
+}
diff --git a/Sources/RemoraDeco/DiveTracker.swift b/Sources/RemoraDeco/DiveTracker.swift
@@ -0,0 +1,259 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+/// What a depth source reports. The Apple Watch feeds these from its submersion sensor; another device
+/// (a housing with a pressure sensor, a simulator) feeds the same values from whatever it has.
+public enum DiveReading: Sendable, Hashable {
+ /// `time` in seconds on the clock of the source (only differences matter), pressures in bar.
+ /// `absolute` is the ambient pressure; nil when there is no measurement: out of the water, but also when
+ /// the sensor cannot measure underwater (beyond its limit, error, link lost). `submerged` tells them apart.
+ case pressure(time: Double, surface: Double, absolute: Double?, submerged: Bool)
+ /// Water temperature, °C.
+ case temperature(Double)
+ /// Text from the source to show on the dive screen (nil clears it).
+ case message(String?)
+}
+
+/// Feedback the dive logic asks for. The app turns each cue into a vibration, a sound or a flash.
+public enum DiveCue: Sendable, Hashable, CaseIterable {
+ /// Underwater and the depth reading was just lost.
+ case depthLost
+ case safetyStopStarted
+ case safetyStopDone
+ /// Alarm in progress (violation or depth unknown): repeated every `alarmRepeat` seconds while it lasts.
+ case alarm
+ /// Warning: once when it appears, repeated every `warningRepeat` seconds while it lasts.
+ case warning
+ /// A dive was just saved in the logbook.
+ case diveSaved
+}
+
+extension DiveComputer.Warning {
+ /// Violations are alarms (the whole screen flashes); the other warnings only blink the value concerned.
+ public var isViolation: Bool { [.ceilingViolated, .ascentTooFast, .ppO2Critical].contains(self) }
+ /// Most serious first.
+ public var rank: Int { isViolation ? 0 : 1 }
+}
+
+/// The dive in progress, independent of any platform: starts the dive on submersion, feeds the computer and
+/// the recorder, holds the depth when the reading is missing, decides when to give feedback, and ends the dive
+/// after a minute at the surface. A value type with no clock and no timer of its own: the caller passes the
+/// readings, the wall-clock time (`now`) and calls `tick` regularly; every call returns what happened.
+/// `DiveMonitor` wraps it for an app.
+public struct DiveTracker: Sendable {
+ public enum Event: Sendable, Hashable {
+ case diveStarted(simulation: Bool)
+ case cue(DiveCue)
+ /// The dive is over. No dive log when the diver never went below `underDepth`.
+ case diveEnded(DiveLog?, simulation: Bool)
+ }
+
+ public struct Tuning: Sendable, Hashable {
+ /// Pressure above the surface pressure that starts a dive (bar; 0.03 ≈ 30 cm of water).
+ public var startOverpressure = 0.03
+ /// The dive counts once the diver went below this depth (m)…
+ public var underDepth = 1.0
+ /// …and ends after `surfaceSeconds` above this depth (m).
+ public var surfaceDepth = 0.3
+ public var surfaceSeconds = 60.0
+ /// Silence of the source (s) after which `tick` moves time forward by itself.
+ public var silence = 5.0
+ /// Silent source: below this overpressure (bar; 0.15 ≈ 1.5 m) the diver is considered out of the water,
+ /// deeper the last known depth is held and flagged.
+ public var shallowOverpressure = 0.15
+ /// Repeat periods of the feedback (s, wall clock).
+ public var alarmRepeat = 2.0
+ public var warningRepeat = 15.0
+ public init() {}
+ }
+
+ public var tuning = Tuning()
+ /// Forces the alarm state (screenshots and feedback tests).
+ public var forcedAlarm = false
+
+ public private(set) var isDiving = false
+ public private(set) var isSimulation = false
+ public private(set) var status: DiveComputer.Status?
+ public private(set) var temperature: Double?
+ public private(set) var sourceMessage: String?
+ /// Underwater without a depth reading (sensor limit exceeded, error, silence): the computer assumes the
+ /// diver stays at the last known depth, and the app must say so in large type.
+ public private(set) var depthUnknown = false
+ public private(set) var warnings = Set<DiveComputer.Warning>()
+
+ private var recorder: DiveRecorder?
+ private var surfacedAt: Double?
+ private var wentUnder = false
+ private var safetyStop = DiveComputer.SafetyStop.notRequired
+ private var lastReadingAt: Date?
+ private var lastPressure: Double?
+ private var surfacePressure = standardSurfacePressure
+ private var lastWarningCue: [DiveComputer.Warning: Date] = [:]
+ private var lastAlarmCue: Date?
+
+ public init() {}
+
+ /// Alarm in progress: a violation, or depth unknown.
+ public var isAlarming: Bool { depthUnknown || warnings.contains(where: \.isViolation) || forcedAlarm }
+ /// Warnings in progress (violations excluded).
+ public var activeWarnings: Set<DiveComputer.Warning> { warnings.filter { !$0.isViolation } }
+ /// Depth ↔ pressure conversion of the dive in progress.
+ public var scale: DepthScale? { recorder?.computer.scale }
+
+ /// A reading from the depth source. `configuration` and `logbook` are only evaluated when this reading
+ /// starts a dive (the logbook provides the tissues of a recent dive).
+ public mutating func handle(_ reading: DiveReading, now: Date,
+ configuration: @autoclosure () -> DiveComputer.Configuration,
+ logbook: @autoclosure () -> Logbook?) -> [Event] {
+ switch reading {
+ case .message(let text):
+ sourceMessage = text
+ return []
+ case .temperature(let celsius):
+ temperature = celsius
+ return []
+ case .pressure(let time, let surface, let absolute, let submerged):
+ // A simulated dive in progress ignores the real sensor.
+ guard !(isDiving && isSimulation) else { return [] }
+ var events: [Event] = []
+ if !isDiving {
+ guard let absolute, absolute > surface + tuning.startOverpressure else { return [] }
+ events += start(surfacePressure: surface, simulation: false, now: now,
+ configuration: configuration(), logbook: logbook())
+ }
+ lastReadingAt = now
+ if let absolute {
+ depthUnknown = false
+ lastPressure = absolute
+ events += ingest(time: time, pressure: absolute, now: now)
+ } else if submerged, let held = lastPressure {
+ // Underwater without a reading: stay at the last known depth (tissues keep loading),
+ // never a false return to the surface.
+ events += signalDepthUnknown()
+ events += ingest(time: time, pressure: held, now: now)
+ } else {
+ depthUnknown = false
+ lastPressure = surface
+ events += ingest(time: time, pressure: surface, now: now)
+ }
+ return events
+ }
+ }
+
+ /// Watchdog, to be called every couple of seconds during a real dive: when the source has been silent for
+ /// more than `silence` seconds, time still moves forward. Near the surface the diver is considered out
+ /// (the dive ends after a minute); deeper, the last known depth is held and flagged.
+ public mutating func tick(now: Date) -> [Event] {
+ guard isDiving, !isSimulation,
+ let last = lastReadingAt, now.timeIntervalSince(last) > tuning.silence,
+ let held = lastPressure else { return [] }
+ let shallow = held < surfacePressure + tuning.shallowOverpressure
+ var events: [Event] = []
+ if !shallow { events += signalDepthUnknown() }
+ events += ingest(time: now.timeIntervalSinceReferenceDate,
+ pressure: shallow ? surfacePressure : held, now: now)
+ return events
+ }
+
+ /// Ends the dive now (it also ends by itself after a minute at the surface).
+ public mutating func end() -> [Event] {
+ depthUnknown = false
+ guard let r = recorder else { return [] }
+ recorder = nil
+ isDiving = false
+ guard wentUnder else { return [.diveEnded(nil, simulation: isSimulation)] }
+ var dive = r.finish()
+ if isSimulation { dive.source = .simulation }
+ return [.diveEnded(dive, simulation: isSimulation)]
+ }
+
+ /// Starts a simulated dive (dry demo); feed it with `simulate`.
+ public mutating func startSimulation(now: Date, configuration: DiveComputer.Configuration,
+ logbook: Logbook?) -> [Event] {
+ guard !isDiving else { return [] }
+ return start(surfacePressure: standardSurfacePressure, simulation: true, now: now,
+ configuration: configuration, logbook: logbook)
+ }
+
+ /// One step of a simulated dive: `time` in seconds since its start, `depth` in metres.
+ public mutating func simulate(time: Double, depth: Double, temperature: Double?, now: Date) -> [Event] {
+ guard isDiving, isSimulation, let scale else { return [] }
+ self.temperature = temperature
+ return ingest(time: time, pressure: scale.pressure(atDepth: depth), now: now)
+ }
+
+ private mutating func signalDepthUnknown() -> [Event] {
+ defer { depthUnknown = true }
+ return depthUnknown ? [] : [.cue(.depthLost)]
+ }
+
+ private mutating func start(surfacePressure: Double, simulation: Bool, now: Date,
+ configuration: DiveComputer.Configuration, logbook: Logbook?) -> [Event] {
+ recorder = DiveRecorder(configuration: configuration, surfacePressure: surfacePressure,
+ start: now, logbook: logbook)
+ isSimulation = simulation
+ isDiving = true
+ self.surfacePressure = surfacePressure
+ lastPressure = nil
+ lastReadingAt = now
+ depthUnknown = false
+ lastWarningCue = [:]
+ lastAlarmCue = nil
+ surfacedAt = nil
+ wentUnder = false
+ warnings = []
+ safetyStop = .notRequired
+ status = nil
+ return [.diveStarted(simulation: simulation)]
+ }
+
+ private mutating func ingest(time: Double, pressure: Double, now: Date) -> [Event] {
+ guard var r = recorder else { return [] }
+ let s = r.record(time: time, pressure: pressure, temperature: temperature)
+ recorder = r
+ status = s
+ var events: [Event] = []
+
+ // Safety stop: one cue at the start and at the end of the countdown.
+ switch (safetyStop, s.safetyStop) {
+ case (.pending, .running), (.notRequired, .running): events.append(.cue(.safetyStopStarted))
+ case (.running, .done): events.append(.cue(.safetyStopDone))
+ default: break
+ }
+ safetyStop = s.safetyStop
+
+ // Feedback (wall clock, not the dive clock).
+ // Alarm (violation, depth unknown): strong cue every `alarmRepeat` seconds for as long as it lasts.
+ // Warning: one cue when it appears, repeated every `warningRepeat` seconds for as long as it lasts.
+ warnings = s.warnings
+ if isAlarming {
+ if lastAlarmCue.map({ now.timeIntervalSince($0) >= tuning.alarmRepeat }) ?? true {
+ lastAlarmCue = now
+ events.append(.cue(.alarm))
+ }
+ } else {
+ lastAlarmCue = nil
+ let due = s.warnings.filter { w in
+ lastWarningCue[w].map { now.timeIntervalSince($0) >= tuning.warningRepeat } ?? true
+ }
+ if !due.isEmpty {
+ for w in due { lastWarningCue[w] = now }
+ events.append(.cue(.warning))
+ }
+ }
+ // A warning that went away and came back gives a cue again, but no more than once per period.
+ lastWarningCue = lastWarningCue.filter {
+ now.timeIntervalSince($0.value) < tuning.warningRepeat || s.warnings.contains($0.key)
+ }
+
+ // Automatic end: a minute at the surface after going below `underDepth`.
+ if s.depth > tuning.underDepth { wentUnder = true }
+ if s.depth < tuning.surfaceDepth {
+ if surfacedAt == nil { surfacedAt = time }
+ if wentUnder, let since = surfacedAt, time - since >= tuning.surfaceSeconds { events += end() }
+ } else {
+ surfacedAt = nil
+ }
+ return events
+ }
+}
diff --git a/Sources/RemoraUI/AlarmStyle.swift b/Sources/RemoraUI/AlarmStyle.swift
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import SwiftUI
+
+/// Alarm (violation, depth unknown): the whole screen flashes red. Put it behind the dive screen.
+public struct AlarmFlash: View {
+ public init() {}
+
+ public var body: some View {
+ TimelineView(.periodic(from: .now, by: 0.4)) { context in
+ let on = Int(context.date.timeIntervalSinceReferenceDate / 0.4) % 2 == 0
+ Color.red.opacity(on ? 0.85 : 0.15).ignoresSafeArea()
+ }
+ }
+}
+
+extension View {
+ /// Warning: the value concerned blinks (nothing moves when `active` is false).
+ @ViewBuilder public func blinking(_ active: Bool) -> some View {
+ if active {
+ TimelineView(.periodic(from: .now, by: 0.4)) { context in
+ let on = Int(context.date.timeIntervalSinceReferenceDate / 0.4) % 2 == 0
+ self.opacity(on ? 1 : 0.15)
+ }
+ } else {
+ self
+ }
+ }
+}
+
+/// Shown over the dive screen while the depth is unknown underwater.
+public struct DepthUnknownBanner: View {
+ var scale: CGFloat
+
+ public init(scale: CGFloat = 1) { self.scale = scale }
+
+ public var body: some View {
+ Text("DEPTH UNKNOWN\nFollow your primary computer", bundle: .module)
+ .font(.system(size: 13 * scale, weight: .heavy, design: .rounded))
+ .multilineTextAlignment(.center)
+ .padding(6 * scale)
+ .frame(maxWidth: .infinity)
+ .background(.red, in: RoundedRectangle(cornerRadius: 8 * scale))
+ }
+}
diff --git a/Sources/RemoraUI/DiveReadouts.swift b/Sources/RemoraUI/DiveReadouts.swift
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import SwiftUI
+import RemoraDeco
+
+/// What to do now: alarm or warning, stop (countdown), safety stop, or no-stop time (NDL).
+/// Sizes are those of the watch; `scale` enlarges everything for a bigger screen.
+public struct DiveInstruction: View {
+ let status: DiveComputer.Status
+ var scale: CGFloat
+
+ public init(status: DiveComputer.Status, scale: CGFloat = 1) {
+ self.status = status
+ self.scale = scale
+ }
+
+ private func rounded(_ size: CGFloat, _ weight: Font.Weight) -> Font {
+ .system(size: size * scale, weight: weight, design: .rounded)
+ }
+
+ /// Text styles follow the system on the watch; scaled, they become fixed sizes.
+ private func small(_ style: Font, _ size: CGFloat) -> Font {
+ scale == 1 ? style : .system(size: size * scale)
+ }
+
+ public var body: some View {
+ let s = status
+ VStack(spacing: 1 * scale) {
+ if let warning = s.warnings.sorted(by: { $0.rank < $1.rank }).first {
+ Text(warning.label.uppercased())
+ .font(rounded(14, .bold))
+ .foregroundStyle(warning.isViolation ? .white : warning.color)
+ .minimumScaleFactor(0.6)
+ .lineLimit(1)
+ .blinking([.ppO2High, .missedSafetyStop].contains(warning))
+ }
+ if let stop = s.plan.stops.first {
+ HStack(alignment: .firstTextBaseline, spacing: 4 * scale) {
+ Text("STOP \(Int(stop.depth)) m", bundle: .module)
+ .font(rounded(16, .bold))
+ Text(Format.clock(Double(stop.seconds ?? stop.minutes * 60)))
+ .font(rounded(22, .bold))
+ .monospacedDigit()
+ }
+ .foregroundStyle(.orange)
+ Text("surface in \(Int(s.plan.timeToSurface.rounded(.up))) min", bundle: .module)
+ .font(small(.caption2, 11)).foregroundStyle(.secondary)
+ } else if case .running(let remaining) = s.safetyStop {
+ Text("SAFETY STOP", bundle: .module).font(rounded(12, .bold)).foregroundStyle(.cyan)
+ Text(Format.clock(remaining))
+ .font(rounded(26, .bold))
+ .monospacedDigit()
+ .foregroundStyle(.cyan)
+ } else {
+ let low = s.warnings.contains(.lowNoDecompression)
+ HStack(alignment: .firstTextBaseline, spacing: 4 * scale) {
+ Text(verbatim: "NDL").font(rounded(15, .semibold)).foregroundStyle(.secondary)
+ Text(Format.ndl(s.plan.noDecompressionLimit))
+ .font(rounded(26, .bold))
+ .monospacedDigit()
+ .foregroundStyle(low ? .orange : .green)
+ .blinking(low)
+ Text(verbatim: "min").font(small(.caption, 12)).foregroundStyle(.secondary)
+ }
+ switch s.safetyStop {
+ case .pending where s.depth < 9:
+ Text("Safety stop 3 min at 5 m", bundle: .module).font(small(.caption2, 11)).foregroundStyle(.cyan)
+ case .done:
+ Text("Safety stop done ✓", bundle: .module).font(small(.caption2, 11)).foregroundStyle(.green)
+ default:
+ EmptyView()
+ }
+ }
+ }
+ }
+}
+
+/// Vertical ascent rate scale: 5 segments (3, 6, 9, 10, 12 m/min) that fill from the bottom;
+/// green, yellow above 10 m/min, red above 12.
+public struct AscentScale: View {
+ let rate: Double
+ var scale: CGFloat
+ public static let thresholds: [Double] = [3, 6, 9, 10, 12]
+
+ public init(rate: Double, scale: CGFloat = 1) {
+ self.rate = rate
+ self.scale = scale
+ }
+
+ public var body: some View {
+ VStack(spacing: 3 * scale) {
+ Image(systemName: "arrow.up").font(.system(size: 9 * scale, weight: .heavy)).foregroundStyle(.secondary)
+ ForEach(Self.thresholds.indices.reversed(), id: \.self) { i in
+ RoundedRectangle(cornerRadius: 2 * scale)
+ .fill(rate >= Self.thresholds[i] ? color : Color.gray.opacity(0.25))
+ .frame(width: 10 * scale, height: (i >= 3 ? 14 : 10) * scale)
+ }
+ }
+ .accessibilityLabel(Text("Ascent \(Int(max(0, rate))) metres per minute", bundle: .module))
+ }
+
+ private var color: Color { rate > 12 ? .red : rate > 10 ? .yellow : .green }
+}
diff --git a/Sources/RemoraUI/Format.swift b/Sources/RemoraUI/Format.swift
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+/// Numbers, durations and dates as the apps display them.
+public enum Format {
+ /// Language the interface runs in. The French interface keeps the decimal comma and the date style it
+ /// always had.
+ public static let isFrench = Bundle.module.preferredLocalizations.first?.hasPrefix("fr") ?? false
+ private static let locale: Locale = {
+ if isFrench { return Locale(identifier: "fr_CA") }
+ return Locale.current.language.languageCode == .english ? Locale.current : Locale(identifier: "en_US")
+ }()
+
+ /// Fixed number of decimals, with the decimal separator of the interface language.
+ public static func decimal(_ value: Double, digits: Int) -> String {
+ let s = String(format: "%.\(digits)f", value)
+ return isFrench ? s.replacingOccurrences(of: ".", with: ",") : s
+ }
+
+ /// Depth in metres, one decimal, without the unit.
+ public static func depth(_ metres: Double) -> String { decimal(metres, digits: 1) }
+
+ /// Seconds → "12:34" (or "1:02:03").
+ public static func clock(_ seconds: Double) -> String {
+ let s = Int(seconds.rounded())
+ return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s / 60 % 60, s % 60)
+ : String(format: "%d:%02d", s / 60, s % 60)
+ }
+
+ /// Seconds → "42 min".
+ public static func minutes(_ seconds: Double) -> String { "\(Int((seconds / 60).rounded())) min" }
+
+ /// Waiting time in hours → "3 h 05" (or "45 min").
+ public static func hours(_ h: Double) -> String {
+ let total = Int((h * 60).rounded(.up))
+ return total >= 60 ? "\(total / 60) h \(String(format: "%02d", total % 60))" : "\(total) min"
+ }
+
+ public static func percent(_ value: Int) -> String { String(localized: "\(value)%", bundle: .module) }
+
+ /// No-decompression limit in minutes, without the unit; nil = unlimited.
+ public static func ndl(_ minutes: Double?) -> String {
+ guard let minutes else { return ">99" }
+ return minutes > 99 ? ">99" : "\(Int(minutes))"
+ }
+
+ public static func day(_ date: Date) -> String {
+ date.formatted(.dateTime.day().month(.abbreviated).year().locale(locale))
+ }
+
+ public static func dayTime(_ date: Date) -> String {
+ date.formatted(.dateTime.day().month(.abbreviated).hour().minute().locale(locale))
+ }
+}
diff --git a/Sources/RemoraUI/Labels.swift b/Sources/RemoraUI/Labels.swift
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import SwiftUI
+import RemoraDeco
+
+extension DiveComputer.Warning {
+ public var label: String {
+ switch self {
+ case .ascentFast: String(localized: "Fast ascent", bundle: .module)
+ case .ascentTooFast: String(localized: "Ascent too fast", bundle: .module)
+ case .ceilingViolated: String(localized: "Ceiling broken", bundle: .module)
+ case .ppO2High: String(localized: "High ppO2", bundle: .module)
+ case .ppO2Critical: String(localized: "Critical ppO2", bundle: .module)
+ case .missedSafetyStop: String(localized: "Safety stop missed", bundle: .module)
+ case .depthLimit: String(localized: "Depth limit", bundle: .module)
+ case .lowNoDecompression: String(localized: "Low NDL", bundle: .module)
+ }
+ }
+
+ /// Alarms (violations) are red, warnings orange.
+ public var color: Color { isViolation ? .red : .orange }
+}
+
+extension Water {
+ public var label: String {
+ switch self {
+ case .fresh: String(localized: "Fresh", bundle: .module)
+ case .en13319: String(localized: "Standard (EN 13319)", bundle: .module)
+ case .salt: String(localized: "Salt", bundle: .module)
+ }
+ }
+}
+
+extension UserSettings.Conservatism {
+ public var label: String {
+ switch self {
+ case .high: String(localized: "High (GF 30/70)", bundle: .module)
+ case .medium: String(localized: "Medium (GF 40/80)", bundle: .module)
+ case .low: String(localized: "Low (GF 50/85)", bundle: .module)
+ case .custom: String(localized: "Custom", bundle: .module)
+ }
+ }
+}
+
+/// The values of the settings as text, for any presentation of them (pickers, a read-only summary, a
+/// button-driven menu).
+public enum SettingsText {
+ /// ppO2 values offered by the advanced settings.
+ public static let ppO2Choices = [1.2, 1.3, 1.4, 1.5, 1.6]
+
+ public static func oxygen(_ percent: Int) -> String {
+ percent == 21 ? String(localized: "\(percent)% (air)", bundle: .module) : Format.percent(percent)
+ }
+
+ public static func ndlAlarm(_ minutes: Int) -> String {
+ minutes == 0 ? String(localized: "Off", bundle: .module)
+ : String(localized: "Below \(minutes) min", bundle: .module)
+ }
+
+ public static func conservatism(_ settings: UserSettings) -> String {
+ settings.conservatism == .custom
+ ? String(localized: "Custom (\(settings.gradientFactors.description))", bundle: .module)
+ : settings.conservatism.label
+ }
+
+ public static func ppO2(_ bar: Double) -> String { "\(Format.decimal(bar, digits: 1)) bar" }
+
+ public static func maximumOperatingDepth(_ settings: UserSettings) -> String {
+ "\(Format.depth(settings.maximumOperatingDepth())) m"
+ }
+}
diff --git a/Sources/RemoraUI/Resources/Localizable.xcstrings b/Sources/RemoraUI/Resources/Localizable.xcstrings
@@ -0,0 +1,476 @@
+{
+ "sourceLanguage": "en",
+ "strings": {
+ "%@ is not a certified dive computer.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ n'est pas un ordinateur de plongée certifié."
+ }
+ }
+ }
+ },
+ "%lld%%": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld %%"
+ }
+ }
+ }
+ },
+ "%lld%% (air)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld %% (air)"
+ }
+ }
+ }
+ },
+ "Advanced": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avancés"
+ }
+ }
+ }
+ },
+ "Advanced settings": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Réglages avancés"
+ }
+ }
+ }
+ },
+ "Always dive with a primary dive computer, and follow it when the two disagree.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongez toujours avec un ordinateur de plongée principal, et suivez-le en cas d'écart."
+ }
+ }
+ }
+ },
+ "Ascent %lld metres per minute": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Remontée %lld mètres par minute"
+ }
+ }
+ }
+ },
+ "Ascent too fast": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Remontée trop rapide"
+ }
+ }
+ }
+ },
+ "Before you dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avant de plonger"
+ }
+ }
+ }
+ },
+ "Below %lld min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sous %lld min"
+ }
+ }
+ }
+ },
+ "Ceiling broken": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plafond franchi"
+ }
+ }
+ }
+ },
+ "Conservatism": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Prudence"
+ }
+ }
+ }
+ },
+ "Critical ppO2": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ppO2 critique"
+ }
+ }
+ }
+ },
+ "Custom": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Personnalisée"
+ }
+ }
+ }
+ },
+ "Custom (%@)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Personnalisée (%@)"
+ }
+ }
+ }
+ },
+ "DEPTH UNKNOWN\nFollow your primary computer": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "PROFONDEUR INCONNUE\nSuivez votre ordinateur principal"
+ }
+ }
+ }
+ },
+ "Depth limit": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur limite"
+ }
+ }
+ }
+ },
+ "Dive within the limits of your training. You are responsible for your settings and your gas.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongez dans les limites de votre formation. Vous êtes responsable de vos réglages et de votre mélange."
+ }
+ }
+ }
+ },
+ "Fast ascent": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Remontée rapide"
+ }
+ }
+ }
+ },
+ "Fresh": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Douce"
+ }
+ }
+ }
+ },
+ "GF high %lld%%": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "GF haut %lld %%"
+ }
+ }
+ }
+ },
+ "GF low %lld%%": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "GF bas %lld %%"
+ }
+ }
+ }
+ },
+ "Gas": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mélange"
+ }
+ }
+ }
+ },
+ "High (GF 30/70)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Élevée (GF 30/70)"
+ }
+ }
+ }
+ },
+ "High ppO2": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ppO2 élevée"
+ }
+ }
+ }
+ },
+ "I understand and accept": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "J'ai compris, j'accepte"
+ }
+ }
+ }
+ },
+ "Low (GF 50/85)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Faible (GF 50/85)"
+ }
+ }
+ }
+ },
+ "Low NDL": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "NDL bas"
+ }
+ }
+ }
+ },
+ "Maximum operating depth": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur maximale du mélange"
+ }
+ }
+ }
+ },
+ "Maximum operating depth: %@ m": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur maximale du mélange : %@ m"
+ }
+ }
+ }
+ },
+ "Maximum ppO2": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ppO2 maximale"
+ }
+ }
+ }
+ },
+ "Medium (GF 40/80)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Moyenne (GF 40/80)"
+ }
+ }
+ }
+ },
+ "NDL alarm": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Alarme de NDL"
+ }
+ }
+ }
+ },
+ "No computation guarantees the absence of decompression sickness.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucun calcul ne garantit l'absence d'accident de décompression."
+ }
+ }
+ }
+ },
+ "Off": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Désactivée"
+ }
+ }
+ }
+ },
+ "Oxygen": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Oxygène"
+ }
+ }
+ }
+ },
+ "SAFETY STOP": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "PALIER DE SÉCURITÉ"
+ }
+ }
+ }
+ },
+ "STOP %lld m": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "PALIER %lld m"
+ }
+ }
+ }
+ },
+ "Safety stop 3 min at 5 m": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Palier de sécurité 3 min à 5 m"
+ }
+ }
+ }
+ },
+ "Safety stop done ✓": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Palier de sécurité fait ✓"
+ }
+ }
+ }
+ },
+ "Safety stop missed": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Palier de sécurité sauté"
+ }
+ }
+ }
+ },
+ "Salt": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Salée"
+ }
+ }
+ }
+ },
+ "Settings": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Réglages"
+ }
+ }
+ }
+ },
+ "Standard (EN 13319)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Standard (EN 13319)"
+ }
+ }
+ }
+ },
+ "Terms of use": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conditions d'utilisation"
+ }
+ }
+ }
+ },
+ "Water": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Eau"
+ }
+ }
+ }
+ },
+ "surface in %lld min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "surface dans %lld min"
+ }
+ }
+ }
+ }
+ },
+ "version": "1.0"
+}
diff --git a/Sources/RemoraUI/SettingsViews.swift b/Sources/RemoraUI/SettingsViews.swift
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import SwiftUI
+import RemoraDeco
+
+/// Diver settings: oxygen percentage, water type and NDL alarm; conservatism and maximum ppO2 are one level
+/// down, in the advanced settings. The app owns the storage: it passes a binding and saves on change.
+public struct DiveSettingsView: View {
+ @Binding var settings: UserSettings
+ let ndlAlarmNote: String?
+ let altitudeNote: String?
+
+ /// The notes are the footers specific to the device (how the alarm shows, where the altitude comes from).
+ public init(settings: Binding<UserSettings>, ndlAlarmNote: String? = nil, altitudeNote: String? = nil) {
+ _settings = settings
+ self.ndlAlarmNote = ndlAlarmNote
+ self.altitudeNote = altitudeNote
+ }
+
+ public var body: some View {
+ List {
+ Section {
+ Picker(selection: $settings.oxygenPercent) {
+ ForEach(Array(UserSettings.Limits.oxygenPercent), id: \.self) { p in
+ Text(SettingsText.oxygen(p)).tag(p)
+ }
+ } label: {
+ Text("Oxygen", bundle: .module)
+ }
+ Picker(selection: $settings.water) {
+ ForEach(Water.allCases, id: \.self) { Text($0.label).tag($0) }
+ } label: {
+ Text("Water", bundle: .module)
+ }
+ } footer: {
+ Text("Maximum operating depth: \(Format.depth(settings.maximumOperatingDepth())) m", bundle: .module)
+ }
+
+ Section {
+ Picker(selection: $settings.ndlAlarmMinutes) {
+ ForEach(UserSettings.Limits.ndlAlarmMinutes, id: \.self) { m in
+ Text(SettingsText.ndlAlarm(m)).tag(m)
+ }
+ } label: {
+ Text("NDL alarm", bundle: .module)
+ }
+ } footer: {
+ if let ndlAlarmNote { Text(ndlAlarmNote) }
+ }
+
+ Section {
+ NavigationLink {
+ AdvancedDiveSettingsView(settings: $settings)
+ } label: {
+ Text("Advanced settings", bundle: .module)
+ }
+ } footer: {
+ if let altitudeNote { Text(altitudeNote) }
+ }
+ }
+ .navigationTitle(Text("Settings", bundle: .module))
+ }
+}
+
+/// Advanced settings: conservatism (gradient factors) and maximum ppO2.
+public struct AdvancedDiveSettingsView: View {
+ @Binding var settings: UserSettings
+
+ public init(settings: Binding<UserSettings>) { _settings = settings }
+
+ public var body: some View {
+ List {
+ Section {
+ Picker(selection: $settings.conservatism) {
+ ForEach(UserSettings.Conservatism.allCases, id: \.self) { Text($0.label).tag($0) }
+ } label: {
+ Text("Conservatism", bundle: .module)
+ }
+ if settings.conservatism == .custom {
+ Stepper(value: $settings.customGFLowPercent,
+ in: UserSettings.Limits.gfLowPercent.lowerBound...settings.customGFHighPercent, step: 5) {
+ Text("GF low \(settings.customGFLowPercent)%", bundle: .module)
+ }
+ Stepper(value: $settings.customGFHighPercent,
+ in: max(UserSettings.Limits.gfHighPercent.lowerBound, settings.customGFLowPercent)...100, step: 5) {
+ Text("GF high \(settings.customGFHighPercent)%", bundle: .module)
+ }
+ }
+ } header: {
+ Text("Conservatism", bundle: .module)
+ }
+ Section {
+ Picker(selection: $settings.ppO2Max) {
+ ForEach(SettingsText.ppO2Choices, id: \.self) { v in
+ Text(verbatim: SettingsText.ppO2(v)).tag(v)
+ }
+ } label: {
+ Text("Maximum ppO2", bundle: .module)
+ }
+ } header: {
+ Text("Oxygen", bundle: .module)
+ }
+ }
+ .navigationTitle(Text("Advanced", bundle: .module))
+ }
+}
+
+/// The settings as read-only rows, in the same order and with the same words as the settings screens.
+/// Meant to be placed in a `List` section or a `Form`.
+public struct SettingsSummary: View {
+ let settings: UserSettings
+
+ public init(settings: UserSettings) { self.settings = settings }
+
+ public var body: some View {
+ row("Gas", settings.gas.description)
+ row("Maximum operating depth", SettingsText.maximumOperatingDepth(settings))
+ row("Water", settings.water.label)
+ row("NDL alarm", SettingsText.ndlAlarm(settings.ndlAlarmMinutes))
+ row("Conservatism", SettingsText.conservatism(settings))
+ row("Maximum ppO2", SettingsText.ppO2(settings.ppO2Max))
+ }
+
+ private func row(_ title: LocalizedStringKey, _ value: String) -> some View {
+ LabeledContent {
+ Text(value)
+ } label: {
+ Text(title, bundle: .module)
+ }
+ }
+}
diff --git a/Sources/RemoraUI/Terms.swift b/Sources/RemoraUI/Terms.swift
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import SwiftUI
+
+/// Warning to accept at first launch. Changing `version` makes the user accept it again.
+public struct Terms: Sendable {
+ public var version: Int
+ /// UserDefaults key holding the accepted version.
+ public var acceptedKey: String
+ public var appName: String
+ /// The risk specific to the device ("The watch can fail…"), in the language of the interface.
+ public var devicePoint: String
+ /// Full terms of use.
+ public var link: URL
+
+ public init(version: Int, acceptedKey: String = "termsAcceptedVersion", appName: String,
+ devicePoint: String, link: URL) {
+ self.version = version
+ self.acceptedKey = acceptedKey
+ self.appName = appName
+ self.devicePoint = devicePoint
+ self.link = link
+ }
+
+ public var title: String { String(localized: "Before you dive", bundle: .module) }
+
+ public var points: [String] {
+ [String(localized: "\(appName) is not a certified dive computer.", bundle: .module),
+ String(localized: "Always dive with a primary dive computer, and follow it when the two disagree.", bundle: .module),
+ String(localized: "No computation guarantees the absence of decompression sickness.", bundle: .module),
+ devicePoint,
+ String(localized: "Dive within the limits of your training. You are responsible for your settings and your gas.", bundle: .module)]
+ }
+
+ public var accept: String { String(localized: "I understand and accept", bundle: .module) }
+}
+
+/// Warning to accept at first launch (and after a change of `Terms.version`).
+public struct TermsView: View {
+ let terms: Terms
+ let onAccept: () -> Void
+
+ public init(terms: Terms, onAccept: @escaping () -> Void) {
+ self.terms = terms
+ self.onAccept = onAccept
+ }
+
+ public var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 10) {
+ Label(terms.title, systemImage: "exclamationmark.triangle.fill")
+ .font(.headline)
+ .foregroundStyle(.orange)
+ ForEach(terms.points, id: \.self) { point in
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(verbatim: "•")
+ Text(point).fixedSize(horizontal: false, vertical: true)
+ }
+ .font(.footnote)
+ }
+ Link(destination: terms.link) { Text("Terms of use", bundle: .module) }
+ .font(.footnote)
+ Button(terms.accept, action: onAccept)
+ .buttonStyle(.borderedProminent)
+ .tint(.orange)
+ .padding(.top, 4)
+ }
+ .padding()
+ }
+ }
+}
+
+extension View {
+ /// Shows `TermsView` until the current version has been accepted (the `-acceptTerms` launch argument
+ /// skips it, for screenshots).
+ public func requiresTerms(_ terms: Terms) -> some View { modifier(TermsGate(terms: terms)) }
+}
+
+private struct TermsGate: ViewModifier {
+ let terms: Terms
+ @AppStorage private var accepted: Int
+
+ init(terms: Terms) {
+ self.terms = terms
+ _accepted = AppStorage(wrappedValue: 0, terms.acceptedKey)
+ }
+
+ func body(content: Content) -> some View {
+ if accepted >= terms.version || CommandLine.arguments.contains("-acceptTerms") {
+ content
+ } else {
+ TermsView(terms: terms) { accepted = terms.version }
+ }
+ }
+}
diff --git a/Tests/RemoraDecoTests/DiveTrackerTests.swift b/Tests/RemoraDecoTests/DiveTrackerTests.swift
@@ -0,0 +1,256 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+import Testing
+@testable import RemoraDeco
+
+/// Scripted depth source: one reading per second, on the same clock as the wall clock.
+struct Script {
+ var tracker = DiveTracker()
+ var events: [DiveTracker.Event] = []
+ var configuration = DiveComputer.Configuration()
+ var seconds = 0.0
+ var depth = 0.0
+ let origin = Date(timeIntervalSinceReferenceDate: 800_000_000)
+ let scale = DepthScale()
+
+ var now: Date { origin.addingTimeInterval(seconds) }
+
+ /// One reading at `depth`, then the clock moves one second forward.
+ mutating func read(_ depth: Double) {
+ self.depth = depth
+ send(scale.pressure(atDepth: depth), submerged: depth > 0)
+ }
+
+ /// `count` readings at a constant depth.
+ mutating func stay(at depth: Double, seconds count: Int) {
+ for _ in 0..<count { read(depth) }
+ }
+
+ /// Goes to `target` at `rate` m/min, one reading per second.
+ mutating func move(to target: Double, rate: Double) {
+ let step = rate / 60
+ while abs(depth - target) > 1e-9 {
+ read(depth < target ? min(target, depth + step) : max(target, depth - step))
+ }
+ }
+
+ /// Underwater, the sensor reports that it cannot measure.
+ mutating func lost(seconds count: Int) {
+ for _ in 0..<count { send(nil, submerged: true) }
+ }
+
+ /// The source says nothing at all: only the watchdog runs, every 2 s.
+ mutating func silent(seconds count: Int) {
+ for _ in 0..<(count / 2) {
+ seconds += 2
+ events += tracker.tick(now: now)
+ }
+ }
+
+ private mutating func send(_ absolute: Double?, submerged: Bool) {
+ let reading = DiveReading.pressure(time: now.timeIntervalSinceReferenceDate,
+ surface: scale.surfacePressure, absolute: absolute, submerged: submerged)
+ events += tracker.handle(reading, now: now, configuration: configuration, logbook: nil)
+ seconds += 1
+ }
+
+ func cues(_ cue: DiveCue) -> Int { events.filter { $0 == .cue(cue) }.count }
+
+ var endedDive: DiveLog? {
+ for case .diveEnded(let dive, _) in events { return dive }
+ return nil
+ }
+}
+
+@Suite("Dive tracker")
+struct DiveTrackerTests {
+ @Test func normalDiveStartsOnSubmersionAndEndsAfterAMinuteAtTheSurface() {
+ var s = Script()
+ s.stay(at: 0, seconds: 3)
+ #expect(!s.tracker.isDiving)
+ s.move(to: 18, rate: 18)
+ #expect(s.tracker.isDiving)
+ #expect(s.events.first == .diveStarted(simulation: false))
+ s.stay(at: 18, seconds: 20 * 60)
+ s.move(to: 5, rate: 9)
+ s.stay(at: 5, seconds: 180)
+ s.move(to: 0, rate: 9)
+ s.stay(at: 0, seconds: 55)
+ #expect(s.tracker.isDiving)
+ s.stay(at: 0, seconds: 8)
+ #expect(!s.tracker.isDiving)
+
+ let dive = s.endedDive
+ #expect(dive != nil)
+ #expect(abs((dive?.maxDepth ?? 0) - 18) < 0.05)
+ #expect(dive?.source == .remora)
+ #expect(s.cues(.safetyStopStarted) == 1)
+ #expect(s.cues(.safetyStopDone) == 1)
+ #expect(s.cues(.alarm) == 0)
+ #expect(s.cues(.depthLost) == 0)
+ // Back at the surface, nothing starts a new dive.
+ let count = s.events.count
+ s.stay(at: 0, seconds: 5)
+ #expect(s.events.count == count)
+ }
+
+ @Test func sensorThatCannotMeasureAtDepthHoldsTheDepth() {
+ var s = Script()
+ s.move(to: 20, rate: 18)
+ s.stay(at: 20, seconds: 60)
+ s.lost(seconds: 10)
+ #expect(s.tracker.depthUnknown)
+ #expect(s.tracker.isAlarming)
+ #expect(s.tracker.isDiving)
+ #expect(abs((s.tracker.status?.depth ?? 0) - 20) < 0.01)
+ #expect(s.cues(.depthLost) == 1)
+ #expect(s.cues(.alarm) == 5) // every 2 s for 10 s
+ // Time kept moving: the tissues keep loading at the held depth.
+ #expect(abs((s.tracker.status?.elapsed ?? 0) * 60 - s.seconds) < 3)
+ s.read(20)
+ #expect(!s.tracker.depthUnknown)
+ #expect(!s.tracker.isAlarming)
+ }
+
+ @Test func silentSourceAtDepthIsCaughtByTheWatchdog() {
+ var s = Script()
+ s.move(to: 20, rate: 18)
+ s.stay(at: 20, seconds: 60)
+ let elapsedBefore = s.tracker.status?.elapsed ?? 0
+ s.silent(seconds: 4)
+ #expect(!s.tracker.depthUnknown) // 5 s of silence are tolerated
+ s.silent(seconds: 20)
+ #expect(s.tracker.depthUnknown)
+ #expect(s.tracker.isDiving)
+ #expect(abs((s.tracker.status?.depth ?? 0) - 20) < 0.01)
+ #expect(s.cues(.depthLost) == 1)
+ #expect((s.tracker.status?.elapsed ?? 0) - elapsedBefore > 20.0 / 60)
+ // Never a false return to the surface, however long the silence lasts.
+ s.silent(seconds: 180)
+ #expect(s.tracker.isDiving)
+ s.read(19)
+ #expect(!s.tracker.depthUnknown)
+ }
+
+ @Test func silentSourceNearTheSurfaceEndsTheDive() {
+ var s = Script()
+ s.move(to: 5, rate: 18)
+ s.stay(at: 5, seconds: 30)
+ s.move(to: 1.2, rate: 9)
+ s.stay(at: 1.2, seconds: 5)
+ s.silent(seconds: 60)
+ #expect(s.tracker.isDiving)
+ s.silent(seconds: 10)
+ #expect(!s.tracker.isDiving)
+ #expect(s.cues(.depthLost) == 0)
+ #expect(s.endedDive != nil)
+ }
+
+ @Test func oscillatingWarningIsCuedAndLoggedOncePerPeriod() {
+ var s = Script()
+ s.configuration.gas = .nitrox(28) // long no-stop time: only the depth limit shows up
+ s.move(to: 37.9, rate: 30)
+ #expect(s.tracker.warnings.isEmpty)
+ for i in 0..<26 { s.read(i % 2 == 0 ? 38.1 : 37.9) }
+ #expect(s.cues(.warning) == 2) // when it appears, then 15 s later
+ #expect(s.cues(.alarm) == 0)
+ s.events += s.tracker.end()
+ #expect(s.endedDive?.events.filter { $0.warning == .depthLimit }.count == 1)
+ }
+
+ @Test func safetyStopCanBeRedoneAfterGoingBackDown() {
+ var s = Script()
+ s.move(to: 15, rate: 18)
+ s.stay(at: 15, seconds: 300)
+ s.move(to: 5, rate: 9)
+ s.stay(at: 5, seconds: 60)
+ #expect(s.cues(.safetyStopStarted) == 1)
+ s.move(to: 8, rate: 9)
+ s.stay(at: 8, seconds: 20)
+ #expect(s.tracker.status?.safetyStop == .pending)
+ s.move(to: 5, rate: 9)
+ s.stay(at: 5, seconds: 120)
+ #expect(s.cues(.safetyStopDone) == 0) // the countdown started again from zero
+ s.stay(at: 5, seconds: 70)
+ #expect(s.cues(.safetyStopStarted) == 2)
+ #expect(s.cues(.safetyStopDone) == 1)
+ #expect(s.tracker.status?.safetyStop == .done)
+ }
+
+ @Test func nothingIsKeptWhenTheDiverNeverWentDown() {
+ var s = Script()
+ s.stay(at: 0.6, seconds: 5)
+ #expect(s.tracker.isDiving)
+ s.stay(at: 0, seconds: 120)
+ #expect(s.tracker.isDiving) // never below 1 m: no automatic end
+ s.events += s.tracker.end()
+ #expect(s.events.last == .diveEnded(nil, simulation: false))
+ #expect(!s.tracker.isDiving)
+ }
+
+ @Test func simulatedDiveIgnoresTheSensorAndARealDiveCanFollow() {
+ var s = Script()
+ s.events += s.tracker.startSimulation(now: s.now, configuration: s.configuration, logbook: nil)
+ #expect(s.events == [.diveStarted(simulation: true)])
+ let depths = DemoProfile.shallow.depths + Array(repeating: 0, count: 61)
+ for (t, d) in depths.enumerated() {
+ if t == 100 { s.read(30) } // the real sensor is ignored during the demo
+ s.events += s.tracker.simulate(time: Double(t), depth: d, temperature: 20, now: s.now)
+ }
+ #expect(!s.tracker.isDiving)
+ let demo = s.endedDive
+ #expect(demo?.source == .simulation)
+ #expect(abs((demo?.maxDepth ?? 0) - 8) < 0.05)
+
+ s.events = []
+ s.read(2)
+ #expect(s.events.first == .diveStarted(simulation: false))
+ #expect(s.tracker.isDiving)
+ #expect(!s.tracker.isSimulation)
+ }
+}
+
+@MainActor
+final class MemoryStore: DiveLogStore {
+ var settings = UserSettings()
+ var logbook = Logbook()
+ func add(_ dive: DiveLog) -> DiveLog {
+ logbook.add(dive)
+ return logbook.dives.first { $0.id == dive.id } ?? dive
+ }
+}
+
+@Suite("Dive monitor")
+@MainActor
+struct DiveMonitorTests {
+ @Test func savesTheDiveAndPassesTheCuesOn() {
+ let store = MemoryStore()
+ var cues: [DiveCue] = []
+ var clock = Date(timeIntervalSinceReferenceDate: 800_000_000)
+ let monitor = DiveMonitor(store: store, feedback: { cues.append($0) }, now: { clock })
+ var started: [Bool] = []
+ var ended: [DiveLog?] = []
+ monitor.onDiveStarted = { started.append($0) }
+ monitor.onDiveEnded = { dive, _ in ended.append(dive) }
+
+ let scale = DepthScale()
+ func read(_ depth: Double) {
+ monitor.receive(.pressure(time: clock.timeIntervalSinceReferenceDate, surface: scale.surfacePressure,
+ absolute: scale.pressure(atDepth: depth), submerged: depth > 0))
+ clock = clock.addingTimeInterval(1)
+ }
+ monitor.receive(.temperature(12))
+ for _ in 0..<120 { read(6) }
+ #expect(monitor.isDiving)
+ #expect(monitor.temperature == 12)
+ for _ in 0..<62 { read(0) }
+
+ #expect(!monitor.isDiving)
+ #expect(started == [false])
+ #expect(ended.count == 1)
+ #expect(store.logbook.dives.count == 1)
+ #expect(monitor.finishedDive?.number == 1)
+ #expect(monitor.finishedDive?.minTemperature == 12)
+ #expect(cues.last == .diveSaved)
+ }
+}
diff --git a/Tests/RemoraUITests/FormatTests.swift b/Tests/RemoraUITests/FormatTests.swift
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+import Testing
+import RemoraDeco
+@testable import RemoraUI
+
+@Suite("Format")
+struct FormatTests {
+ @Test func clockAndDurations() {
+ #expect(Format.clock(754) == "12:34")
+ #expect(Format.clock(3723) == "1:02:03")
+ #expect(Format.minutes(2520) == "42 min")
+ #expect(Format.hours(3.08) == "3 h 05")
+ #expect(Format.hours(0.75) == "45 min")
+ }
+
+ @Test func noDecompressionLimit() {
+ #expect(Format.ndl(nil) == ">99")
+ #expect(Format.ndl(120) == ">99")
+ #expect(Format.ndl(17.8) == "17")
+ }
+
+ @Test func decimalsFollowTheInterfaceLanguage() {
+ #expect(Format.depth(12.34) == (Format.isFrench ? "12,3" : "12.3"))
+ }
+
+ @Test func everyWarningHasALabelAndALevel() {
+ for warning in DiveComputer.Warning.allCases {
+ #expect(!warning.label.isEmpty)
+ #expect(warning.color == (warning.isViolation ? .red : .orange))
+ }
+ }
+}