Skip to main content

divecomputer_core/
dive.rs

1//! The dive data model ([spec](https://michidk.github.io/divecomputer-rs/spec/common/data-model.html)).
2//!
3//! A download yields [`RawDive`]s; a family's parser turns one into a [`Dive`]. The model
4//! mirrors one DiveJSON *recording*: header values, gas mixes, tanks, samples and events
5//! from one device.
6
7use alloc::{string::String, vec::Vec};
8use core::time::Duration;
9
10use crate::units::{Depth, GasFraction, Pressure, Temperature};
11
12/// A dive as downloaded, before parsing: the bytes exactly as the device sent them, and
13/// the fingerprint that identifies the dive for incremental downloads.
14#[derive(Clone, Debug, PartialEq, Eq, Hash)]
15pub struct RawDive {
16    fingerprint: Vec<u8>,
17    data: Vec<u8>,
18}
19
20impl RawDive {
21    /// Creates a raw dive.
22    #[must_use]
23    pub const fn new(fingerprint: Vec<u8>, data: Vec<u8>) -> Self {
24        Self { fingerprint, data }
25    }
26
27    /// The bytes that identify this dive on its device. Store the newest dive's
28    /// fingerprint and pass it to the next download to fetch only newer dives.
29    #[must_use]
30    pub fn fingerprint(&self) -> &[u8] {
31        &self.fingerprint
32    }
33
34    /// The dive's raw bytes, in the family's log format.
35    #[must_use]
36    pub fn data(&self) -> &[u8] {
37        &self.data
38    }
39}
40
41/// A parsed dive: one device's recording of one dive.
42///
43/// Every field is optional or may be empty: a parser fills what the device recorded and
44/// leaves the rest absent, never zero-filled. Values are in the units of
45/// [`crate::units`]; times are elapsed from the dive start.
46#[derive(Clone, Debug, Default, PartialEq)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize))]
48#[non_exhaustive]
49pub struct Dive {
50    /// The dive start on the device's local wall clock. Combine with
51    /// [`utc_offset`](Self::utc_offset) when that is known; never convert through the
52    /// host's time zone.
53    pub start: Option<jiff::civil::DateTime>,
54    /// Offset of [`start`](Self::start) from UTC in seconds, only when the device
55    /// recorded its time zone.
56    pub utc_offset: Option<i32>,
57    /// The device's own dive counter.
58    pub number: Option<u32>,
59    /// Dive time as stored by the device. May differ from the last sample time.
60    #[cfg_attr(feature = "serde", serde(with = "millis_opt"))]
61    pub duration: Option<Duration>,
62    /// Maximum depth as stored by the device, not recomputed from samples.
63    pub max_depth: Option<Depth>,
64    /// Average depth as stored by the device.
65    pub avg_depth: Option<Depth>,
66    /// Lowest water temperature as stored by the device.
67    pub min_temperature: Option<Temperature>,
68    /// Highest water temperature as stored by the device.
69    pub max_temperature: Option<Temperature>,
70    /// The mode the device ran in.
71    pub mode: Option<DiveMode>,
72    /// The water type the device was set to.
73    pub salinity: Option<Salinity>,
74    /// The water density the device was set to, in kg/m³.
75    pub water_density: Option<f64>,
76    /// The surface (atmospheric) pressure the device measured or assumed.
77    pub surface_pressure: Option<Pressure>,
78    /// The decompression model the device ran, with its settings.
79    pub deco_model: Option<DecoModel>,
80    /// Surface position at the start of the dive.
81    pub location: Option<Location>,
82    /// The device that recorded the dive.
83    pub device: DeviceInfo,
84    /// Gas mixes; [`Sample`]s and [`Event`]s refer to them by index.
85    pub gas_mixes: Vec<GasMix>,
86    /// Tanks; [`TankPressure`]s refer to them by index.
87    pub tanks: Vec<Tank>,
88    /// Samples in time order.
89    pub samples: Vec<Sample>,
90    /// Events in time order. An event may fall after the last sample.
91    pub events: Vec<Event>,
92}
93
94/// Identification of the device that recorded a dive. Strings are as the device
95/// reports them.
96#[derive(Clone, Debug, Default, PartialEq, Eq)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize))]
98#[non_exhaustive]
99pub struct DeviceInfo {
100    /// The maker, for example `Shearwater`.
101    pub brand: Option<String>,
102    /// The product name, for example `Perdix 2`.
103    pub model: Option<String>,
104    /// The device's serial number in its own rendering.
105    pub serial: Option<String>,
106    /// The firmware version the device was running.
107    pub firmware: Option<String>,
108}
109
110/// The mode a dive computer ran in.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
112#[cfg_attr(
113    feature = "serde",
114    derive(serde::Serialize),
115    serde(rename_all = "snake_case")
116)]
117#[non_exhaustive]
118pub enum DiveMode {
119    /// Open circuit.
120    OpenCircuit,
121    /// Closed-circuit rebreather.
122    ClosedCircuit,
123    /// Semi-closed rebreather.
124    SemiClosed,
125    /// Depth and time only, no decompression calculation.
126    Gauge,
127    /// Breath-hold diving.
128    Freedive,
129}
130
131/// The water type a device converts pressure to depth with.
132#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
133#[cfg_attr(
134    feature = "serde",
135    derive(serde::Serialize),
136    serde(rename_all = "snake_case")
137)]
138#[non_exhaustive]
139pub enum Salinity {
140    /// Fresh water.
141    Fresh,
142    /// The EN 13319 convention (1020 kg/m³).
143    En13319,
144    /// Salt water.
145    Salt,
146}
147
148/// A decompression model and the settings it ran with.
149#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
150#[cfg_attr(
151    feature = "serde",
152    derive(serde::Serialize),
153    serde(tag = "algorithm", rename_all = "snake_case")
154)]
155#[non_exhaustive]
156pub enum DecoModel {
157    /// Bühlmann with gradient factors.
158    Buhlmann {
159        /// Gradient factor low, percent.
160        gf_low: u8,
161        /// Gradient factor high, percent.
162        gf_high: u8,
163    },
164    /// VPM-B, optionally combined with a Bühlmann gradient factor (VPM-B/GFS).
165    Vpm {
166        /// Conservatism on the device's own scale.
167        conservatism: u8,
168        /// The GFS gradient factor in percent, for VPM-B/GFS.
169        gfs_gradient_factor: Option<u8>,
170    },
171    /// DCIEM.
172    Dciem,
173}
174
175/// A position in decimal degrees (WGS 84).
176#[derive(Clone, Copy, Debug, PartialEq)]
177#[cfg_attr(feature = "serde", derive(serde::Serialize))]
178#[non_exhaustive]
179pub struct Location {
180    /// Latitude, −90 to 90.
181    pub latitude: f64,
182    /// Longitude, −180 to 180.
183    pub longitude: f64,
184}
185
186impl Location {
187    /// A position in decimal degrees.
188    #[must_use]
189    pub const fn new(latitude: f64, longitude: f64) -> Self {
190        Self {
191            latitude,
192            longitude,
193        }
194    }
195}
196
197/// A breathing gas.
198#[derive(Clone, Copy, Debug, PartialEq)]
199#[cfg_attr(feature = "serde", derive(serde::Serialize))]
200#[non_exhaustive]
201pub struct GasMix {
202    /// Oxygen share.
203    pub oxygen: GasFraction,
204    /// Helium share; 0 for nitrox and air.
205    pub helium: GasFraction,
206    /// What the mix is used for, when the device says.
207    pub usage: Option<GasUsage>,
208}
209
210impl GasMix {
211    /// A mix of oxygen and helium, the rest nitrogen.
212    #[must_use]
213    pub const fn new(oxygen: GasFraction, helium: GasFraction, usage: Option<GasUsage>) -> Self {
214        Self {
215            oxygen,
216            helium,
217            usage,
218        }
219    }
220}
221
222/// What a gas or tank is used for.
223#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
224#[cfg_attr(
225    feature = "serde",
226    derive(serde::Serialize),
227    serde(rename_all = "snake_case")
228)]
229#[non_exhaustive]
230pub enum GasUsage {
231    /// Breathed open circuit.
232    OpenCircuit,
233    /// Rebreather diluent.
234    Diluent,
235    /// Rebreather oxygen.
236    Oxygen,
237}
238
239/// A tank, usually one monitored by a wireless pressure transmitter.
240#[derive(Clone, Debug, Default, PartialEq)]
241#[cfg_attr(feature = "serde", derive(serde::Serialize))]
242#[non_exhaustive]
243pub struct Tank {
244    /// The device's name for the tank or transmitter.
245    pub name: Option<String>,
246    /// The transmitter's serial number in the device's rendering.
247    pub transmitter: Option<String>,
248    /// What the tank is used for.
249    pub usage: Option<GasUsage>,
250    /// Index into [`Dive::gas_mixes`].
251    pub gas_mix: Option<usize>,
252    /// Pressure at the start of the dive.
253    pub begin_pressure: Option<Pressure>,
254    /// Pressure at the end of the dive.
255    pub end_pressure: Option<Pressure>,
256}
257
258/// The values a device recorded at one instant. Absent values were not recorded.
259#[derive(Clone, Debug, Default, PartialEq)]
260#[cfg_attr(feature = "serde", derive(serde::Serialize))]
261#[non_exhaustive]
262pub struct Sample {
263    /// Elapsed time since the dive start.
264    #[cfg_attr(feature = "serde", serde(with = "millis"))]
265    pub time: Duration,
266    /// Depth.
267    pub depth: Option<Depth>,
268    /// Water temperature.
269    pub temperature: Option<Temperature>,
270    /// Tank pressures, one entry per tank that reported.
271    pub pressures: Vec<TankPressure>,
272    /// The ppO₂ the device computed or voted from its sensors.
273    pub ppo2: Option<Pressure>,
274    /// ppO₂ of each oxygen sensor, by sensor number (0 = first); `None` for a sensor
275    /// without a usable reading.
276    pub ppo2_sensors: Vec<Option<Pressure>>,
277    /// Rebreather setpoint.
278    pub setpoint: Option<Pressure>,
279    /// CNS oxygen toxicity, in percent.
280    pub cns: Option<f64>,
281    /// No-decompression limit or the next decompression stop.
282    pub deco: Option<Deco>,
283    /// Time to surface.
284    #[cfg_attr(feature = "serde", serde(with = "millis_opt"))]
285    pub time_to_surface: Option<Duration>,
286    /// Remaining gas time from air integration.
287    #[cfg_attr(feature = "serde", serde(with = "millis_opt"))]
288    pub gas_time_remaining: Option<Duration>,
289    /// Gradient factor of the leading tissue (GF99), in percent.
290    pub gradient_factor: Option<u8>,
291}
292
293/// A tank pressure reading.
294#[derive(Clone, Copy, Debug, PartialEq)]
295#[cfg_attr(feature = "serde", derive(serde::Serialize))]
296#[non_exhaustive]
297pub struct TankPressure {
298    /// Index into [`Dive::tanks`].
299    pub tank: usize,
300    /// The pressure.
301    pub pressure: Pressure,
302}
303
304impl TankPressure {
305    /// A reading for tank `tank`.
306    #[must_use]
307    pub const fn new(tank: usize, pressure: Pressure) -> Self {
308        Self { tank, pressure }
309    }
310}
311
312/// Decompression state at a sample.
313#[derive(Clone, Copy, Debug, PartialEq)]
314#[cfg_attr(
315    feature = "serde",
316    derive(serde::Serialize),
317    serde(tag = "kind", rename_all = "snake_case")
318)]
319#[non_exhaustive]
320pub enum Deco {
321    /// No decompression obligation; `time` is the remaining no-decompression time.
322    Ndl {
323        /// Remaining no-decompression time.
324        #[cfg_attr(feature = "serde", serde(with = "millis"))]
325        time: Duration,
326    },
327    /// A decompression stop is required.
328    Stop {
329        /// Depth of the next stop.
330        depth: Depth,
331        /// Time at that stop.
332        #[cfg_attr(feature = "serde", serde(with = "millis"))]
333        time: Duration,
334    },
335}
336
337/// Something that happened at one instant of the dive.
338#[derive(Clone, Copy, Debug, PartialEq, Eq)]
339#[cfg_attr(feature = "serde", derive(serde::Serialize))]
340#[non_exhaustive]
341pub struct Event {
342    /// Elapsed time since the dive start.
343    #[cfg_attr(feature = "serde", serde(with = "millis"))]
344    pub time: Duration,
345    /// What happened.
346    pub kind: EventKind,
347}
348
349impl Event {
350    /// An event at `time`.
351    #[must_use]
352    pub const fn new(time: Duration, kind: EventKind) -> Self {
353        Self { time, kind }
354    }
355}
356
357/// The kinds of [`Event`].
358#[derive(Clone, Copy, Debug, PartialEq, Eq)]
359#[cfg_attr(
360    feature = "serde",
361    derive(serde::Serialize),
362    serde(tag = "type", rename_all = "snake_case")
363)]
364#[non_exhaustive]
365pub enum EventKind {
366    /// The breathing gas changed.
367    GasSwitch {
368        /// Index into [`Dive::gas_mixes`].
369        gas_mix: usize,
370    },
371    /// The diver marked this moment.
372    Bookmark {
373        /// Compass heading in degrees, when recorded.
374        heading: Option<u32>,
375    },
376    /// A device event with no common meaning.
377    Vendor {
378        /// The device's event code.
379        code: u32,
380        /// The event's first parameter.
381        value: u32,
382    },
383}
384
385/// Serializes a [`Duration`] as whole milliseconds.
386#[cfg(feature = "serde")]
387mod millis {
388    use core::time::Duration;
389
390    pub(super) fn serialize<S: serde::Serializer>(
391        duration: &Duration,
392        serializer: S,
393    ) -> Result<S::Ok, S::Error> {
394        serializer.serialize_u64(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
395    }
396}
397
398/// Serializes an optional [`Duration`] as whole milliseconds.
399#[cfg(feature = "serde")]
400mod millis_opt {
401    use core::time::Duration;
402
403    #[allow(clippy::ref_option, reason = "signature required by serde(with)")]
404    pub(super) fn serialize<S: serde::Serializer>(
405        duration: &Option<Duration>,
406        serializer: S,
407    ) -> Result<S::Ok, S::Error> {
408        match duration {
409            Some(duration) => super::millis::serialize(duration, serializer),
410            None => serializer.serialize_none(),
411        }
412    }
413}