1use crate::types::{
4 half_up, ExerciseCategory, FileType, Manufacturer, Position, Sport, SubSport, SwimStroke,
5 Timestamp,
6};
7
8pub(crate) mod base {
10 pub const ENUM: u8 = 0x00;
11 pub const SINT8: u8 = 0x01;
12 pub const UINT8: u8 = 0x02;
13 pub const STRING: u8 = 0x07;
14 pub const UINT8Z: u8 = 0x0A;
15 pub const BYTE: u8 = 0x0D;
16 pub const SINT16: u8 = 0x83;
17 pub const UINT16: u8 = 0x84;
18 pub const SINT32: u8 = 0x85;
19 pub const UINT32: u8 = 0x86;
20 pub const FLOAT32: u8 = 0x88;
21 pub const FLOAT64: u8 = 0x89;
22 pub const UINT16Z: u8 = 0x8B;
23 pub const UINT32Z: u8 = 0x8C;
24 pub const SINT64: u8 = 0x8E;
25 pub const UINT64: u8 = 0x8F;
26 pub const UINT64Z: u8 = 0x90;
27}
28
29const INVALID_U8: u8 = 0xFF;
31const INVALID_U32: u32 = 0xFFFF_FFFF;
32
33pub(crate) const TIMESTAMP: u8 = 253;
36const MESSAGE_INDEX: u8 = 254;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub(crate) struct FieldDef {
42 pub num: u8,
43 pub size: u8,
44 pub base: u8,
45}
46
47pub(crate) const fn field(num: u8, size: u8, base: u8) -> FieldDef {
48 FieldDef { num, size, base }
49}
50
51pub(crate) trait FieldOut {
53 fn u8(&mut self, v: u8);
54 fn u16(&mut self, v: u16);
55 fn u32(&mut self, v: u32);
56 fn i8(&mut self, v: i8);
57 fn i32(&mut self, v: i32);
58 fn str(&mut self, v: &str);
59 fn u16s(&mut self, v: &[u16]);
61 fn bytes(&mut self, v: &[u8]);
63 fn none(&mut self);
65
66 fn opt_u8(&mut self, v: Option<u8>) {
67 match v {
68 Some(v) => self.u8(v),
69 None => self.none(),
70 }
71 }
72
73 fn opt_u16(&mut self, v: Option<u16>) {
74 match v {
75 Some(v) => self.u16(v),
76 None => self.none(),
77 }
78 }
79
80 fn opt_i8(&mut self, v: Option<i8>) {
81 match v {
82 Some(v) => self.i8(v),
83 None => self.none(),
84 }
85 }
86
87 fn position(&mut self, v: Option<Position>) {
89 if let Some((lat, long)) = v.map(Position::semicircles) {
90 self.i32(lat);
91 self.i32(long);
92 } else {
93 self.none();
94 self.none();
95 }
96 }
97
98 fn opt_u32(&mut self, v: Option<u32>) {
99 match v {
100 Some(v) => self.u32(v),
101 None => self.none(),
102 }
103 }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub(crate) enum FieldError {
109 StringTooLong,
110 OutOfRange,
111}
112
113pub(crate) trait Put {
115 fn put(&mut self, bytes: &[u8]);
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
120pub(crate) struct Mask([u64; 4]);
121
122impl Mask {
123 pub(crate) const ALL: Self = Self([u64::MAX; 4]);
124 const EMPTY: Self = Self([0; 4]);
125
126 fn word_bit(i: usize) -> (usize, u64) {
127 let shift = u32::try_from(i % 64).unwrap_or(u32::MAX);
128 (i / 64, 1u64.checked_shl(shift).unwrap_or(0))
129 }
130
131 pub(crate) fn contains(self, i: usize) -> bool {
132 let (word, bit) = Self::word_bit(i);
133 self.0.get(word).is_some_and(|w| w & bit != 0)
134 }
135
136 fn insert(&mut self, i: usize) {
137 let (word, bit) = Self::word_bit(i);
138 if let Some(w) = self.0.get_mut(word) {
139 *w |= bit;
140 }
141 }
142
143 fn without(self, other: Self) -> Self {
144 let mut words = self.0;
145 for (word, out) in words.iter_mut().zip(other.0) {
146 *word &= !out;
147 }
148 Self(words)
149 }
150}
151
152pub(crate) fn kept<I: Iterator<Item = FieldDef> + Clone>(
154 table: I,
155 keep: Mask,
156) -> impl Iterator<Item = FieldDef> + Clone {
157 table.enumerate().filter(move |(i, _)| keep.contains(*i)).map(|(_, f)| f)
158}
159
160pub(crate) struct Fields<'a, I> {
162 defs: I,
163 out: Option<&'a mut dyn Put>,
164 refused: Option<FieldError>,
165 keep: Mask,
166 next: usize,
168 writing: bool,
169 nones: Mask,
170}
171
172pub(crate) const fn none_byte(base: u8, i: usize, size: usize) -> u8 {
174 match base {
175 base::STRING | base::UINT8Z | base::UINT16Z | base::UINT32Z | base::UINT64Z => 0,
176 base::SINT8 | base::SINT16 | base::SINT32 | base::SINT64 if i.saturating_add(1) == size => {
177 0x7F
178 }
179 _ => INVALID_U8,
180 }
181}
182
183pub(crate) fn is_none(base: u8, value: &[u8]) -> bool {
185 value.iter().enumerate().all(|(i, &b)| b == none_byte(base, i, value.len()))
186}
187
188impl<'a, I: Iterator<Item = FieldDef>> Fields<'a, I> {
189 pub(crate) fn new(defs: I, out: Option<&'a mut dyn Put>) -> Self {
191 Self {
192 defs,
193 out,
194 refused: None,
195 keep: Mask::ALL,
196 next: 0,
197 writing: false,
198 nones: Mask::EMPTY,
199 }
200 }
201
202 pub(crate) const fn keep(mut self, keep: Mask) -> Self {
204 self.keep = keep;
205 self
206 }
207
208 pub(crate) const fn refused(&self) -> Option<FieldError> {
210 self.refused
211 }
212
213 pub(crate) fn present(mut self) -> Mask {
215 while self.field().is_some() {
216 self.nones.insert(self.next.saturating_sub(1));
217 }
218 Mask::ALL.without(self.nones)
219 }
220
221 fn field(&mut self) -> Option<FieldDef> {
223 let def = self.defs.next()?;
224 self.writing = self.keep.contains(self.next);
225 self.next = self.next.saturating_add(1);
226 Some(def)
227 }
228
229 fn put(&mut self, bytes: &[u8]) {
230 if let (true, Some(out)) = (self.writing, self.out.as_deref_mut()) {
231 out.put(bytes);
232 }
233 }
234
235 fn refuse(&mut self, e: FieldError) {
236 self.refused.get_or_insert(e);
237 }
238
239 fn fill(&mut self, def: FieldDef) {
240 self.nones.insert(self.next.saturating_sub(1));
241 let size = usize::from(def.size);
242 for i in 0..size {
243 self.put(&[none_byte(def.base, i, size)]);
244 }
245 }
246
247 fn number(&mut self, le: &[u8]) {
248 let Some(def) = self.field() else { return };
249 let size = usize::from(def.size);
250 let (value, rest) = le.split_at(size.min(le.len()));
251 let is_none = value.len() == size && is_none(def.base, value);
252 if rest.iter().any(|&b| b != 0) || is_none {
253 self.refuse(FieldError::OutOfRange);
254 }
255 self.put(value);
256 for _ in value.len()..size {
257 self.put(&[0]);
258 }
259 }
260
261 pub(crate) fn finish(mut self) {
263 while let Some(def) = self.field() {
264 self.fill(def);
265 }
266 }
267}
268
269impl<I: Iterator<Item = FieldDef>> FieldOut for Fields<'_, I> {
270 fn u8(&mut self, v: u8) {
271 self.number(&[v]);
272 }
273
274 fn u16(&mut self, v: u16) {
275 self.number(&v.to_le_bytes());
276 }
277
278 fn u32(&mut self, v: u32) {
279 self.number(&v.to_le_bytes());
280 }
281
282 fn i8(&mut self, v: i8) {
283 self.number(&v.to_le_bytes());
284 }
285
286 fn i32(&mut self, v: i32) {
287 self.number(&v.to_le_bytes());
288 }
289
290 fn str(&mut self, v: &str) {
293 let Some(def) = self.field() else { return };
294 let bytes = v.as_bytes();
295 if bytes.is_empty() {
296 self.fill(def);
297 return;
298 }
299 if bytes.contains(&0) {
300 self.refuse(FieldError::OutOfRange);
301 return;
302 }
303 if bytes.len() >= usize::from(def.size) {
304 self.refuse(FieldError::StringTooLong);
305 return;
306 }
307 self.put(bytes);
308 for _ in bytes.len()..usize::from(def.size) {
309 self.put(&[0]);
310 }
311 }
312
313 fn u16s(&mut self, v: &[u16]) {
314 let Some(def) = self.field() else { return };
315 let size = usize::from(def.size);
316 let len = v.len().saturating_mul(2);
317 if len > size || v.contains(&u16::MAX) {
318 self.refuse(FieldError::OutOfRange);
319 }
320 if v.is_empty() {
321 self.fill(def);
322 return;
323 }
324 for x in v {
325 self.put(&x.to_le_bytes());
326 }
327 for _ in len..size {
328 self.put(&[INVALID_U8]);
329 }
330 }
331
332 fn bytes(&mut self, v: &[u8]) {
333 let Some(def) = self.field() else { return };
334 if v.len() != usize::from(def.size) || is_none(def.base, v) {
335 self.refuse(FieldError::OutOfRange);
336 return;
337 }
338 self.put(v);
339 }
340
341 fn none(&mut self) {
342 if let Some(def) = self.field() {
343 self.fill(def);
344 }
345 }
346}
347
348pub(crate) fn data_len(fields: impl Iterator<Item = FieldDef>) -> u32 {
350 fields.map(|f| u32::from(f.size)).fold(0, u32::wrapping_add)
351}
352
353pub(crate) trait Message {
355 const GLOBAL: u16;
356 const FIELDS: &'static [FieldDef];
357 fn timestamp(&self) -> Option<Timestamp>;
359 fn encode(&self, out: &mut dyn FieldOut, index: u16);
362}
363
364#[derive(Clone, Copy, Debug, PartialEq, Eq)]
366pub(crate) struct FileId {
367 file_type: FileType,
368 manufacturer: Manufacturer,
369 product: u16,
370 serial_number: Option<u32>,
371 time_created: Timestamp,
372}
373
374impl FileId {
375 #[must_use]
377 pub const fn new(
378 file_type: FileType,
379 manufacturer: Manufacturer,
380 product: u16,
381 time_created: Timestamp,
382 ) -> Self {
383 Self { file_type, manufacturer, product, serial_number: None, time_created }
384 }
385
386 #[must_use]
388 pub const fn serial_number(mut self, serial_number: u32) -> Self {
389 self.serial_number = Some(serial_number);
390 self
391 }
392}
393
394impl Message for FileId {
395 const GLOBAL: u16 = 0;
396 const FIELDS: &'static [FieldDef] = &[
397 field(0, 1, base::ENUM), field(1, 2, base::UINT16), field(2, 2, base::UINT16), field(3, 4, base::UINT32Z), field(4, 4, base::UINT32), ];
403
404 fn timestamp(&self) -> Option<Timestamp> {
405 None
406 }
407
408 fn encode(&self, out: &mut dyn FieldOut, _: u16) {
409 out.u8(self.file_type.get());
410 out.u16(self.manufacturer.get());
411 out.u16(self.product);
412 out.opt_u32(self.serial_number);
413 out.u32(self.time_created.fit());
414 }
415}
416
417pub const PRODUCT_NAME_MAX: usize = 19;
419
420#[derive(Clone, Copy, Debug, PartialEq, Eq)]
435pub struct Device<'a> {
436 pub(crate) manufacturer: Manufacturer,
437 pub(crate) product: u16,
438 pub(crate) serial_number: Option<u32>,
439 pub(crate) software_version: Option<u16>,
440 pub(crate) product_name: &'a str,
441}
442
443impl<'a> Device<'a> {
444 #[must_use]
446 pub const fn new(manufacturer: Manufacturer, product: u16) -> Self {
447 Self {
448 manufacturer,
449 product,
450 serial_number: None,
451 software_version: None,
452 product_name: "",
453 }
454 }
455
456 #[must_use]
458 pub const fn serial_number(mut self, serial_number: u32) -> Self {
459 self.serial_number = Some(serial_number);
460 self
461 }
462
463 #[must_use]
465 pub const fn software_version(mut self, hundredths: u16) -> Self {
466 self.software_version = Some(hundredths);
467 self
468 }
469
470 #[must_use]
472 pub const fn product_name(mut self, name: &'a str) -> Self {
473 self.product_name = name;
474 self
475 }
476
477 pub(crate) const fn info(&self, timestamp: Timestamp, index: u8) -> DeviceInfo<'a> {
479 DeviceInfo {
480 timestamp,
481 device_index: index,
482 manufacturer: Some(self.manufacturer),
483 serial_number: self.serial_number,
484 product: Some(self.product),
485 software_version: self.software_version,
486 product_name: self.product_name,
487 }
488 }
489}
490
491#[derive(Clone, Copy, Debug, PartialEq, Eq)]
492pub(crate) struct DeviceInfo<'a> {
493 timestamp: Timestamp,
494 device_index: u8,
495 manufacturer: Option<Manufacturer>,
496 serial_number: Option<u32>,
497 product: Option<u16>,
498 software_version: Option<u16>,
499 product_name: &'a str,
500}
501
502#[cfg(test)]
503impl<'a> DeviceInfo<'a> {
504 pub(crate) const fn new(timestamp: Timestamp) -> Self {
505 Self {
506 timestamp,
507 device_index: 0,
508 manufacturer: None,
509 serial_number: None,
510 product: None,
511 software_version: None,
512 product_name: "",
513 }
514 }
515
516 pub(crate) const fn device_index(mut self, device_index: u8) -> Self {
517 self.device_index = device_index;
518 self
519 }
520
521 pub(crate) const fn manufacturer(mut self, manufacturer: Manufacturer) -> Self {
522 self.manufacturer = Some(manufacturer);
523 self
524 }
525
526 pub(crate) const fn serial_number(mut self, serial_number: u32) -> Self {
528 self.serial_number = Some(serial_number);
529 self
530 }
531
532 pub(crate) const fn product(mut self, product: u16) -> Self {
533 self.product = Some(product);
534 self
535 }
536
537 pub(crate) const fn software_version(mut self, hundredths: u16) -> Self {
539 self.software_version = Some(hundredths);
540 self
541 }
542
543 pub(crate) const fn product_name(mut self, name: &'a str) -> Self {
545 self.product_name = name;
546 self
547 }
548}
549
550impl Message for DeviceInfo<'_> {
551 const GLOBAL: u16 = 23;
552 #[allow(clippy::cast_possible_truncation)]
553 const FIELDS: &'static [FieldDef] = &[
554 field(TIMESTAMP, 4, base::UINT32),
555 field(0, 1, base::UINT8), field(2, 2, base::UINT16), field(3, 4, base::UINT32Z), field(4, 2, base::UINT16), field(5, 2, base::UINT16), field(27, PRODUCT_NAME_MAX as u8 + 1, base::STRING), ];
562
563 fn timestamp(&self) -> Option<Timestamp> {
564 Some(self.timestamp)
565 }
566
567 fn encode(&self, out: &mut dyn FieldOut, _: u16) {
568 out.u32(self.timestamp.fit());
569 out.u8(self.device_index);
570 out.opt_u16(self.manufacturer.map(Manufacturer::get));
571 out.opt_u32(self.serial_number);
572 out.opt_u16(self.product);
573 out.opt_u16(self.software_version);
574 out.str(self.product_name);
575 }
576}
577
578pub(crate) mod event {
580 pub const TIMER: u8 = 0;
581 pub const SESSION: u8 = 8;
582 pub const LAP: u8 = 9;
583 pub const LENGTH: u8 = 28;
584 pub const ACTIVITY: u8 = 26;
585 pub const START: u8 = 0;
586 pub const STOP: u8 = 1;
587 pub const STOP_ALL: u8 = 4;
588}
589
590#[derive(Clone, Copy, Debug, PartialEq, Eq)]
592#[allow(clippy::struct_field_names)]
593pub(crate) struct Event {
594 timestamp: Timestamp,
595 event: u8,
596 event_type: u8,
597}
598
599impl Event {
600 #[must_use]
602 pub const fn timer_start(timestamp: Timestamp) -> Self {
603 Self { timestamp, event: event::TIMER, event_type: event::START }
604 }
605
606 #[must_use]
608 pub const fn timer_stop(timestamp: Timestamp) -> Self {
609 Self { timestamp, event: event::TIMER, event_type: event::STOP }
610 }
611
612 #[must_use]
614 pub const fn timer_stop_all(timestamp: Timestamp) -> Self {
615 Self { timestamp, event: event::TIMER, event_type: event::STOP_ALL }
616 }
617}
618
619impl Message for Event {
620 const GLOBAL: u16 = 21;
621 const FIELDS: &'static [FieldDef] = &[
622 field(TIMESTAMP, 4, base::UINT32),
623 field(0, 1, base::ENUM), field(1, 1, base::ENUM), ];
626
627 fn timestamp(&self) -> Option<Timestamp> {
628 Some(self.timestamp)
629 }
630
631 fn encode(&self, out: &mut dyn FieldOut, _: u16) {
632 out.u32(self.timestamp.fit());
633 out.u8(self.event);
634 out.u8(self.event_type);
635 }
636}
637
638#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
640pub(crate) struct RecordFields(pub(crate) u32);
641
642impl RecordFields {
643 pub(crate) const POSITION: Self = Self(1);
644 pub(crate) const ALTITUDE: Self = Self(1 << 1);
645 pub(crate) const HEART_RATE: Self = Self(1 << 2);
646 pub(crate) const CADENCE: Self = Self(1 << 3);
647 pub(crate) const DISTANCE: Self = Self(1 << 4);
648 pub(crate) const SPEED: Self = Self(1 << 5);
649 pub(crate) const POWER: Self = Self(1 << 6);
650 pub(crate) const TEMPERATURE: Self = Self(1 << 7);
651
652 pub(crate) const fn contains(self, other: Self) -> bool {
653 self.0 & other.0 == other.0
654 }
655}
656const RECORD_FIELDS: [(RecordFields, FieldDef); 9] = [
658 (RecordFields::POSITION, field(0, 4, base::SINT32)), (RecordFields::POSITION, field(1, 4, base::SINT32)), (RecordFields::ALTITUDE, field(2, 2, base::UINT16)), (RecordFields::HEART_RATE, field(3, 1, base::UINT8)),
662 (RecordFields::CADENCE, field(4, 1, base::UINT8)),
663 (RecordFields::DISTANCE, field(5, 4, base::UINT32)), (RecordFields::SPEED, field(6, 2, base::UINT16)), (RecordFields::POWER, field(7, 2, base::UINT16)),
666 (RecordFields::TEMPERATURE, field(13, 1, base::SINT8)),
667];
668
669pub(crate) const RECORD_GLOBAL: u16 = 20;
670pub(crate) const RECORD_TIMESTAMP: FieldDef = field(TIMESTAMP, 4, base::UINT32);
671
672pub(crate) fn record_owns(num: u8) -> bool {
675 num == TIMESTAMP
676 || [8, 73, 78].contains(&num)
677 || RECORD_FIELDS.iter().any(|(_, f)| f.num == num)
678}
679
680pub(crate) fn record_fields(layout: RecordFields) -> impl Iterator<Item = FieldDef> + Clone {
682 RECORD_FIELDS.into_iter().filter(move |(bit, _)| layout.contains(*bit)).map(|(_, f)| f)
683}
684
685#[derive(Clone, Copy, Debug, PartialEq, Eq)]
696pub struct Record {
697 pub(crate) timestamp: Timestamp,
698 pub(crate) position: Option<Position>,
699 pub(crate) altitude: Option<Altitude>,
700 pub(crate) heart_rate: Option<u8>,
701 pub(crate) cadence: Option<u8>,
702 pub(crate) distance_input: Option<Distance>,
703 pub(crate) distance: Option<u32>,
705 pub(crate) speed: Option<u16>,
706 pub(crate) power: Option<u16>,
707 pub(crate) temperature: Option<i8>,
708}
709
710#[derive(Clone, Copy, Debug, PartialEq, Eq)]
713pub(crate) enum Distance {
714 Advanced(u64),
715 Total(u32),
716}
717
718pub(crate) const SMOOTHING: u8 = 5;
720
721#[derive(Clone, Copy, Debug, PartialEq, Eq)]
731pub struct Altitude {
732 pub(crate) fifths: u16,
734 pub(crate) threshold: u16,
736 pub(crate) window: u8,
738}
739
740impl Altitude {
741 #[must_use]
744 pub fn barometric_meters(meters: f64) -> Self {
745 Self::meters_with_threshold(meters, 2.0)
746 }
747
748 #[must_use]
751 pub fn gnss_meters(meters: f64) -> Self {
752 Self::meters_with_threshold(meters, 10.0)
753 }
754
755 #[must_use]
757 pub fn smoothed_meters(meters: f64) -> Self {
758 Self { window: 1, ..Self::meters_with_threshold(meters, 0.0) }
759 }
760
761 #[must_use]
765 pub fn meters_with_threshold(meters: f64, threshold: f64) -> Self {
766 let none = u32::from(u16::MAX);
767 let fifths = u16::try_from(scaled(meters + 500.0, 5.0, none)).unwrap_or(u16::MAX);
768 let threshold = u16::try_from(scaled(threshold, 5.0, none)).unwrap_or(u16::MAX);
769 let fifths = if threshold == u16::MAX { u16::MAX } else { fifths };
771 Self { fifths, threshold: threshold.max(1), window: SMOOTHING }
772 }
773}
774
775fn scaled(x: f64, scale: f64, none: u32) -> u32 {
778 half_up(x * scale).map_or(none, |v| u32::try_from(v).unwrap_or(none).min(none))
779}
780
781impl Record {
782 #[must_use]
784 pub const fn new(timestamp: Timestamp) -> Self {
785 Self {
786 timestamp,
787 position: None,
788 altitude: None,
789 heart_rate: None,
790 cadence: None,
791 distance_input: None,
792 distance: None,
793 speed: None,
794 power: None,
795 temperature: None,
796 }
797 }
798
799 #[must_use]
801 pub const fn position(mut self, position: Position) -> Self {
802 self.position = Some(position);
803 self
804 }
805
806 #[must_use]
808 pub const fn altitude(mut self, altitude: Altitude) -> Self {
809 self.altitude = Some(altitude);
810 self
811 }
812
813 #[must_use]
815 pub const fn heart_rate(mut self, bpm: u8) -> Self {
816 self.heart_rate = Some(bpm);
817 self
818 }
819
820 #[must_use]
822 pub const fn cadence_rpm(mut self, rpm: u8) -> Self {
823 self.cadence = Some(rpm);
824 self
825 }
826
827 #[must_use]
831 pub fn distance_advanced_meters(mut self, meters: f64) -> Self {
832 let um = half_up(meters * 1e6).unwrap_or(u64::MAX);
834 self.distance_input = Some(Distance::Advanced(um));
835 self
836 }
837
838 #[must_use]
842 pub fn distance_meters(mut self, meters: f64) -> Self {
843 self.distance_input = Some(Distance::Total(scaled(meters, 100.0, u32::MAX)));
844 self
845 }
846
847 #[must_use]
849 pub fn speed_meters_per_second(mut self, speed: f64) -> Self {
850 let raw = scaled(speed, 1000.0, u32::from(u16::MAX));
851 self.speed = Some(u16::try_from(raw).unwrap_or(u16::MAX));
852 self
853 }
854
855 #[must_use]
857 pub const fn power_watts(mut self, watts: u16) -> Self {
858 self.power = Some(watts);
859 self
860 }
861
862 #[must_use]
864 pub const fn temperature_celsius(mut self, celsius: i8) -> Self {
865 self.temperature = Some(celsius);
866 self
867 }
868
869 pub(crate) fn fields(self) -> RecordFields {
871 let bits = [
872 (self.position.is_some(), RecordFields::POSITION),
873 (self.altitude.is_some(), RecordFields::ALTITUDE),
874 (self.heart_rate.is_some(), RecordFields::HEART_RATE),
875 (self.cadence.is_some(), RecordFields::CADENCE),
876 (self.distance.is_some(), RecordFields::DISTANCE),
877 (self.speed.is_some(), RecordFields::SPEED),
878 (self.power.is_some(), RecordFields::POWER),
879 (self.temperature.is_some(), RecordFields::TEMPERATURE),
880 ];
881 RecordFields(bits.iter().filter(|(set, _)| *set).map(|(_, bit)| bit.0).sum())
882 }
883
884 pub(crate) fn encode(self, out: &mut dyn FieldOut) {
886 if self.position.is_some() {
887 out.position(self.position);
888 }
889 if let Some(v) = self.altitude.map(|a| a.fifths) {
890 out.u16(v);
891 }
892 if let Some(v) = self.heart_rate {
893 out.u8(v);
894 }
895 if let Some(v) = self.cadence {
896 out.u8(v);
897 }
898 if let Some(v) = self.distance {
899 out.u32(v);
900 }
901 if let Some(v) = self.speed {
902 out.u16(v);
903 }
904 if let Some(v) = self.power {
905 out.u16(v);
906 }
907 if let Some(v) = self.temperature {
908 out.i8(v);
909 }
910 }
911}
912
913#[derive(Clone, Copy, Debug, PartialEq, Eq)]
915pub(crate) struct Span {
916 pub start_time: Timestamp,
917 pub timestamp: Timestamp,
918 pub total_elapsed_ms: u32,
919 pub total_timer_ms: u32,
920}
921
922#[derive(Clone, Copy, Debug, PartialEq, Eq)]
924struct Summary {
925 avg_heart_rate: Option<u8>,
926 max_heart_rate: Option<u8>,
927 sport: Option<Sport>,
928 sub_sport: Option<SubSport>,
929}
930
931impl Summary {
932 const NONE: Self =
933 Self { avg_heart_rate: None, max_heart_rate: None, sport: None, sub_sport: None };
934}
935
936#[derive(Clone, Copy, Debug, PartialEq, Eq)]
938pub(crate) struct Totals {
939 pub start: Option<Position>,
940 pub end: Option<Position>,
941 pub north_east: Option<Position>,
942 pub south_west: Option<Position>,
943 pub distance: Option<u32>,
944 pub avg_speed: Option<u16>,
945 pub max_speed: Option<u16>,
946 pub avg_cadence: Option<u8>,
947 pub max_cadence: Option<u8>,
948 pub avg_power: Option<u16>,
949 pub max_power: Option<u16>,
950 pub ascent: Option<u16>,
952 pub descent: Option<u16>,
953 pub avg_temperature: Option<i8>,
954 pub max_temperature: Option<i8>,
955 pub cycles: Option<u32>,
957 pub lengths: Option<u16>,
958 pub active_lengths: Option<u16>,
959 pub stroke_distance: Option<u16>,
961 pub swim_stroke: Option<SwimStroke>,
962}
963
964impl Totals {
965 pub(crate) const NONE: Self = Self {
966 start: None,
967 end: None,
968 north_east: None,
969 south_west: None,
970 distance: None,
971 avg_speed: None,
972 max_speed: None,
973 avg_cadence: None,
974 max_cadence: None,
975 avg_power: None,
976 max_power: None,
977 ascent: None,
978 descent: None,
979 avg_temperature: None,
980 max_temperature: None,
981 cycles: None,
982 lengths: None,
983 active_lengths: None,
984 stroke_distance: None,
985 swim_stroke: None,
986 };
987
988 fn encode(&self, out: &mut dyn FieldOut) {
990 out.position(self.start);
991 out.position(self.end);
992 out.opt_u32(self.distance);
993 out.opt_u16(self.avg_speed);
994 out.opt_u16(self.max_speed);
995 out.opt_u8(self.avg_cadence);
996 out.opt_u8(self.max_cadence);
997 out.opt_u16(self.avg_power);
998 out.opt_u16(self.max_power);
999 out.opt_u16(self.ascent);
1000 out.opt_u16(self.descent);
1001 out.position(self.north_east);
1002 out.position(self.south_west);
1003 out.opt_i8(self.avg_temperature);
1004 out.opt_i8(self.max_temperature);
1005 out.opt_u32(self.cycles);
1006 out.opt_u16(self.lengths);
1007 out.opt_u16(self.active_lengths);
1008 out.opt_u16(self.stroke_distance);
1009 out.opt_u8(self.swim_stroke.map(SwimStroke::get));
1010 }
1011}
1012
1013macro_rules! with_totals {
1016 (
1017 [$($head:expr),* $(,)?],
1018 $start_lat:literal, $start_long:literal, $end_lat:literal, $end_long:literal,
1019 $distance:literal, $avg_speed:literal, $max_speed:literal, $avg_cadence:literal,
1020 $max_cadence:literal, $avg_power:literal, $max_power:literal, $ascent:literal,
1021 $descent:literal, $nec_lat:literal, $nec_long:literal, $swc_lat:literal,
1022 $swc_long:literal, $avg_temperature:literal, $max_temperature:literal,
1023 $cycles:literal, $lengths:literal, $active_lengths:literal, $stroke_distance:literal,
1024 $swim_stroke:literal, [$($tail:expr),* $(,)?]
1025 ) => {
1026 &[
1027 $($head,)*
1028 field($start_lat, 4, base::SINT32),
1029 field($start_long, 4, base::SINT32),
1030 field($end_lat, 4, base::SINT32),
1031 field($end_long, 4, base::SINT32),
1032 field($distance, 4, base::UINT32), field($avg_speed, 2, base::UINT16), field($max_speed, 2, base::UINT16), field($avg_cadence, 1, base::UINT8),
1036 field($max_cadence, 1, base::UINT8),
1037 field($avg_power, 2, base::UINT16),
1038 field($max_power, 2, base::UINT16),
1039 field($ascent, 2, base::UINT16),
1040 field($descent, 2, base::UINT16),
1041 field($nec_lat, 4, base::SINT32),
1042 field($nec_long, 4, base::SINT32),
1043 field($swc_lat, 4, base::SINT32),
1044 field($swc_long, 4, base::SINT32),
1045 field($avg_temperature, 1, base::SINT8),
1046 field($max_temperature, 1, base::SINT8),
1047 field($cycles, 4, base::UINT32),
1048 field($lengths, 2, base::UINT16),
1049 field($active_lengths, 2, base::UINT16),
1050 field($stroke_distance, 2, base::UINT16), field($swim_stroke, 1, base::ENUM),
1052 $($tail,)*
1053 ]
1054 };
1055}
1056
1057#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1059pub(crate) struct Lap {
1060 span: Span,
1061 summary: Summary,
1062 totals: Totals,
1063 first_length_index: Option<u16>,
1064 trigger: u8,
1065}
1066
1067impl Lap {
1068 #[must_use]
1071 pub const fn new(
1072 start_time: Timestamp,
1073 timestamp: Timestamp,
1074 total_elapsed_ms: u32,
1075 total_timer_ms: u32,
1076 ) -> Self {
1077 Self {
1078 span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
1079 summary: Summary::NONE,
1080 totals: Totals::NONE,
1081 first_length_index: None,
1082 trigger: lap_trigger::MANUAL,
1083 }
1084 }
1085
1086 #[must_use]
1088 pub const fn trigger(mut self, trigger: u8) -> Self {
1089 self.trigger = trigger;
1090 self
1091 }
1092
1093 #[must_use]
1095 pub const fn first_length(mut self, index: u16) -> Self {
1096 self.first_length_index = Some(index);
1097 self
1098 }
1099
1100 #[must_use]
1101 pub const fn totals(mut self, totals: Totals) -> Self {
1102 self.totals = totals;
1103 self
1104 }
1105
1106 #[must_use]
1108 pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
1109 self.summary.avg_heart_rate = Some(avg);
1110 self.summary.max_heart_rate = Some(max);
1111 self
1112 }
1113
1114 #[must_use]
1116 pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
1117 self.summary.sport = Some(sport);
1118 self.summary.sub_sport = Some(sub_sport);
1119 self
1120 }
1121}
1122
1123impl Message for Lap {
1124 const GLOBAL: u16 = 19;
1125 const FIELDS: &'static [FieldDef] = with_totals!(
1126 [
1127 field(MESSAGE_INDEX, 2, base::UINT16),
1128 field(TIMESTAMP, 4, base::UINT32),
1129 field(0, 1, base::ENUM), field(1, 1, base::ENUM), field(2, 4, base::UINT32), field(7, 4, base::UINT32), field(8, 4, base::UINT32), field(15, 1, base::UINT8), field(16, 1, base::UINT8), field(25, 1, base::ENUM), field(39, 1, base::ENUM), field(24, 1, base::ENUM), ],
1140 3,
1141 4,
1142 5,
1143 6,
1144 9,
1145 13,
1146 14,
1147 17,
1148 18,
1149 19,
1150 20,
1151 21,
1152 22,
1153 27,
1154 28,
1155 29,
1156 30,
1157 50,
1158 51,
1159 10,
1160 32,
1161 40,
1162 37,
1163 38,
1164 [field(35, 2, base::UINT16)] );
1166
1167 fn timestamp(&self) -> Option<Timestamp> {
1168 Some(self.span.timestamp)
1169 }
1170
1171 fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1172 let (span, summary) = (&self.span, &self.summary);
1173 out.u16(index);
1174 out.u32(span.timestamp.fit());
1175 out.u8(event::LAP);
1176 out.u8(event::STOP);
1177 out.u32(span.start_time.fit());
1178 out.u32(span.total_elapsed_ms);
1179 out.u32(span.total_timer_ms);
1180 out.opt_u8(summary.avg_heart_rate);
1181 out.opt_u8(summary.max_heart_rate);
1182 out.opt_u8(summary.sport.map(Sport::get));
1183 out.opt_u8(summary.sub_sport.map(SubSport::get));
1184 out.u8(self.trigger);
1185 self.totals.encode(out);
1186 out.opt_u16(self.first_length_index);
1187 }
1188}
1189
1190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1192pub(crate) struct Session {
1193 span: Span,
1194 summary: Summary,
1195 totals: Totals,
1196 first_lap_index: u16,
1197 num_laps: u16,
1198 pool: Option<Pool>,
1199 trigger: u8,
1200}
1201
1202impl Session {
1203 #[must_use]
1207 pub const fn new(
1208 start_time: Timestamp,
1209 timestamp: Timestamp,
1210 total_elapsed_ms: u32,
1211 total_timer_ms: u32,
1212 ) -> Self {
1213 Self {
1214 span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
1215 summary: Summary::NONE,
1216 totals: Totals::NONE,
1217 first_lap_index: 0,
1218 num_laps: 1,
1219 pool: None,
1220 trigger: trigger::ACTIVITY_END,
1221 }
1222 }
1223
1224 #[must_use]
1226 pub const fn trigger(mut self, trigger: u8) -> Self {
1227 self.trigger = trigger;
1228 self
1229 }
1230
1231 #[must_use]
1233 pub const fn pool(mut self, pool: Pool) -> Self {
1234 self.pool = Some(pool);
1235 self
1236 }
1237
1238 #[must_use]
1239 pub const fn totals(mut self, totals: Totals) -> Self {
1240 self.totals = totals;
1241 self
1242 }
1243
1244 #[must_use]
1246 pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
1247 self.summary.avg_heart_rate = Some(avg);
1248 self.summary.max_heart_rate = Some(max);
1249 self
1250 }
1251
1252 #[must_use]
1254 pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
1255 self.summary.sport = Some(sport);
1256 self.summary.sub_sport = Some(sub_sport);
1257 self
1258 }
1259
1260 #[must_use]
1262 pub const fn laps(mut self, first: u16, count: u16) -> Self {
1263 self.first_lap_index = first;
1264 self.num_laps = count;
1265 self
1266 }
1267}
1268
1269impl Message for Session {
1270 const GLOBAL: u16 = 18;
1271 const FIELDS: &'static [FieldDef] = with_totals!(
1272 [
1273 field(MESSAGE_INDEX, 2, base::UINT16),
1274 field(TIMESTAMP, 4, base::UINT32),
1275 field(0, 1, base::ENUM), field(1, 1, base::ENUM), field(2, 4, base::UINT32), field(5, 1, base::ENUM), field(6, 1, base::ENUM), field(7, 4, base::UINT32), field(8, 4, base::UINT32), field(16, 1, base::UINT8), field(17, 1, base::UINT8), field(25, 2, base::UINT16), field(26, 2, base::UINT16), ],
1287 3,
1288 4,
1289 38,
1290 39,
1291 9,
1292 14,
1293 15,
1294 18,
1295 19,
1296 20,
1297 21,
1298 22,
1299 23,
1300 29,
1301 30,
1302 31,
1303 32,
1304 57,
1305 58,
1306 10,
1307 33,
1308 47,
1309 42,
1310 43,
1311 [
1312 field(44, 2, base::UINT16), field(46, 1, base::ENUM), field(28, 1, base::ENUM), ]
1316 );
1317
1318 fn timestamp(&self) -> Option<Timestamp> {
1319 Some(self.span.timestamp)
1320 }
1321
1322 fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1323 let (span, summary) = (&self.span, &self.summary);
1324 out.u16(index);
1325 out.u32(span.timestamp.fit());
1326 out.u8(event::SESSION);
1327 out.u8(event::STOP);
1328 out.u32(span.start_time.fit());
1329 out.opt_u8(summary.sport.map(Sport::get));
1330 out.opt_u8(summary.sub_sport.map(SubSport::get));
1331 out.u32(span.total_elapsed_ms);
1332 out.u32(span.total_timer_ms);
1333 out.opt_u8(summary.avg_heart_rate);
1334 out.opt_u8(summary.max_heart_rate);
1335 out.u16(self.first_lap_index);
1336 out.u16(self.num_laps);
1337 self.totals.encode(out);
1338 out.opt_u16(self.pool.map(|p| p.centimetres));
1339 out.opt_u8(self.pool.map(|p| p.unit));
1340 out.u8(self.trigger);
1341 }
1342}
1343
1344pub(crate) mod lap_trigger {
1346 pub const MANUAL: u8 = 0;
1347 pub const SESSION_END: u8 = 7;
1348}
1349
1350#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1353#[non_exhaustive]
1354pub enum LapTrigger {
1355 Manual,
1357 Time,
1359 Distance,
1361 PositionStart,
1363 PositionLap,
1365 PositionWaypoint,
1367 PositionMarked,
1369 FitnessEquipment,
1371}
1372
1373impl LapTrigger {
1374 pub(crate) const fn get(self) -> u8 {
1376 match self {
1377 Self::Manual => lap_trigger::MANUAL,
1378 Self::Time => 1,
1379 Self::Distance => 2,
1380 Self::PositionStart => 3,
1381 Self::PositionLap => 4,
1382 Self::PositionWaypoint => 5,
1383 Self::PositionMarked => 6,
1384 Self::FitnessEquipment => 8,
1385 }
1386 }
1387
1388 #[must_use]
1390 pub const fn name(self) -> &'static str {
1391 match self {
1392 Self::Manual => "manual",
1393 Self::Time => "time",
1394 Self::Distance => "distance",
1395 Self::PositionStart => "position_start",
1396 Self::PositionLap => "position_lap",
1397 Self::PositionWaypoint => "position_waypoint",
1398 Self::PositionMarked => "position_marked",
1399 Self::FitnessEquipment => "fitness_equipment",
1400 }
1401 }
1402}
1403
1404impl core::fmt::Display for LapTrigger {
1405 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1406 f.write_str(self.name())
1407 }
1408}
1409
1410pub(crate) mod trigger {
1412 pub const ACTIVITY_END: u8 = 0;
1413 pub const MANUAL: u8 = 1;
1414 pub const AUTO_MULTI_SPORT: u8 = 2;
1415}
1416
1417pub const SPORT_NAME_MAX: usize = 23;
1419
1420#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1422pub(crate) struct SportMsg<'a> {
1423 pub sport: Sport,
1424 pub sub_sport: SubSport,
1425 pub name: &'a str,
1426}
1427
1428impl Message for SportMsg<'_> {
1429 const GLOBAL: u16 = 12;
1430 #[allow(clippy::cast_possible_truncation, reason = "a short name")]
1431 const FIELDS: &'static [FieldDef] = &[
1432 field(0, 1, base::ENUM), field(1, 1, base::ENUM), field(3, SPORT_NAME_MAX as u8 + 1, base::STRING), ];
1436
1437 fn timestamp(&self) -> Option<Timestamp> {
1438 None
1439 }
1440
1441 fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1442 out.u8(self.sport.get());
1443 out.u8(self.sub_sport.get());
1444 out.str(self.name);
1445 }
1446}
1447
1448#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1459pub struct Leg<'a> {
1460 pub(crate) sport: SportMsg<'a>,
1461 pub(crate) pool: Option<Pool>,
1462 pub(crate) by_hand: bool,
1463}
1464
1465impl<'a> Leg<'a> {
1466 #[must_use]
1468 pub const fn new(sport: Sport, sub_sport: SubSport) -> Self {
1469 Self { sport: SportMsg { sport, sub_sport, name: "" }, pool: None, by_hand: false }
1470 }
1471
1472 #[must_use]
1474 pub const fn pool_swim(pool: Pool) -> Self {
1475 let sport =
1476 SportMsg { sport: Sport::SWIMMING, sub_sport: SubSport::LAP_SWIMMING, name: "" };
1477 Self { sport, pool: Some(pool), by_hand: false }
1478 }
1479
1480 #[must_use]
1483 pub const fn named(mut self, name: &'a str) -> Self {
1484 self.sport.name = name;
1485 self
1486 }
1487
1488 #[must_use]
1492 pub const fn by_hand(mut self) -> Self {
1493 self.by_hand = true;
1494 self
1495 }
1496}
1497
1498#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1507pub struct Pool {
1508 pub(crate) centimetres: u16,
1510 pub(crate) unit: u8,
1512}
1513
1514impl Pool {
1515 #[must_use]
1517 pub fn meters(meters: f64) -> Self {
1518 Self::of(meters, 0)
1519 }
1520
1521 #[must_use]
1524 pub fn yards(yards: f64) -> Self {
1525 Self::of(yards * 0.9144, 1)
1526 }
1527
1528 fn of(meters: f64, unit: u8) -> Self {
1529 let cm = scaled(meters, 100.0, u32::from(u16::MAX));
1530 Self { centimetres: u16::try_from(cm).unwrap_or(u16::MAX), unit }
1531 }
1532}
1533
1534#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1543pub struct Length {
1544 pub(crate) stroke: SwimStroke,
1545 pub(crate) strokes: Option<u16>,
1546}
1547
1548impl Length {
1549 #[must_use]
1552 pub const fn swum(stroke: SwimStroke, strokes: u16) -> Self {
1553 if stroke.get() == SwimStroke::DRILL.get() {
1554 return Self::drill();
1555 }
1556 Self { stroke, strokes: Some(strokes) }
1557 }
1558
1559 #[must_use]
1561 pub const fn drill() -> Self {
1562 Self { stroke: SwimStroke::DRILL, strokes: None }
1563 }
1564}
1565
1566#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1577pub struct Exercise {
1578 pub(crate) category: ExerciseCategory,
1579 pub(crate) name: Option<u16>,
1580}
1581
1582impl Exercise {
1583 #[must_use]
1585 pub const fn new(category: ExerciseCategory) -> Self {
1586 Self { category, name: None }
1587 }
1588
1589 #[must_use]
1591 pub const fn name(mut self, name: u16) -> Self {
1592 self.name = Some(name);
1593 self
1594 }
1595}
1596
1597#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1609pub struct Set {
1610 pub(crate) exercise: Option<Exercise>,
1611 pub(crate) repetitions: Option<u16>,
1612 pub(crate) weight: Option<u16>,
1614 pub(crate) weight_unit: Option<u16>,
1616}
1617
1618impl Set {
1619 #[must_use]
1621 pub const fn new() -> Self {
1622 Self { exercise: None, repetitions: None, weight: None, weight_unit: None }
1623 }
1624
1625 #[must_use]
1627 pub const fn exercise(mut self, exercise: Exercise) -> Self {
1628 self.exercise = Some(exercise);
1629 self
1630 }
1631
1632 #[must_use]
1634 pub const fn repetitions(mut self, repetitions: u16) -> Self {
1635 self.repetitions = Some(repetitions);
1636 self
1637 }
1638
1639 #[must_use]
1642 pub fn weight_kilograms(self, kilograms: f64) -> Self {
1643 self.weight(kilograms, KILOGRAM)
1644 }
1645
1646 #[must_use]
1649 pub fn weight_pounds(self, pounds: f64) -> Self {
1650 self.weight(pounds * 0.453_592_37, POUND)
1651 }
1652
1653 fn weight(mut self, kilograms: f64, unit: u16) -> Self {
1654 let raw = scaled(kilograms, 16.0, u32::from(u16::MAX));
1655 self.weight = Some(u16::try_from(raw).unwrap_or(u16::MAX));
1656 self.weight_unit = Some(unit);
1657 self
1658 }
1659}
1660
1661const KILOGRAM: u16 = 1;
1663const POUND: u16 = 2;
1664
1665#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1667pub(crate) struct LengthMsg {
1668 pub span: Span,
1669 pub swum: Option<Length>,
1671 pub avg_speed: Option<u16>,
1672 pub cadence: Option<u8>,
1673}
1674
1675impl LengthMsg {
1676 pub const SWUM: &'static [u8] = &[5, 6, 7, 9];
1678}
1679
1680impl Message for LengthMsg {
1681 const GLOBAL: u16 = 101;
1682 const FIELDS: &'static [FieldDef] = &[
1683 field(MESSAGE_INDEX, 2, base::UINT16),
1684 field(TIMESTAMP, 4, base::UINT32),
1685 field(0, 1, base::ENUM), field(1, 1, base::ENUM), field(2, 4, base::UINT32), field(3, 4, base::UINT32), field(4, 4, base::UINT32), field(5, 2, base::UINT16), field(6, 2, base::UINT16), field(7, 1, base::ENUM), field(9, 1, base::UINT8), field(12, 1, base::ENUM), ];
1696
1697 fn timestamp(&self) -> Option<Timestamp> {
1698 Some(self.span.timestamp)
1699 }
1700
1701 fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1702 const IDLE: u8 = 0;
1703 const ACTIVE: u8 = 1;
1704 let span = &self.span;
1705 out.u16(index);
1706 out.u32(span.timestamp.fit());
1707 out.u8(event::LENGTH);
1708 out.u8(event::STOP);
1709 out.u32(span.start_time.fit());
1710 out.u32(span.total_elapsed_ms);
1711 out.u32(span.total_timer_ms);
1712 out.opt_u16(self.swum.and_then(|l| l.strokes));
1713 out.opt_u16(self.avg_speed);
1714 out.opt_u8(self.swum.map(|l| l.stroke.get()));
1715 out.opt_u8(self.cadence);
1716 out.u8(if self.swum.is_some() { ACTIVE } else { IDLE });
1717 }
1718}
1719
1720#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1722pub(crate) struct SetMsg {
1723 pub start_time: Timestamp,
1724 pub timestamp: Timestamp,
1725 pub duration_ms: u32,
1726 pub set: Option<Set>,
1728}
1729
1730impl SetMsg {
1731 pub const ACTIVE: &'static [u8] = &[3, 4, 7, 8, 9];
1733}
1734
1735impl Message for SetMsg {
1736 const GLOBAL: u16 = 225;
1737 const FIELDS: &'static [FieldDef] = &[
1738 field(254, 4, base::UINT32), field(0, 4, base::UINT32), field(3, 2, base::UINT16), field(4, 2, base::UINT16), field(5, 1, base::UINT8), field(6, 4, base::UINT32), field(7, 2, base::UINT16), field(8, 2, base::UINT16), field(9, 2, base::UINT16), field(10, 2, base::UINT16), ];
1749
1750 fn timestamp(&self) -> Option<Timestamp> {
1751 None
1752 }
1753
1754 fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1755 const REST: u8 = 0;
1756 const ACTIVE: u8 = 1;
1757 let set = self.set.unwrap_or_default();
1758 let exercise = set.exercise;
1759 out.u32(self.timestamp.fit());
1760 out.u32(self.duration_ms);
1761 out.opt_u16(set.repetitions);
1762 out.opt_u16(set.weight);
1763 out.u8(if self.set.is_some() { ACTIVE } else { REST });
1764 out.u32(self.start_time.fit());
1765 out.u16s(exercise.as_ref().map(|e| e.category.get()).as_slice());
1766 out.u16s(exercise.and_then(|e| e.name).as_slice());
1767 out.opt_u16(set.weight_unit);
1768 out.u16(index);
1769 }
1770}
1771
1772pub(crate) const HRV_BEATS: usize = 5;
1774
1775#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1777pub(crate) struct Hrv<'a>(pub &'a [u16]);
1778
1779impl Message for Hrv<'_> {
1780 const GLOBAL: u16 = 78;
1781 #[allow(clippy::cast_possible_truncation, reason = "five two-byte values")]
1782 const FIELDS: &'static [FieldDef] = &[field(0, HRV_BEATS as u8 * 2, base::UINT16)]; fn timestamp(&self) -> Option<Timestamp> {
1785 None
1786 }
1787
1788 fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1789 out.u16s(self.0);
1790 }
1791}
1792
1793#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1795pub(crate) struct Activity {
1796 timestamp: Timestamp,
1797 total_timer_ms: u32,
1798 num_sessions: u16,
1799 utc_offset: Option<i32>,
1800 auto_multisport: bool,
1801}
1802
1803impl Activity {
1804 #[must_use]
1806 pub const fn new(timestamp: Timestamp, total_timer_ms: u32) -> Self {
1807 Self {
1808 timestamp,
1809 total_timer_ms,
1810 num_sessions: 1,
1811 utc_offset: None,
1812 auto_multisport: false,
1813 }
1814 }
1815
1816 #[must_use]
1819 pub const fn auto_multisport(mut self, auto: bool) -> Self {
1820 self.auto_multisport = auto;
1821 self
1822 }
1823
1824 #[must_use]
1826 pub const fn sessions(mut self, num_sessions: u16) -> Self {
1827 self.num_sessions = num_sessions;
1828 self
1829 }
1830
1831 #[must_use]
1834 pub const fn utc_offset(mut self, seconds: i32) -> Self {
1835 self.utc_offset = Some(seconds);
1836 self
1837 }
1838
1839 fn local_timestamp(&self) -> Option<u32> {
1841 let offset = self.utc_offset?;
1842 Some(self.timestamp.fit().checked_add_signed(offset).unwrap_or(INVALID_U32))
1843 }
1844}
1845
1846impl Message for Activity {
1847 const GLOBAL: u16 = 34;
1848 const FIELDS: &'static [FieldDef] = &[
1849 field(TIMESTAMP, 4, base::UINT32),
1850 field(0, 4, base::UINT32), field(1, 2, base::UINT16), field(2, 1, base::ENUM), field(3, 1, base::ENUM), field(4, 1, base::ENUM), field(5, 4, base::UINT32), ];
1857
1858 fn timestamp(&self) -> Option<Timestamp> {
1859 Some(self.timestamp)
1860 }
1861
1862 fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1863 const MANUAL: u8 = 0;
1864 const AUTO_MULTI_SPORT: u8 = 1;
1865 out.u32(self.timestamp.fit());
1866 out.u32(self.total_timer_ms);
1867 out.u16(self.num_sessions);
1868 out.u8(if self.auto_multisport { AUTO_MULTI_SPORT } else { MANUAL });
1869 out.u8(event::ACTIVITY);
1870 out.u8(event::STOP);
1871 out.opt_u32(self.local_timestamp());
1872 }
1873}
1874
1875#[cfg(test)]
1876mod tests {
1877 use super::*;
1878 use crate::types::{
1879 ExerciseCategory, FileType, Manufacturer, Sport, SubSport, SwimStroke, Timestamp,
1880 };
1881 use std::vec;
1882
1883 struct VecPut(std::vec::Vec<u8>);
1884
1885 impl Put for VecPut {
1886 fn put(&mut self, bytes: &[u8]) {
1887 self.0.extend_from_slice(bytes);
1888 }
1889 }
1890
1891 struct Count(usize);
1893
1894 impl FieldOut for Count {
1895 fn u8(&mut self, _: u8) {
1896 self.0 += 1;
1897 }
1898 fn u16(&mut self, _: u16) {
1899 self.0 += 1;
1900 }
1901 fn u32(&mut self, _: u32) {
1902 self.0 += 1;
1903 }
1904 fn i8(&mut self, _: i8) {
1905 self.0 += 1;
1906 }
1907 fn i32(&mut self, _: i32) {
1908 self.0 += 1;
1909 }
1910 fn str(&mut self, _: &str) {
1911 self.0 += 1;
1912 }
1913 fn u16s(&mut self, _: &[u16]) {
1914 self.0 += 1;
1915 }
1916 fn bytes(&mut self, _: &[u8]) {
1917 self.0 += 1;
1918 }
1919 fn none(&mut self) {
1920 self.0 += 1;
1921 }
1922 }
1923
1924 fn refused<M: Message>(msg: &M, index: u16) -> Option<FieldError> {
1925 let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
1926 msg.encode(&mut fields, index);
1927 fields.refused()
1928 }
1929
1930 fn bytes<M: Message>(msg: &M, index: u16) -> std::vec::Vec<u8> {
1931 let mut count = Count(0);
1932 msg.encode(&mut count, index);
1933 assert_eq!(count.0, M::FIELDS.len(), "{}: a value per field", M::GLOBAL);
1934 let mut out = VecPut(vec![]);
1935 let mut fields = Fields::new(M::FIELDS.iter().copied(), Some(&mut out));
1936 msg.encode(&mut fields, index);
1937 assert_eq!(fields.refused(), None);
1938 fields.finish();
1939 assert_eq!(u32::try_from(out.0.len()).unwrap(), data_len(M::FIELDS.iter().copied()));
1940 out.0
1941 }
1942
1943 const T: Timestamp = Timestamp::from_fit(0x1122_3344);
1944 const T2: Timestamp = Timestamp::from_fit(0x1122_3380);
1945
1946 #[rustfmt::skip]
1948 const NO_TOTALS: [u8; 63] = [
1949 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, ];
1963
1964 fn totals() -> Totals {
1965 let p = |lat, long| Position::from_semicircles(lat, long);
1966 Totals {
1967 start: p(1, -2),
1968 end: p(3, -4),
1969 north_east: p(5, -6),
1970 south_west: p(7, -8),
1971 distance: Some(0x0102_0304),
1972 avg_speed: Some(0x0506),
1973 max_speed: Some(0x0708),
1974 avg_cadence: Some(9),
1975 max_cadence: Some(10),
1976 avg_power: Some(0x0B0C),
1977 max_power: Some(0x0D0E),
1978 ascent: Some(0x0F10),
1979 descent: Some(0x1112),
1980 avg_temperature: Some(-13),
1981 max_temperature: Some(14),
1982 cycles: Some(0x1314_1516),
1983 lengths: Some(0x1718),
1984 active_lengths: Some(0x191A),
1985 stroke_distance: Some(0x1B1C),
1986 swim_stroke: Some(SwimStroke::new(0x1D)),
1987 }
1988 }
1989
1990 #[rustfmt::skip]
1991 const TOTALS: [u8; 63] = [
1992 1, 0, 0, 0, 0xFE, 0xFF, 0xFF, 0xFF,
1993 3, 0, 0, 0, 0xFC, 0xFF, 0xFF, 0xFF,
1994 0x04, 0x03, 0x02, 0x01,
1995 0x06, 0x05, 0x08, 0x07,
1996 9, 10,
1997 0x0C, 0x0B, 0x0E, 0x0D,
1998 0x10, 0x0F, 0x12, 0x11,
1999 5, 0, 0, 0, 0xFA, 0xFF, 0xFF, 0xFF,
2000 7, 0, 0, 0, 0xF8, 0xFF, 0xFF, 0xFF,
2001 0xF3, 14,
2002 0x16, 0x15, 0x14, 0x13,
2003 0x18, 0x17, 0x1A, 0x19,
2004 0x1C, 0x1B, 0x1D,
2005 ];
2006
2007 #[test]
2008 fn a_value_just_under_a_half_rounds_down() {
2009 let under = 0.499_999_999_999_999_94;
2010 assert_eq!(scaled(under, 1.0, 100), 0);
2011 assert_eq!(scaled(0.5, 1.0, 100), 1);
2012 }
2013
2014 #[test]
2015 fn file_id() {
2016 let id = FileId::new(FileType::ACTIVITY, Manufacturer::DEVELOPMENT, 0x0102, T)
2017 .serial_number(0xAABB_CCDD);
2018 assert_eq!(
2019 bytes(&id, 0),
2020 [4, 0xFF, 0x00, 0x02, 0x01, 0xDD, 0xCC, 0xBB, 0xAA, 0x44, 0x33, 0x22, 0x11]
2021 );
2022 let no_serial = FileId::new(FileType::new(9), Manufacturer::new(1), 2, T);
2023 assert_eq!(bytes(&no_serial, 0), [9, 1, 0, 2, 0, 0, 0, 0, 0, 0x44, 0x33, 0x22, 0x11]);
2024 assert_eq!(id.timestamp(), None);
2025 }
2026
2027 #[test]
2028 fn device_info() {
2029 let info = DeviceInfo::new(T)
2030 .device_index(2)
2031 .manufacturer(Manufacturer::new(0x0304))
2032 .serial_number(7)
2033 .product(0x0506)
2034 .software_version(123)
2035 .product_name("Watch");
2036 let mut want = vec![0x44, 0x33, 0x22, 0x11, 2, 0x04, 0x03, 7, 0, 0, 0, 0x06, 0x05, 123, 0];
2037 want.extend_from_slice(b"Watch");
2038 want.resize(want.len() + 15, 0);
2039 assert_eq!(bytes(&info, 0), want);
2040 assert_eq!(info.timestamp(), Some(T));
2041
2042 let mut empty =
2043 vec![0x44, 0x33, 0x22, 0x11, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF];
2044 empty.resize(empty.len() + 20, 0);
2045 assert_eq!(bytes(&DeviceInfo::new(T), 0), empty);
2046 }
2047
2048 #[test]
2049 fn product_name_limit() {
2050 let longest = "0123456789abcdefghi";
2051 assert_eq!(longest.len(), PRODUCT_NAME_MAX);
2052 let out = bytes(&DeviceInfo::new(T).product_name(longest), 0);
2053 assert_eq!(out.last(), Some(&0));
2054 let long = DeviceInfo::new(T).product_name("0123456789abcdefghij");
2055 assert_eq!(refused(&long, 0), Some(FieldError::StringTooLong));
2056 }
2057
2058 #[test]
2059 fn events() {
2060 let t = [0x44, 0x33, 0x22, 0x11];
2061 assert_eq!(bytes(&Event::timer_start(T), 0), [&t[..], &[0, 0]].concat());
2062 assert_eq!(bytes(&Event::timer_stop(T), 0), [&t[..], &[0, 1]].concat());
2063 assert_eq!(bytes(&Event::timer_stop_all(T), 0), [&t[..], &[0, 4]].concat());
2064 assert_eq!(Event::timer_start(T).timestamp(), Some(T));
2065 }
2066
2067 #[test]
2068 fn lap() {
2069 let lap = Lap::new(T, T2, 0x0001_0203, 0x0004_0506)
2070 .heart_rate(120, 150)
2071 .sport(Sport::RUNNING, SubSport::TREADMILL);
2072 let out = bytes(&lap, 0x0102);
2073 assert_eq!(
2074 out[..24],
2075 [
2076 0x02, 0x01, 0x80, 0x33, 0x22, 0x11, 9, 1, 0x44, 0x33, 0x22, 0x11, 0x03, 0x02, 0x01,
2077 0x00, 0x06, 0x05, 0x04, 0x00, 120, 150, 1, 1
2078 ]
2079 );
2080 assert_eq!(out[24], lap_trigger::MANUAL);
2081 assert_eq!(out[25..88], NO_TOTALS);
2082 assert_eq!(out[88..], [0xFF, 0xFF]);
2083 let ended = bytes(&lap.trigger(lap_trigger::SESSION_END), 0x0102);
2084 assert_eq!(ended[24], 7);
2085 let bare = bytes(&Lap::new(T, T2, 0, 0), 0);
2086 assert_eq!(bare.get(20..24), Some(&[0xFF; 4][..]));
2087 let full = bytes(&lap.totals(totals()).first_length(0x1E1F), 0x0102);
2088 assert_eq!((&full[25..88], &full[88..]), (&TOTALS[..], &[0x1F, 0x1E][..]));
2089 assert_eq!(lap.timestamp(), Some(T2));
2090 }
2091
2092 #[test]
2093 fn session() {
2094 let session = Session::new(T, T2, 0x0001_0203, 0x0004_0506)
2095 .heart_rate(121, 151)
2096 .sport(Sport::TRAINING, SubSport::CARDIO_TRAINING)
2097 .laps(3, 4);
2098 let out = bytes(&session, 5);
2099 assert_eq!(
2100 out[..28],
2101 [
2102 5, 0, 0x80, 0x33, 0x22, 0x11, 8, 1, 0x44, 0x33, 0x22, 0x11, 10, 26, 0x03, 0x02,
2103 0x01, 0x00, 0x06, 0x05, 0x04, 0x00, 121, 151, 3, 0, 4, 0
2104 ]
2105 );
2106 assert_eq!(out[28..91], NO_TOTALS);
2107 assert_eq!(out[91..], [0xFF, 0xFF, 0xFF, trigger::ACTIVITY_END]);
2108 let bare = bytes(&Session::new(T, T2, 0, 0), 0);
2109 assert_eq!(bare.get(12..14), Some(&[0xFF; 2][..]));
2110 assert_eq!(bare.get(22..28), Some(&[0xFF, 0xFF, 0, 0, 1, 0][..]));
2111 let full = session.totals(totals()).pool(Pool::yards(25.0)).trigger(trigger::MANUAL);
2112 let full = bytes(&full, 5);
2113 assert_eq!((&full[28..91], &full[91..]), (&TOTALS[..], &[0xEE, 0x08, 1, 1][..]));
2114 assert_eq!(session.timestamp(), Some(T2));
2115 }
2116
2117 #[test]
2118 fn activity() {
2119 let a = Activity::new(T2, 0x0004_0506).sessions(2).utc_offset(-0x80);
2120 assert_eq!(
2121 bytes(&a, 0),
2122 [
2123 0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00, 2, 0, 0, 26, 1, 0x00, 0x33, 0x22,
2124 0x11
2125 ]
2126 );
2127 let none = bytes(&Activity::new(T2, 0), 0);
2128 assert_eq!(none.get(8..11), Some(&[1, 0, 0][..]), "one session, manual");
2129 let auto = bytes(&Activity::new(T2, 0).auto_multisport(true), 0);
2130 assert_eq!(auto.get(10), Some(&1), "auto_multi_sport");
2131 assert_eq!(none.get(13..), Some(&[0xFF; 4][..]));
2132 assert_eq!(a.timestamp(), Some(T2));
2133 }
2134
2135 #[test]
2136 fn sports() {
2137 let named = SportMsg { sport: Sport::new(5), sub_sport: SubSport::new(18), name: "Swim" };
2138 let mut want = [0u8; 26];
2139 want[..6].copy_from_slice(&[5, 18, b'S', b'w', b'i', b'm']);
2140 assert_eq!(bytes(&named, 0), want);
2141 let unnamed = bytes(&SportMsg { name: "", ..named }, 0);
2142 assert_eq!(unnamed, [&[5, 18][..], &[0; 24]].concat(), "a string's none");
2143 let long = "a name of twenty-four by";
2144 assert_eq!(long.len(), SPORT_NAME_MAX + 1);
2145 assert_eq!(refused(&SportMsg { name: long, ..named }, 0), Some(FieldError::StringTooLong));
2146 assert_eq!(named.timestamp(), None);
2147 }
2148
2149 #[test]
2150 fn local_timestamp_out_of_range_is_refused() {
2151 let at = |t: u32, offset: i32| Activity::new(Timestamp::from_fit(t), 0).utc_offset(offset);
2152 assert_eq!(at(10, -11).local_timestamp(), Some(INVALID_U32));
2153 assert_eq!(at(10, -10).local_timestamp(), Some(0));
2154 assert_eq!(at(u32::MAX - 1, 1).local_timestamp(), Some(INVALID_U32));
2155 assert_eq!(at(u32::MAX - 2, 1).local_timestamp(), Some(u32::MAX - 1));
2156 assert_eq!(at(100, 3600).local_timestamp(), Some(3700));
2157 assert_eq!(Activity::new(T, 0).local_timestamp(), None);
2158 assert_eq!(refused(&at(10, -11), 0), Some(FieldError::OutOfRange));
2159 }
2160
2161 #[test]
2162 fn record_layouts() {
2163 assert_eq!(Record::new(T).heart_rate(99).fields(), RecordFields::HEART_RATE);
2164 assert_eq!(Record::new(T).fields(), RecordFields(0));
2165 assert_eq!(record_fields(RecordFields(0)).count(), 0);
2166 let mut all = Record::new(T)
2167 .position(Position::from_semicircles(1, 2).unwrap())
2168 .altitude(Altitude::smoothed_meters(0.0))
2169 .heart_rate(3)
2170 .cadence_rpm(4)
2171 .speed_meters_per_second(6.0)
2172 .power_watts(7)
2173 .temperature_celsius(-8);
2174 all.distance = Some(500);
2175 let defs: std::vec::Vec<FieldDef> = record_fields(all.fields()).collect();
2176 assert_eq!(defs.len(), 9);
2177 let mut out = VecPut(vec![]);
2178 let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
2179 all.encode(&mut fields);
2180 assert_eq!(fields.refused(), None);
2181 fields.finish();
2182 #[rustfmt::skip]
2183 let want = [
2184 1, 0, 0, 0, 2, 0, 0, 0, 0xC4, 0x09, 3, 4,
2187 0xF4, 0x01, 0, 0, 0x70, 0x17, 7, 0,
2190 0xF8, ];
2192 assert_eq!(out.0, want);
2193 assert_eq!(
2194 record_fields(RecordFields::HEART_RATE).collect::<std::vec::Vec<_>>(),
2195 [field(3, 1, base::UINT8)]
2196 );
2197 assert!(!RecordFields(0).contains(RecordFields::HEART_RATE));
2198 assert!(RecordFields::HEART_RATE.contains(RecordFields(0)));
2199 }
2200
2201 #[test]
2202 fn values_fill_their_fields_exactly() {
2203 let defs = [
2204 field(0, 2, base::UINT16),
2205 field(1, 1, base::UINT8),
2206 field(2, 3, base::STRING),
2207 field(3, 4, base::UINT32Z),
2208 field(4, 2, base::UINT16),
2209 field(5, 1, base::ENUM),
2210 ];
2211 let mut out = VecPut(vec![]);
2212 let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
2213 fields.u8(7);
2215 fields.u32(9);
2216 fields.str("ab");
2217 fields.none();
2218 fields.finish();
2219 assert_eq!(
2220 fields_refused(&defs, |f| {
2221 f.u8(7);
2222 f.u32(9);
2223 }),
2224 None
2225 );
2226 assert_eq!(out.0, [7, 0, 9, b'a', b'b', 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF]);
2227
2228 let mut out = VecPut(vec![]);
2229 let mut fields = Fields::new([field(0, 1, base::UINT8)].into_iter(), Some(&mut out));
2230 fields.u8(1);
2231 fields.u8(2);
2232 fields.str("x");
2233 fields.none();
2234 fields.finish();
2235 assert_eq!(out.0, [1], "values past the table are dropped");
2236 }
2237
2238 fn fields_refused(
2239 defs: &[FieldDef],
2240 f: impl Fn(&mut Fields<'_, core::iter::Copied<core::slice::Iter<'_, FieldDef>>>),
2241 ) -> Option<FieldError> {
2242 let mut fields = Fields::new(defs.iter().copied(), None);
2243 f(&mut fields);
2244 fields.refused()
2245 }
2246
2247 #[test]
2248 fn a_value_that_is_none_or_too_wide_is_refused() {
2249 let s8 = [field(0, 1, base::SINT8)];
2250 let s32 = [field(0, 4, base::SINT32)];
2251 assert_eq!(fields_refused(&s8, |f| f.i8(i8::MAX)), Some(FieldError::OutOfRange));
2252 assert_eq!(fields_refused(&s8, |f| f.i8(-1)), None);
2253 assert_eq!(fields_refused(&s32, |f| f.i32(i32::MAX)), Some(FieldError::OutOfRange));
2254 assert_eq!(fields_refused(&s32, |f| f.i32(-1)), None);
2255 let u8_ = [field(0, 1, base::UINT8)];
2256 let u16_ = [field(0, 2, base::UINT16)];
2257 let z = [field(0, 4, base::UINT32Z)];
2258 let e = Some(FieldError::OutOfRange);
2259 assert_eq!(fields_refused(&u8_, |f| f.u8(0xFF)), e);
2260 assert_eq!(fields_refused(&u8_, |f| f.u8(0xFE)), None);
2261 assert_eq!(fields_refused(&u8_, |f| f.u16(0x0100)), e);
2262 assert_eq!(fields_refused(&u8_, |f| f.u16(0x00FE)), None);
2263 assert_eq!(fields_refused(&u16_, |f| f.u16(0xFFFF)), e);
2264 assert_eq!(fields_refused(&u16_, |f| f.u8(0xFF)), None, "widened, it is 0x00FF");
2265 assert_eq!(fields_refused(&z, |f| f.u32(0)), e);
2266 assert_eq!(fields_refused(&z, |f| f.u32(u32::MAX)), None);
2267 assert_eq!(fields_refused(&z, |f| f.none()), None);
2268 let two = [field(0, 1, base::STRING), field(1, 1, base::UINT8)];
2270 assert_eq!(
2271 fields_refused(&two, |f| {
2272 f.str("x");
2273 f.u8(0xFF);
2274 }),
2275 Some(FieldError::StringTooLong)
2276 );
2277 }
2278
2279 #[test]
2280 fn messages_refuse_none_as_a_value() {
2281 let e = Some(FieldError::OutOfRange);
2282 let id = |t| FileId::new(t, Manufacturer::DEVELOPMENT, 1, T);
2283 assert_eq!(refused(&id(FileType::new(255)), 0), e);
2284 assert_eq!(refused(&id(FileType::ACTIVITY).serial_number(0), 0), e);
2285 assert_eq!(
2286 refused(&FileId::new(FileType::ACTIVITY, Manufacturer::new(0xFFFF), 1, T), 0),
2287 e
2288 );
2289 assert_eq!(refused(&DeviceInfo::new(T).product(0xFFFF), 0), e);
2290 assert_eq!(refused(&Event::timer_start(Timestamp::from_fit(u32::MAX)), 0), e);
2291 let lap = Lap::new(T, T2, 0, 0);
2292 assert_eq!(refused(&lap.heart_rate(255, 255), 0), e);
2293 assert_eq!(refused(&lap.sport(Sport::new(255), SubSport::GENERIC), 0), e);
2294 assert_eq!(refused(&Lap::new(T, T2, u32::MAX, 0), 0), e);
2295 assert_eq!(
2296 refused(&Session::new(T, T2, 0, 0).sport(Sport::RUNNING, SubSport::new(255)), 0),
2297 e
2298 );
2299 assert_eq!(
2300 refused(&lap.heart_rate(254, 254).sport(Sport::new(254), SubSport::new(254)), 0),
2301 None
2302 );
2303 }
2304
2305 #[test]
2306 fn masks_hold_any_field_of_a_definition() {
2307 let mut m = Mask::EMPTY;
2308 for i in [0, 63, 64, 200, 255] {
2309 assert!(!m.contains(i));
2310 m.insert(i);
2311 assert!(m.contains(i));
2312 }
2313 assert!(!m.contains(1) && !m.contains(65) && !m.contains(256));
2314 m.insert(256);
2315 assert!(!m.contains(256), "past a definition's last field");
2316 let rest = Mask::ALL.without(m);
2317 assert!(!rest.contains(64) && rest.contains(65) && rest.contains(254));
2318 let defs = [field(1, 1, base::UINT8), field(2, 2, base::UINT16), field(3, 1, base::UINT8)];
2319 let mut keep = Mask::EMPTY;
2320 keep.insert(0);
2321 keep.insert(2);
2322 assert_eq!(
2323 kept(defs.into_iter(), keep).map(|f| f.num).collect::<std::vec::Vec<_>>(),
2324 [1, 3]
2325 );
2326 }
2327
2328 #[test]
2329 fn a_message_keeps_the_fields_it_has_values_for() {
2330 let mut fields = Fields::new(DeviceInfo::FIELDS.iter().copied(), None);
2331 DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
2332 let present = fields.present();
2333 let kept: std::vec::Vec<u8> =
2334 kept(DeviceInfo::FIELDS.iter().copied(), present).map(|f| f.num).collect();
2335 assert_eq!(kept, [TIMESTAMP, 0, 27], "timestamp, device_index and product_name");
2336 let mut out = VecPut(vec![]);
2337 let mut fields =
2338 Fields::new(DeviceInfo::FIELDS.iter().copied(), Some(&mut out)).keep(present);
2339 DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
2340 fields.finish();
2341 assert_eq!(out.0.len(), 4 + 1 + 20);
2342 }
2343
2344 #[test]
2345 fn lengths() {
2346 let span = Span {
2347 start_time: T,
2348 timestamp: T2,
2349 total_elapsed_ms: 0x0001_0203,
2350 total_timer_ms: 0x0004_0506,
2351 };
2352 let swum = LengthMsg {
2353 span,
2354 swum: Some(Length::swum(SwimStroke::BACKSTROKE, 0x0708)),
2355 avg_speed: Some(0x090A),
2356 cadence: Some(11),
2357 };
2358 #[rustfmt::skip]
2359 let want = [
2360 3, 0, 0x80, 0x33, 0x22, 0x11, 28, 1, 0x44, 0x33, 0x22, 0x11,
2361 0x03, 0x02, 0x01, 0x00, 0x06, 0x05, 0x04, 0x00,
2362 0x08, 0x07, 0x0A, 0x09, 1, 11, 1,
2363 ];
2364 assert_eq!(bytes(&swum, 3), want);
2365 let idle = LengthMsg { span, swum: None, avg_speed: None, cadence: None };
2366 let out = bytes(&idle, 3);
2367 assert_eq!((&out[20..26], out[26]), (&[0xFF; 6][..], 0));
2368 let drill = LengthMsg { swum: Some(Length::drill()), ..idle };
2369 assert_eq!(&bytes(&drill, 3)[20..], [0xFF, 0xFF, 0xFF, 0xFF, 4, 0xFF, 1]);
2370 assert_eq!(idle.timestamp(), Some(T2));
2371 }
2372
2373 #[test]
2374 fn sets() {
2375 let set = Set::new()
2376 .exercise(Exercise::new(ExerciseCategory::SQUAT).name(0x0102))
2377 .repetitions(10)
2378 .weight_pounds(100.0);
2379 let msg = SetMsg { start_time: T, timestamp: T2, duration_ms: 0x0004_0506, set: Some(set) };
2380 #[rustfmt::skip]
2381 let want = [
2382 0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00,
2383 10, 0, 0xD6, 0x02, 1, 0x44, 0x33, 0x22, 0x11, 28, 0, 0x02, 0x01, 2, 0, 7, 0,
2385 ];
2386 assert_eq!(bytes(&msg, 7), want);
2387 let rest = SetMsg { set: None, ..msg };
2388 let out = bytes(&rest, 7);
2389 assert_eq!((&out[8..12], out[12]), (&[0xFF; 4][..], 0));
2390 assert_eq!(&out[17..23], &[0xFF; 6][..]);
2391 let unnamed = SetMsg {
2392 set: Some(Set::new().exercise(Exercise::new(ExerciseCategory::new(1)))),
2393 ..msg
2394 };
2395 assert_eq!(&bytes(&unnamed, 7)[17..21], [1, 0, 0xFF, 0xFF]);
2396 assert_eq!(Set::new().weight_kilograms(60.0).weight, Some(960));
2397 assert_eq!(Set::new().weight_kilograms(60.0).weight_unit, Some(1));
2398 assert_eq!(Set::new().weight_kilograms(4095.875).weight, Some(65_534));
2399 assert_eq!(Set::new().weight_kilograms(-1.0).weight, Some(u16::MAX));
2400 }
2401
2402 #[test]
2403 fn pools() {
2404 assert_eq!(Pool::meters(25.0), Pool { centimetres: 2500, unit: 0 });
2405 assert_eq!(Pool::yards(25.0), Pool { centimetres: 2286, unit: 1 });
2406 assert_eq!(Pool::meters(33.333), Pool { centimetres: 3333, unit: 0 });
2407 assert_eq!(Pool::meters(1000.0).centimetres, u16::MAX);
2408 }
2409
2410 #[test]
2411 fn pool_limits_hold_once_rounded() {
2412 let check = |pool| Leg::pool_swim(pool).check();
2413 for (largest, pool) in [
2414 (655.344_999_999_999_9, Pool::meters as fn(f64) -> Pool),
2415 (716.694_006_999_125, Pool::yards),
2416 ] {
2417 assert_eq!(pool(largest).centimetres, 65_534);
2418 assert_eq!(check(pool(largest)), Ok(()));
2419 assert_eq!(check(pool(largest.next_up())), Err(crate::Error::OutOfRange));
2420 }
2421 assert_eq!(check(Pool::meters(0.005)), Ok(()));
2422 assert_eq!(check(Pool::meters(0.004_999_999_999_999_998)), Err(crate::Error::OutOfRange));
2423 }
2424
2425 #[test]
2426 fn speed_and_weight_limits_hold_once_rounded() {
2427 let speed = |s| Record::new(Timestamp::from_fit(0)).speed_meters_per_second(s).speed;
2428 assert_eq!(speed(65.5345), Some(65_534));
2429 assert_eq!(speed(65.5345_f64.next_up()), Some(u16::MAX));
2430 let kg = |k| Set::new().weight_kilograms(k).weight;
2431 assert_eq!(kg(4_095.906_249_999_999_5), Some(65_534));
2432 assert_eq!(kg(4_095.906_25), Some(u16::MAX));
2433 let lb = |p| Set::new().weight_pounds(p).weight;
2434 assert_eq!(lb(9_029.927_575_721_786), Some(65_534));
2435 assert_eq!(lb(9_029.927_575_721_787), Some(u16::MAX));
2436 }
2437
2438 #[test]
2439 fn beat_intervals_fill_five_slots() {
2440 let out = bytes(&Hrv(&[0x0102, 0x0304]), 0);
2441 assert_eq!(out, [0x02, 0x01, 0x04, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
2442 assert_eq!(bytes(&Hrv(&[1, 2, 3, 4, 5]), 0), [1, 0, 2, 0, 3, 0, 4, 0, 5, 0]);
2443 assert_eq!(refused(&Hrv(&[1, 2, 3, 4, 5, 6]), 0), Some(FieldError::OutOfRange));
2444 assert_eq!(refused(&Hrv(&[1, u16::MAX]), 0), Some(FieldError::OutOfRange));
2445 assert_eq!(bytes(&Hrv(&[]), 0), [0xFF; 10], "none");
2446 assert_eq!(Hrv(&[]).timestamp(), None);
2447 }
2448
2449 #[test]
2450 fn bytes_fill_their_field_exactly() {
2451 let defs = [field(0, 2, base::BYTE)];
2452 let e = Some(FieldError::OutOfRange);
2453 assert_eq!(fields_refused(&defs, |f| f.bytes(&[1, 2, 3])), e);
2454 assert_eq!(fields_refused(&defs, |f| f.bytes(&[1])), e);
2455 assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0xFF])), e);
2456 assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0])), None);
2457 }
2458
2459 #[test]
2460 fn strings_need_room_for_their_nul() {
2461 let defs = [field(0, 3, base::STRING)];
2462 let mut fields = Fields::new(defs.into_iter(), None);
2463 fields.str("abc");
2464 assert_eq!(fields.refused(), Some(FieldError::StringTooLong));
2465 let mut fields = Fields::new(defs.into_iter(), None);
2466 fields.str("ab");
2467 assert_eq!(fields.refused(), None);
2468 }
2469
2470 #[test]
2471 fn strings_hold_no_nul() {
2472 let defs = [field(0, 8, base::STRING)];
2473 for s in ["a\0b", "\0", "ab\0"] {
2474 let mut fields = Fields::new(defs.into_iter(), None);
2475 fields.str(s);
2476 assert_eq!(fields.refused(), Some(FieldError::OutOfRange), "{s:?}");
2477 }
2478 }
2479}