use crate::types::{
half_up, ExerciseCategory, FileType, Manufacturer, Position, Sport, SubSport, SwimStroke,
Timestamp,
};
pub(crate) mod base {
pub const ENUM: u8 = 0x00;
pub const SINT8: u8 = 0x01;
pub const UINT8: u8 = 0x02;
pub const STRING: u8 = 0x07;
pub const UINT8Z: u8 = 0x0A;
pub const BYTE: u8 = 0x0D;
pub const SINT16: u8 = 0x83;
pub const UINT16: u8 = 0x84;
pub const SINT32: u8 = 0x85;
pub const UINT32: u8 = 0x86;
pub const FLOAT32: u8 = 0x88;
pub const FLOAT64: u8 = 0x89;
pub const UINT16Z: u8 = 0x8B;
pub const UINT32Z: u8 = 0x8C;
pub const SINT64: u8 = 0x8E;
pub const UINT64: u8 = 0x8F;
pub const UINT64Z: u8 = 0x90;
}
const INVALID_U8: u8 = 0xFF;
const INVALID_U32: u32 = 0xFFFF_FFFF;
pub(crate) const TIMESTAMP: u8 = 253;
const MESSAGE_INDEX: u8 = 254;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FieldDef {
pub num: u8,
pub size: u8,
pub base: u8,
}
pub(crate) const fn field(num: u8, size: u8, base: u8) -> FieldDef {
FieldDef { num, size, base }
}
pub(crate) trait FieldOut {
fn u8(&mut self, v: u8);
fn u16(&mut self, v: u16);
fn u32(&mut self, v: u32);
fn i8(&mut self, v: i8);
fn i32(&mut self, v: i32);
fn str(&mut self, v: &str);
fn u16s(&mut self, v: &[u16]);
fn bytes(&mut self, v: &[u8]);
fn none(&mut self);
fn opt_u8(&mut self, v: Option<u8>) {
match v {
Some(v) => self.u8(v),
None => self.none(),
}
}
fn opt_u16(&mut self, v: Option<u16>) {
match v {
Some(v) => self.u16(v),
None => self.none(),
}
}
fn opt_i8(&mut self, v: Option<i8>) {
match v {
Some(v) => self.i8(v),
None => self.none(),
}
}
fn position(&mut self, v: Option<Position>) {
if let Some((lat, long)) = v.map(Position::semicircles) {
self.i32(lat);
self.i32(long);
} else {
self.none();
self.none();
}
}
fn opt_u32(&mut self, v: Option<u32>) {
match v {
Some(v) => self.u32(v),
None => self.none(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FieldError {
StringTooLong,
OutOfRange,
}
pub(crate) trait Put {
fn put(&mut self, bytes: &[u8]);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct Mask([u64; 4]);
impl Mask {
pub(crate) const ALL: Self = Self([u64::MAX; 4]);
const EMPTY: Self = Self([0; 4]);
fn word_bit(i: usize) -> (usize, u64) {
let shift = u32::try_from(i % 64).unwrap_or(u32::MAX);
(i / 64, 1u64.checked_shl(shift).unwrap_or(0))
}
pub(crate) fn contains(self, i: usize) -> bool {
let (word, bit) = Self::word_bit(i);
self.0.get(word).is_some_and(|w| w & bit != 0)
}
fn insert(&mut self, i: usize) {
let (word, bit) = Self::word_bit(i);
if let Some(w) = self.0.get_mut(word) {
*w |= bit;
}
}
fn without(self, other: Self) -> Self {
let mut words = self.0;
for (word, out) in words.iter_mut().zip(other.0) {
*word &= !out;
}
Self(words)
}
}
pub(crate) fn kept<I: Iterator<Item = FieldDef> + Clone>(
table: I,
keep: Mask,
) -> impl Iterator<Item = FieldDef> + Clone {
table.enumerate().filter(move |(i, _)| keep.contains(*i)).map(|(_, f)| f)
}
pub(crate) struct Fields<'a, I> {
defs: I,
out: Option<&'a mut dyn Put>,
refused: Option<FieldError>,
keep: Mask,
next: usize,
writing: bool,
nones: Mask,
}
pub(crate) const fn none_byte(base: u8, i: usize, size: usize) -> u8 {
match base {
base::STRING | base::UINT8Z | base::UINT16Z | base::UINT32Z | base::UINT64Z => 0,
base::SINT8 | base::SINT16 | base::SINT32 | base::SINT64 if i.saturating_add(1) == size => {
0x7F
}
_ => INVALID_U8,
}
}
pub(crate) fn is_none(base: u8, value: &[u8]) -> bool {
value.iter().enumerate().all(|(i, &b)| b == none_byte(base, i, value.len()))
}
impl<'a, I: Iterator<Item = FieldDef>> Fields<'a, I> {
pub(crate) fn new(defs: I, out: Option<&'a mut dyn Put>) -> Self {
Self {
defs,
out,
refused: None,
keep: Mask::ALL,
next: 0,
writing: false,
nones: Mask::EMPTY,
}
}
pub(crate) const fn keep(mut self, keep: Mask) -> Self {
self.keep = keep;
self
}
pub(crate) const fn refused(&self) -> Option<FieldError> {
self.refused
}
pub(crate) fn present(mut self) -> Mask {
while self.field().is_some() {
self.nones.insert(self.next.saturating_sub(1));
}
Mask::ALL.without(self.nones)
}
fn field(&mut self) -> Option<FieldDef> {
let def = self.defs.next()?;
self.writing = self.keep.contains(self.next);
self.next = self.next.saturating_add(1);
Some(def)
}
fn put(&mut self, bytes: &[u8]) {
if let (true, Some(out)) = (self.writing, self.out.as_deref_mut()) {
out.put(bytes);
}
}
fn refuse(&mut self, e: FieldError) {
self.refused.get_or_insert(e);
}
fn fill(&mut self, def: FieldDef) {
self.nones.insert(self.next.saturating_sub(1));
let size = usize::from(def.size);
for i in 0..size {
self.put(&[none_byte(def.base, i, size)]);
}
}
fn number(&mut self, le: &[u8]) {
let Some(def) = self.field() else { return };
let size = usize::from(def.size);
let (value, rest) = le.split_at(size.min(le.len()));
let is_none = value.len() == size && is_none(def.base, value);
if rest.iter().any(|&b| b != 0) || is_none {
self.refuse(FieldError::OutOfRange);
}
self.put(value);
for _ in value.len()..size {
self.put(&[0]);
}
}
pub(crate) fn finish(mut self) {
while let Some(def) = self.field() {
self.fill(def);
}
}
}
impl<I: Iterator<Item = FieldDef>> FieldOut for Fields<'_, I> {
fn u8(&mut self, v: u8) {
self.number(&[v]);
}
fn u16(&mut self, v: u16) {
self.number(&v.to_le_bytes());
}
fn u32(&mut self, v: u32) {
self.number(&v.to_le_bytes());
}
fn i8(&mut self, v: i8) {
self.number(&v.to_le_bytes());
}
fn i32(&mut self, v: i32) {
self.number(&v.to_le_bytes());
}
fn str(&mut self, v: &str) {
let Some(def) = self.field() else { return };
let bytes = v.as_bytes();
if bytes.is_empty() {
self.fill(def);
return;
}
if bytes.contains(&0) {
self.refuse(FieldError::OutOfRange);
return;
}
if bytes.len() >= usize::from(def.size) {
self.refuse(FieldError::StringTooLong);
return;
}
self.put(bytes);
for _ in bytes.len()..usize::from(def.size) {
self.put(&[0]);
}
}
fn u16s(&mut self, v: &[u16]) {
let Some(def) = self.field() else { return };
let size = usize::from(def.size);
let len = v.len().saturating_mul(2);
if len > size || v.contains(&u16::MAX) {
self.refuse(FieldError::OutOfRange);
}
if v.is_empty() {
self.fill(def);
return;
}
for x in v {
self.put(&x.to_le_bytes());
}
for _ in len..size {
self.put(&[INVALID_U8]);
}
}
fn bytes(&mut self, v: &[u8]) {
let Some(def) = self.field() else { return };
if v.len() != usize::from(def.size) || is_none(def.base, v) {
self.refuse(FieldError::OutOfRange);
return;
}
self.put(v);
}
fn none(&mut self) {
if let Some(def) = self.field() {
self.fill(def);
}
}
}
pub(crate) fn data_len(fields: impl Iterator<Item = FieldDef>) -> u32 {
fields.map(|f| u32::from(f.size)).fold(0, u32::wrapping_add)
}
pub(crate) trait Message {
const GLOBAL: u16;
const FIELDS: &'static [FieldDef];
fn timestamp(&self) -> Option<Timestamp>;
fn encode(&self, out: &mut dyn FieldOut, index: u16);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FileId {
file_type: FileType,
manufacturer: Manufacturer,
product: u16,
serial_number: Option<u32>,
time_created: Timestamp,
}
impl FileId {
#[must_use]
pub const fn new(
file_type: FileType,
manufacturer: Manufacturer,
product: u16,
time_created: Timestamp,
) -> Self {
Self { file_type, manufacturer, product, serial_number: None, time_created }
}
#[must_use]
pub const fn serial_number(mut self, serial_number: u32) -> Self {
self.serial_number = Some(serial_number);
self
}
}
impl Message for FileId {
const GLOBAL: u16 = 0;
const FIELDS: &'static [FieldDef] = &[
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), ];
fn timestamp(&self) -> Option<Timestamp> {
None
}
fn encode(&self, out: &mut dyn FieldOut, _: u16) {
out.u8(self.file_type.get());
out.u16(self.manufacturer.get());
out.u16(self.product);
out.opt_u32(self.serial_number);
out.u32(self.time_created.fit());
}
}
pub const PRODUCT_NAME_MAX: usize = 19;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Device<'a> {
pub(crate) manufacturer: Manufacturer,
pub(crate) product: u16,
pub(crate) serial_number: Option<u32>,
pub(crate) software_version: Option<u16>,
pub(crate) product_name: &'a str,
}
impl<'a> Device<'a> {
#[must_use]
pub const fn new(manufacturer: Manufacturer, product: u16) -> Self {
Self {
manufacturer,
product,
serial_number: None,
software_version: None,
product_name: "",
}
}
#[must_use]
pub const fn serial_number(mut self, serial_number: u32) -> Self {
self.serial_number = Some(serial_number);
self
}
#[must_use]
pub const fn software_version(mut self, hundredths: u16) -> Self {
self.software_version = Some(hundredths);
self
}
#[must_use]
pub const fn product_name(mut self, name: &'a str) -> Self {
self.product_name = name;
self
}
pub(crate) const fn info(&self, timestamp: Timestamp, index: u8) -> DeviceInfo<'a> {
DeviceInfo {
timestamp,
device_index: index,
manufacturer: Some(self.manufacturer),
serial_number: self.serial_number,
product: Some(self.product),
software_version: self.software_version,
product_name: self.product_name,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DeviceInfo<'a> {
timestamp: Timestamp,
device_index: u8,
manufacturer: Option<Manufacturer>,
serial_number: Option<u32>,
product: Option<u16>,
software_version: Option<u16>,
product_name: &'a str,
}
#[cfg(test)]
impl<'a> DeviceInfo<'a> {
pub(crate) const fn new(timestamp: Timestamp) -> Self {
Self {
timestamp,
device_index: 0,
manufacturer: None,
serial_number: None,
product: None,
software_version: None,
product_name: "",
}
}
pub(crate) const fn device_index(mut self, device_index: u8) -> Self {
self.device_index = device_index;
self
}
pub(crate) const fn manufacturer(mut self, manufacturer: Manufacturer) -> Self {
self.manufacturer = Some(manufacturer);
self
}
pub(crate) const fn serial_number(mut self, serial_number: u32) -> Self {
self.serial_number = Some(serial_number);
self
}
pub(crate) const fn product(mut self, product: u16) -> Self {
self.product = Some(product);
self
}
pub(crate) const fn software_version(mut self, hundredths: u16) -> Self {
self.software_version = Some(hundredths);
self
}
pub(crate) const fn product_name(mut self, name: &'a str) -> Self {
self.product_name = name;
self
}
}
impl Message for DeviceInfo<'_> {
const GLOBAL: u16 = 23;
#[allow(clippy::cast_possible_truncation)]
const FIELDS: &'static [FieldDef] = &[
field(TIMESTAMP, 4, base::UINT32),
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), ];
fn timestamp(&self) -> Option<Timestamp> {
Some(self.timestamp)
}
fn encode(&self, out: &mut dyn FieldOut, _: u16) {
out.u32(self.timestamp.fit());
out.u8(self.device_index);
out.opt_u16(self.manufacturer.map(Manufacturer::get));
out.opt_u32(self.serial_number);
out.opt_u16(self.product);
out.opt_u16(self.software_version);
out.str(self.product_name);
}
}
pub(crate) mod event {
pub const TIMER: u8 = 0;
pub const SESSION: u8 = 8;
pub const LAP: u8 = 9;
pub const LENGTH: u8 = 28;
pub const ACTIVITY: u8 = 26;
pub const START: u8 = 0;
pub const STOP: u8 = 1;
pub const STOP_ALL: u8 = 4;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(clippy::struct_field_names)]
pub(crate) struct Event {
timestamp: Timestamp,
event: u8,
event_type: u8,
}
impl Event {
#[must_use]
pub const fn timer_start(timestamp: Timestamp) -> Self {
Self { timestamp, event: event::TIMER, event_type: event::START }
}
#[must_use]
pub const fn timer_stop(timestamp: Timestamp) -> Self {
Self { timestamp, event: event::TIMER, event_type: event::STOP }
}
#[must_use]
pub const fn timer_stop_all(timestamp: Timestamp) -> Self {
Self { timestamp, event: event::TIMER, event_type: event::STOP_ALL }
}
}
impl Message for Event {
const GLOBAL: u16 = 21;
const FIELDS: &'static [FieldDef] = &[
field(TIMESTAMP, 4, base::UINT32),
field(0, 1, base::ENUM), field(1, 1, base::ENUM), ];
fn timestamp(&self) -> Option<Timestamp> {
Some(self.timestamp)
}
fn encode(&self, out: &mut dyn FieldOut, _: u16) {
out.u32(self.timestamp.fit());
out.u8(self.event);
out.u8(self.event_type);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct RecordFields(pub(crate) u32);
impl RecordFields {
pub(crate) const POSITION: Self = Self(1);
pub(crate) const ALTITUDE: Self = Self(1 << 1);
pub(crate) const HEART_RATE: Self = Self(1 << 2);
pub(crate) const CADENCE: Self = Self(1 << 3);
pub(crate) const DISTANCE: Self = Self(1 << 4);
pub(crate) const SPEED: Self = Self(1 << 5);
pub(crate) const POWER: Self = Self(1 << 6);
pub(crate) const TEMPERATURE: Self = Self(1 << 7);
pub(crate) const fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
const RECORD_FIELDS: [(RecordFields, FieldDef); 9] = [
(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)),
(RecordFields::CADENCE, field(4, 1, base::UINT8)),
(RecordFields::DISTANCE, field(5, 4, base::UINT32)), (RecordFields::SPEED, field(6, 2, base::UINT16)), (RecordFields::POWER, field(7, 2, base::UINT16)),
(RecordFields::TEMPERATURE, field(13, 1, base::SINT8)),
];
pub(crate) const RECORD_GLOBAL: u16 = 20;
pub(crate) const RECORD_TIMESTAMP: FieldDef = field(TIMESTAMP, 4, base::UINT32);
pub(crate) fn record_owns(num: u8) -> bool {
num == TIMESTAMP
|| [8, 73, 78].contains(&num)
|| RECORD_FIELDS.iter().any(|(_, f)| f.num == num)
}
pub(crate) fn record_fields(layout: RecordFields) -> impl Iterator<Item = FieldDef> + Clone {
RECORD_FIELDS.into_iter().filter(move |(bit, _)| layout.contains(*bit)).map(|(_, f)| f)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Record {
pub(crate) timestamp: Timestamp,
pub(crate) position: Option<Position>,
pub(crate) altitude: Option<Altitude>,
pub(crate) heart_rate: Option<u8>,
pub(crate) cadence: Option<u8>,
pub(crate) distance_input: Option<Distance>,
pub(crate) distance: Option<u32>,
pub(crate) speed: Option<u16>,
pub(crate) power: Option<u16>,
pub(crate) temperature: Option<i8>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Distance {
Advanced(u64),
Total(u32),
}
pub(crate) const SMOOTHING: u8 = 5;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Altitude {
pub(crate) fifths: u16,
pub(crate) threshold: u16,
pub(crate) window: u8,
}
impl Altitude {
#[must_use]
pub fn barometric_meters(meters: f64) -> Self {
Self::meters_with_threshold(meters, 2.0)
}
#[must_use]
pub fn gnss_meters(meters: f64) -> Self {
Self::meters_with_threshold(meters, 10.0)
}
#[must_use]
pub fn smoothed_meters(meters: f64) -> Self {
Self { window: 1, ..Self::meters_with_threshold(meters, 0.0) }
}
#[must_use]
pub fn meters_with_threshold(meters: f64, threshold: f64) -> Self {
let none = u32::from(u16::MAX);
let fifths = u16::try_from(scaled(meters + 500.0, 5.0, none)).unwrap_or(u16::MAX);
let threshold = u16::try_from(scaled(threshold, 5.0, none)).unwrap_or(u16::MAX);
let fifths = if threshold == u16::MAX { u16::MAX } else { fifths };
Self { fifths, threshold: threshold.max(1), window: SMOOTHING }
}
}
fn scaled(x: f64, scale: f64, none: u32) -> u32 {
half_up(x * scale).map_or(none, |v| u32::try_from(v).unwrap_or(none).min(none))
}
impl Record {
#[must_use]
pub const fn new(timestamp: Timestamp) -> Self {
Self {
timestamp,
position: None,
altitude: None,
heart_rate: None,
cadence: None,
distance_input: None,
distance: None,
speed: None,
power: None,
temperature: None,
}
}
#[must_use]
pub const fn position(mut self, position: Position) -> Self {
self.position = Some(position);
self
}
#[must_use]
pub const fn altitude(mut self, altitude: Altitude) -> Self {
self.altitude = Some(altitude);
self
}
#[must_use]
pub const fn heart_rate(mut self, bpm: u8) -> Self {
self.heart_rate = Some(bpm);
self
}
#[must_use]
pub const fn cadence_rpm(mut self, rpm: u8) -> Self {
self.cadence = Some(rpm);
self
}
#[must_use]
pub fn distance_advanced_meters(mut self, meters: f64) -> Self {
let um = half_up(meters * 1e6).unwrap_or(u64::MAX);
self.distance_input = Some(Distance::Advanced(um));
self
}
#[must_use]
pub fn distance_meters(mut self, meters: f64) -> Self {
self.distance_input = Some(Distance::Total(scaled(meters, 100.0, u32::MAX)));
self
}
#[must_use]
pub fn speed_meters_per_second(mut self, speed: f64) -> Self {
let raw = scaled(speed, 1000.0, u32::from(u16::MAX));
self.speed = Some(u16::try_from(raw).unwrap_or(u16::MAX));
self
}
#[must_use]
pub const fn power_watts(mut self, watts: u16) -> Self {
self.power = Some(watts);
self
}
#[must_use]
pub const fn temperature_celsius(mut self, celsius: i8) -> Self {
self.temperature = Some(celsius);
self
}
pub(crate) fn fields(self) -> RecordFields {
let bits = [
(self.position.is_some(), RecordFields::POSITION),
(self.altitude.is_some(), RecordFields::ALTITUDE),
(self.heart_rate.is_some(), RecordFields::HEART_RATE),
(self.cadence.is_some(), RecordFields::CADENCE),
(self.distance.is_some(), RecordFields::DISTANCE),
(self.speed.is_some(), RecordFields::SPEED),
(self.power.is_some(), RecordFields::POWER),
(self.temperature.is_some(), RecordFields::TEMPERATURE),
];
RecordFields(bits.iter().filter(|(set, _)| *set).map(|(_, bit)| bit.0).sum())
}
pub(crate) fn encode(self, out: &mut dyn FieldOut) {
if self.position.is_some() {
out.position(self.position);
}
if let Some(v) = self.altitude.map(|a| a.fifths) {
out.u16(v);
}
if let Some(v) = self.heart_rate {
out.u8(v);
}
if let Some(v) = self.cadence {
out.u8(v);
}
if let Some(v) = self.distance {
out.u32(v);
}
if let Some(v) = self.speed {
out.u16(v);
}
if let Some(v) = self.power {
out.u16(v);
}
if let Some(v) = self.temperature {
out.i8(v);
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Span {
pub start_time: Timestamp,
pub timestamp: Timestamp,
pub total_elapsed_ms: u32,
pub total_timer_ms: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Summary {
avg_heart_rate: Option<u8>,
max_heart_rate: Option<u8>,
sport: Option<Sport>,
sub_sport: Option<SubSport>,
}
impl Summary {
const NONE: Self =
Self { avg_heart_rate: None, max_heart_rate: None, sport: None, sub_sport: None };
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Totals {
pub start: Option<Position>,
pub end: Option<Position>,
pub north_east: Option<Position>,
pub south_west: Option<Position>,
pub distance: Option<u32>,
pub avg_speed: Option<u16>,
pub max_speed: Option<u16>,
pub avg_cadence: Option<u8>,
pub max_cadence: Option<u8>,
pub avg_power: Option<u16>,
pub max_power: Option<u16>,
pub ascent: Option<u16>,
pub descent: Option<u16>,
pub avg_temperature: Option<i8>,
pub max_temperature: Option<i8>,
pub cycles: Option<u32>,
pub lengths: Option<u16>,
pub active_lengths: Option<u16>,
pub stroke_distance: Option<u16>,
pub swim_stroke: Option<SwimStroke>,
}
impl Totals {
pub(crate) const NONE: Self = Self {
start: None,
end: None,
north_east: None,
south_west: None,
distance: None,
avg_speed: None,
max_speed: None,
avg_cadence: None,
max_cadence: None,
avg_power: None,
max_power: None,
ascent: None,
descent: None,
avg_temperature: None,
max_temperature: None,
cycles: None,
lengths: None,
active_lengths: None,
stroke_distance: None,
swim_stroke: None,
};
fn encode(&self, out: &mut dyn FieldOut) {
out.position(self.start);
out.position(self.end);
out.opt_u32(self.distance);
out.opt_u16(self.avg_speed);
out.opt_u16(self.max_speed);
out.opt_u8(self.avg_cadence);
out.opt_u8(self.max_cadence);
out.opt_u16(self.avg_power);
out.opt_u16(self.max_power);
out.opt_u16(self.ascent);
out.opt_u16(self.descent);
out.position(self.north_east);
out.position(self.south_west);
out.opt_i8(self.avg_temperature);
out.opt_i8(self.max_temperature);
out.opt_u32(self.cycles);
out.opt_u16(self.lengths);
out.opt_u16(self.active_lengths);
out.opt_u16(self.stroke_distance);
out.opt_u8(self.swim_stroke.map(SwimStroke::get));
}
}
macro_rules! with_totals {
(
[$($head:expr),* $(,)?],
$start_lat:literal, $start_long:literal, $end_lat:literal, $end_long:literal,
$distance:literal, $avg_speed:literal, $max_speed:literal, $avg_cadence:literal,
$max_cadence:literal, $avg_power:literal, $max_power:literal, $ascent:literal,
$descent:literal, $nec_lat:literal, $nec_long:literal, $swc_lat:literal,
$swc_long:literal, $avg_temperature:literal, $max_temperature:literal,
$cycles:literal, $lengths:literal, $active_lengths:literal, $stroke_distance:literal,
$swim_stroke:literal, [$($tail:expr),* $(,)?]
) => {
&[
$($head,)*
field($start_lat, 4, base::SINT32),
field($start_long, 4, base::SINT32),
field($end_lat, 4, base::SINT32),
field($end_long, 4, base::SINT32),
field($distance, 4, base::UINT32), field($avg_speed, 2, base::UINT16), field($max_speed, 2, base::UINT16), field($avg_cadence, 1, base::UINT8),
field($max_cadence, 1, base::UINT8),
field($avg_power, 2, base::UINT16),
field($max_power, 2, base::UINT16),
field($ascent, 2, base::UINT16),
field($descent, 2, base::UINT16),
field($nec_lat, 4, base::SINT32),
field($nec_long, 4, base::SINT32),
field($swc_lat, 4, base::SINT32),
field($swc_long, 4, base::SINT32),
field($avg_temperature, 1, base::SINT8),
field($max_temperature, 1, base::SINT8),
field($cycles, 4, base::UINT32),
field($lengths, 2, base::UINT16),
field($active_lengths, 2, base::UINT16),
field($stroke_distance, 2, base::UINT16), field($swim_stroke, 1, base::ENUM),
$($tail,)*
]
};
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Lap {
span: Span,
summary: Summary,
totals: Totals,
first_length_index: Option<u16>,
trigger: u8,
}
impl Lap {
#[must_use]
pub const fn new(
start_time: Timestamp,
timestamp: Timestamp,
total_elapsed_ms: u32,
total_timer_ms: u32,
) -> Self {
Self {
span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
summary: Summary::NONE,
totals: Totals::NONE,
first_length_index: None,
trigger: lap_trigger::MANUAL,
}
}
#[must_use]
pub const fn trigger(mut self, trigger: u8) -> Self {
self.trigger = trigger;
self
}
#[must_use]
pub const fn first_length(mut self, index: u16) -> Self {
self.first_length_index = Some(index);
self
}
#[must_use]
pub const fn totals(mut self, totals: Totals) -> Self {
self.totals = totals;
self
}
#[must_use]
pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
self.summary.avg_heart_rate = Some(avg);
self.summary.max_heart_rate = Some(max);
self
}
#[must_use]
pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
self.summary.sport = Some(sport);
self.summary.sub_sport = Some(sub_sport);
self
}
}
impl Message for Lap {
const GLOBAL: u16 = 19;
const FIELDS: &'static [FieldDef] = with_totals!(
[
field(MESSAGE_INDEX, 2, base::UINT16),
field(TIMESTAMP, 4, base::UINT32),
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), ],
3,
4,
5,
6,
9,
13,
14,
17,
18,
19,
20,
21,
22,
27,
28,
29,
30,
50,
51,
10,
32,
40,
37,
38,
[field(35, 2, base::UINT16)] );
fn timestamp(&self) -> Option<Timestamp> {
Some(self.span.timestamp)
}
fn encode(&self, out: &mut dyn FieldOut, index: u16) {
let (span, summary) = (&self.span, &self.summary);
out.u16(index);
out.u32(span.timestamp.fit());
out.u8(event::LAP);
out.u8(event::STOP);
out.u32(span.start_time.fit());
out.u32(span.total_elapsed_ms);
out.u32(span.total_timer_ms);
out.opt_u8(summary.avg_heart_rate);
out.opt_u8(summary.max_heart_rate);
out.opt_u8(summary.sport.map(Sport::get));
out.opt_u8(summary.sub_sport.map(SubSport::get));
out.u8(self.trigger);
self.totals.encode(out);
out.opt_u16(self.first_length_index);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Session {
span: Span,
summary: Summary,
totals: Totals,
first_lap_index: u16,
num_laps: u16,
pool: Option<Pool>,
trigger: u8,
}
impl Session {
#[must_use]
pub const fn new(
start_time: Timestamp,
timestamp: Timestamp,
total_elapsed_ms: u32,
total_timer_ms: u32,
) -> Self {
Self {
span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
summary: Summary::NONE,
totals: Totals::NONE,
first_lap_index: 0,
num_laps: 1,
pool: None,
trigger: trigger::ACTIVITY_END,
}
}
#[must_use]
pub const fn trigger(mut self, trigger: u8) -> Self {
self.trigger = trigger;
self
}
#[must_use]
pub const fn pool(mut self, pool: Pool) -> Self {
self.pool = Some(pool);
self
}
#[must_use]
pub const fn totals(mut self, totals: Totals) -> Self {
self.totals = totals;
self
}
#[must_use]
pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
self.summary.avg_heart_rate = Some(avg);
self.summary.max_heart_rate = Some(max);
self
}
#[must_use]
pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
self.summary.sport = Some(sport);
self.summary.sub_sport = Some(sub_sport);
self
}
#[must_use]
pub const fn laps(mut self, first: u16, count: u16) -> Self {
self.first_lap_index = first;
self.num_laps = count;
self
}
}
impl Message for Session {
const GLOBAL: u16 = 18;
const FIELDS: &'static [FieldDef] = with_totals!(
[
field(MESSAGE_INDEX, 2, base::UINT16),
field(TIMESTAMP, 4, base::UINT32),
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), ],
3,
4,
38,
39,
9,
14,
15,
18,
19,
20,
21,
22,
23,
29,
30,
31,
32,
57,
58,
10,
33,
47,
42,
43,
[
field(44, 2, base::UINT16), field(46, 1, base::ENUM), field(28, 1, base::ENUM), ]
);
fn timestamp(&self) -> Option<Timestamp> {
Some(self.span.timestamp)
}
fn encode(&self, out: &mut dyn FieldOut, index: u16) {
let (span, summary) = (&self.span, &self.summary);
out.u16(index);
out.u32(span.timestamp.fit());
out.u8(event::SESSION);
out.u8(event::STOP);
out.u32(span.start_time.fit());
out.opt_u8(summary.sport.map(Sport::get));
out.opt_u8(summary.sub_sport.map(SubSport::get));
out.u32(span.total_elapsed_ms);
out.u32(span.total_timer_ms);
out.opt_u8(summary.avg_heart_rate);
out.opt_u8(summary.max_heart_rate);
out.u16(self.first_lap_index);
out.u16(self.num_laps);
self.totals.encode(out);
out.opt_u16(self.pool.map(|p| p.centimetres));
out.opt_u8(self.pool.map(|p| p.unit));
out.u8(self.trigger);
}
}
pub(crate) mod lap_trigger {
pub const MANUAL: u8 = 0;
pub const SESSION_END: u8 = 7;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LapTrigger {
Manual,
Time,
Distance,
PositionStart,
PositionLap,
PositionWaypoint,
PositionMarked,
FitnessEquipment,
}
impl LapTrigger {
pub(crate) const fn get(self) -> u8 {
match self {
Self::Manual => lap_trigger::MANUAL,
Self::Time => 1,
Self::Distance => 2,
Self::PositionStart => 3,
Self::PositionLap => 4,
Self::PositionWaypoint => 5,
Self::PositionMarked => 6,
Self::FitnessEquipment => 8,
}
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Manual => "manual",
Self::Time => "time",
Self::Distance => "distance",
Self::PositionStart => "position_start",
Self::PositionLap => "position_lap",
Self::PositionWaypoint => "position_waypoint",
Self::PositionMarked => "position_marked",
Self::FitnessEquipment => "fitness_equipment",
}
}
}
impl core::fmt::Display for LapTrigger {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.name())
}
}
pub(crate) mod trigger {
pub const ACTIVITY_END: u8 = 0;
pub const MANUAL: u8 = 1;
pub const AUTO_MULTI_SPORT: u8 = 2;
}
pub const SPORT_NAME_MAX: usize = 23;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SportMsg<'a> {
pub sport: Sport,
pub sub_sport: SubSport,
pub name: &'a str,
}
impl Message for SportMsg<'_> {
const GLOBAL: u16 = 12;
#[allow(clippy::cast_possible_truncation, reason = "a short name")]
const FIELDS: &'static [FieldDef] = &[
field(0, 1, base::ENUM), field(1, 1, base::ENUM), field(3, SPORT_NAME_MAX as u8 + 1, base::STRING), ];
fn timestamp(&self) -> Option<Timestamp> {
None
}
fn encode(&self, out: &mut dyn FieldOut, _: u16) {
out.u8(self.sport.get());
out.u8(self.sub_sport.get());
out.str(self.name);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Leg<'a> {
pub(crate) sport: SportMsg<'a>,
pub(crate) pool: Option<Pool>,
pub(crate) by_hand: bool,
}
impl<'a> Leg<'a> {
#[must_use]
pub const fn new(sport: Sport, sub_sport: SubSport) -> Self {
Self { sport: SportMsg { sport, sub_sport, name: "" }, pool: None, by_hand: false }
}
#[must_use]
pub const fn pool_swim(pool: Pool) -> Self {
let sport =
SportMsg { sport: Sport::SWIMMING, sub_sport: SubSport::LAP_SWIMMING, name: "" };
Self { sport, pool: Some(pool), by_hand: false }
}
#[must_use]
pub const fn named(mut self, name: &'a str) -> Self {
self.sport.name = name;
self
}
#[must_use]
pub const fn by_hand(mut self) -> Self {
self.by_hand = true;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Pool {
pub(crate) centimetres: u16,
pub(crate) unit: u8,
}
impl Pool {
#[must_use]
pub fn meters(meters: f64) -> Self {
Self::of(meters, 0)
}
#[must_use]
pub fn yards(yards: f64) -> Self {
Self::of(yards * 0.9144, 1)
}
fn of(meters: f64, unit: u8) -> Self {
let cm = scaled(meters, 100.0, u32::from(u16::MAX));
Self { centimetres: u16::try_from(cm).unwrap_or(u16::MAX), unit }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Length {
pub(crate) stroke: SwimStroke,
pub(crate) strokes: Option<u16>,
}
impl Length {
#[must_use]
pub const fn swum(stroke: SwimStroke, strokes: u16) -> Self {
if stroke.get() == SwimStroke::DRILL.get() {
return Self::drill();
}
Self { stroke, strokes: Some(strokes) }
}
#[must_use]
pub const fn drill() -> Self {
Self { stroke: SwimStroke::DRILL, strokes: None }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Exercise {
pub(crate) category: ExerciseCategory,
pub(crate) name: Option<u16>,
}
impl Exercise {
#[must_use]
pub const fn new(category: ExerciseCategory) -> Self {
Self { category, name: None }
}
#[must_use]
pub const fn name(mut self, name: u16) -> Self {
self.name = Some(name);
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Set {
pub(crate) exercise: Option<Exercise>,
pub(crate) repetitions: Option<u16>,
pub(crate) weight: Option<u16>,
pub(crate) weight_unit: Option<u16>,
}
impl Set {
#[must_use]
pub const fn new() -> Self {
Self { exercise: None, repetitions: None, weight: None, weight_unit: None }
}
#[must_use]
pub const fn exercise(mut self, exercise: Exercise) -> Self {
self.exercise = Some(exercise);
self
}
#[must_use]
pub const fn repetitions(mut self, repetitions: u16) -> Self {
self.repetitions = Some(repetitions);
self
}
#[must_use]
pub fn weight_kilograms(self, kilograms: f64) -> Self {
self.weight(kilograms, KILOGRAM)
}
#[must_use]
pub fn weight_pounds(self, pounds: f64) -> Self {
self.weight(pounds * 0.453_592_37, POUND)
}
fn weight(mut self, kilograms: f64, unit: u16) -> Self {
let raw = scaled(kilograms, 16.0, u32::from(u16::MAX));
self.weight = Some(u16::try_from(raw).unwrap_or(u16::MAX));
self.weight_unit = Some(unit);
self
}
}
const KILOGRAM: u16 = 1;
const POUND: u16 = 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LengthMsg {
pub span: Span,
pub swum: Option<Length>,
pub avg_speed: Option<u16>,
pub cadence: Option<u8>,
}
impl LengthMsg {
pub const SWUM: &'static [u8] = &[5, 6, 7, 9];
}
impl Message for LengthMsg {
const GLOBAL: u16 = 101;
const FIELDS: &'static [FieldDef] = &[
field(MESSAGE_INDEX, 2, base::UINT16),
field(TIMESTAMP, 4, base::UINT32),
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), ];
fn timestamp(&self) -> Option<Timestamp> {
Some(self.span.timestamp)
}
fn encode(&self, out: &mut dyn FieldOut, index: u16) {
const IDLE: u8 = 0;
const ACTIVE: u8 = 1;
let span = &self.span;
out.u16(index);
out.u32(span.timestamp.fit());
out.u8(event::LENGTH);
out.u8(event::STOP);
out.u32(span.start_time.fit());
out.u32(span.total_elapsed_ms);
out.u32(span.total_timer_ms);
out.opt_u16(self.swum.and_then(|l| l.strokes));
out.opt_u16(self.avg_speed);
out.opt_u8(self.swum.map(|l| l.stroke.get()));
out.opt_u8(self.cadence);
out.u8(if self.swum.is_some() { ACTIVE } else { IDLE });
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SetMsg {
pub start_time: Timestamp,
pub timestamp: Timestamp,
pub duration_ms: u32,
pub set: Option<Set>,
}
impl SetMsg {
pub const ACTIVE: &'static [u8] = &[3, 4, 7, 8, 9];
}
impl Message for SetMsg {
const GLOBAL: u16 = 225;
const FIELDS: &'static [FieldDef] = &[
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), ];
fn timestamp(&self) -> Option<Timestamp> {
None
}
fn encode(&self, out: &mut dyn FieldOut, index: u16) {
const REST: u8 = 0;
const ACTIVE: u8 = 1;
let set = self.set.unwrap_or_default();
let exercise = set.exercise;
out.u32(self.timestamp.fit());
out.u32(self.duration_ms);
out.opt_u16(set.repetitions);
out.opt_u16(set.weight);
out.u8(if self.set.is_some() { ACTIVE } else { REST });
out.u32(self.start_time.fit());
out.u16s(exercise.as_ref().map(|e| e.category.get()).as_slice());
out.u16s(exercise.and_then(|e| e.name).as_slice());
out.opt_u16(set.weight_unit);
out.u16(index);
}
}
pub(crate) const HRV_BEATS: usize = 5;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Hrv<'a>(pub &'a [u16]);
impl Message for Hrv<'_> {
const GLOBAL: u16 = 78;
#[allow(clippy::cast_possible_truncation, reason = "five two-byte values")]
const FIELDS: &'static [FieldDef] = &[field(0, HRV_BEATS as u8 * 2, base::UINT16)];
fn timestamp(&self) -> Option<Timestamp> {
None
}
fn encode(&self, out: &mut dyn FieldOut, _: u16) {
out.u16s(self.0);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Activity {
timestamp: Timestamp,
total_timer_ms: u32,
num_sessions: u16,
utc_offset: Option<i32>,
auto_multisport: bool,
}
impl Activity {
#[must_use]
pub const fn new(timestamp: Timestamp, total_timer_ms: u32) -> Self {
Self {
timestamp,
total_timer_ms,
num_sessions: 1,
utc_offset: None,
auto_multisport: false,
}
}
#[must_use]
pub const fn auto_multisport(mut self, auto: bool) -> Self {
self.auto_multisport = auto;
self
}
#[must_use]
pub const fn sessions(mut self, num_sessions: u16) -> Self {
self.num_sessions = num_sessions;
self
}
#[must_use]
pub const fn utc_offset(mut self, seconds: i32) -> Self {
self.utc_offset = Some(seconds);
self
}
fn local_timestamp(&self) -> Option<u32> {
let offset = self.utc_offset?;
Some(self.timestamp.fit().checked_add_signed(offset).unwrap_or(INVALID_U32))
}
}
impl Message for Activity {
const GLOBAL: u16 = 34;
const FIELDS: &'static [FieldDef] = &[
field(TIMESTAMP, 4, base::UINT32),
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), ];
fn timestamp(&self) -> Option<Timestamp> {
Some(self.timestamp)
}
fn encode(&self, out: &mut dyn FieldOut, _: u16) {
const MANUAL: u8 = 0;
const AUTO_MULTI_SPORT: u8 = 1;
out.u32(self.timestamp.fit());
out.u32(self.total_timer_ms);
out.u16(self.num_sessions);
out.u8(if self.auto_multisport { AUTO_MULTI_SPORT } else { MANUAL });
out.u8(event::ACTIVITY);
out.u8(event::STOP);
out.opt_u32(self.local_timestamp());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{
ExerciseCategory, FileType, Manufacturer, Sport, SubSport, SwimStroke, Timestamp,
};
use std::vec;
struct VecPut(std::vec::Vec<u8>);
impl Put for VecPut {
fn put(&mut self, bytes: &[u8]) {
self.0.extend_from_slice(bytes);
}
}
struct Count(usize);
impl FieldOut for Count {
fn u8(&mut self, _: u8) {
self.0 += 1;
}
fn u16(&mut self, _: u16) {
self.0 += 1;
}
fn u32(&mut self, _: u32) {
self.0 += 1;
}
fn i8(&mut self, _: i8) {
self.0 += 1;
}
fn i32(&mut self, _: i32) {
self.0 += 1;
}
fn str(&mut self, _: &str) {
self.0 += 1;
}
fn u16s(&mut self, _: &[u16]) {
self.0 += 1;
}
fn bytes(&mut self, _: &[u8]) {
self.0 += 1;
}
fn none(&mut self) {
self.0 += 1;
}
}
fn refused<M: Message>(msg: &M, index: u16) -> Option<FieldError> {
let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
msg.encode(&mut fields, index);
fields.refused()
}
fn bytes<M: Message>(msg: &M, index: u16) -> std::vec::Vec<u8> {
let mut count = Count(0);
msg.encode(&mut count, index);
assert_eq!(count.0, M::FIELDS.len(), "{}: a value per field", M::GLOBAL);
let mut out = VecPut(vec![]);
let mut fields = Fields::new(M::FIELDS.iter().copied(), Some(&mut out));
msg.encode(&mut fields, index);
assert_eq!(fields.refused(), None);
fields.finish();
assert_eq!(u32::try_from(out.0.len()).unwrap(), data_len(M::FIELDS.iter().copied()));
out.0
}
const T: Timestamp = Timestamp::from_fit(0x1122_3344);
const T2: Timestamp = Timestamp::from_fit(0x1122_3380);
#[rustfmt::skip]
const NO_TOTALS: [u8; 63] = [
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, ];
fn totals() -> Totals {
let p = |lat, long| Position::from_semicircles(lat, long);
Totals {
start: p(1, -2),
end: p(3, -4),
north_east: p(5, -6),
south_west: p(7, -8),
distance: Some(0x0102_0304),
avg_speed: Some(0x0506),
max_speed: Some(0x0708),
avg_cadence: Some(9),
max_cadence: Some(10),
avg_power: Some(0x0B0C),
max_power: Some(0x0D0E),
ascent: Some(0x0F10),
descent: Some(0x1112),
avg_temperature: Some(-13),
max_temperature: Some(14),
cycles: Some(0x1314_1516),
lengths: Some(0x1718),
active_lengths: Some(0x191A),
stroke_distance: Some(0x1B1C),
swim_stroke: Some(SwimStroke::new(0x1D)),
}
}
#[rustfmt::skip]
const TOTALS: [u8; 63] = [
1, 0, 0, 0, 0xFE, 0xFF, 0xFF, 0xFF,
3, 0, 0, 0, 0xFC, 0xFF, 0xFF, 0xFF,
0x04, 0x03, 0x02, 0x01,
0x06, 0x05, 0x08, 0x07,
9, 10,
0x0C, 0x0B, 0x0E, 0x0D,
0x10, 0x0F, 0x12, 0x11,
5, 0, 0, 0, 0xFA, 0xFF, 0xFF, 0xFF,
7, 0, 0, 0, 0xF8, 0xFF, 0xFF, 0xFF,
0xF3, 14,
0x16, 0x15, 0x14, 0x13,
0x18, 0x17, 0x1A, 0x19,
0x1C, 0x1B, 0x1D,
];
#[test]
fn a_value_just_under_a_half_rounds_down() {
let under = 0.499_999_999_999_999_94;
assert_eq!(scaled(under, 1.0, 100), 0);
assert_eq!(scaled(0.5, 1.0, 100), 1);
}
#[test]
fn file_id() {
let id = FileId::new(FileType::ACTIVITY, Manufacturer::DEVELOPMENT, 0x0102, T)
.serial_number(0xAABB_CCDD);
assert_eq!(
bytes(&id, 0),
[4, 0xFF, 0x00, 0x02, 0x01, 0xDD, 0xCC, 0xBB, 0xAA, 0x44, 0x33, 0x22, 0x11]
);
let no_serial = FileId::new(FileType::new(9), Manufacturer::new(1), 2, T);
assert_eq!(bytes(&no_serial, 0), [9, 1, 0, 2, 0, 0, 0, 0, 0, 0x44, 0x33, 0x22, 0x11]);
assert_eq!(id.timestamp(), None);
}
#[test]
fn device_info() {
let info = DeviceInfo::new(T)
.device_index(2)
.manufacturer(Manufacturer::new(0x0304))
.serial_number(7)
.product(0x0506)
.software_version(123)
.product_name("Watch");
let mut want = vec![0x44, 0x33, 0x22, 0x11, 2, 0x04, 0x03, 7, 0, 0, 0, 0x06, 0x05, 123, 0];
want.extend_from_slice(b"Watch");
want.resize(want.len() + 15, 0);
assert_eq!(bytes(&info, 0), want);
assert_eq!(info.timestamp(), Some(T));
let mut empty =
vec![0x44, 0x33, 0x22, 0x11, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF];
empty.resize(empty.len() + 20, 0);
assert_eq!(bytes(&DeviceInfo::new(T), 0), empty);
}
#[test]
fn product_name_limit() {
let longest = "0123456789abcdefghi";
assert_eq!(longest.len(), PRODUCT_NAME_MAX);
let out = bytes(&DeviceInfo::new(T).product_name(longest), 0);
assert_eq!(out.last(), Some(&0));
let long = DeviceInfo::new(T).product_name("0123456789abcdefghij");
assert_eq!(refused(&long, 0), Some(FieldError::StringTooLong));
}
#[test]
fn events() {
let t = [0x44, 0x33, 0x22, 0x11];
assert_eq!(bytes(&Event::timer_start(T), 0), [&t[..], &[0, 0]].concat());
assert_eq!(bytes(&Event::timer_stop(T), 0), [&t[..], &[0, 1]].concat());
assert_eq!(bytes(&Event::timer_stop_all(T), 0), [&t[..], &[0, 4]].concat());
assert_eq!(Event::timer_start(T).timestamp(), Some(T));
}
#[test]
fn lap() {
let lap = Lap::new(T, T2, 0x0001_0203, 0x0004_0506)
.heart_rate(120, 150)
.sport(Sport::RUNNING, SubSport::TREADMILL);
let out = bytes(&lap, 0x0102);
assert_eq!(
out[..24],
[
0x02, 0x01, 0x80, 0x33, 0x22, 0x11, 9, 1, 0x44, 0x33, 0x22, 0x11, 0x03, 0x02, 0x01,
0x00, 0x06, 0x05, 0x04, 0x00, 120, 150, 1, 1
]
);
assert_eq!(out[24], lap_trigger::MANUAL);
assert_eq!(out[25..88], NO_TOTALS);
assert_eq!(out[88..], [0xFF, 0xFF]);
let ended = bytes(&lap.trigger(lap_trigger::SESSION_END), 0x0102);
assert_eq!(ended[24], 7);
let bare = bytes(&Lap::new(T, T2, 0, 0), 0);
assert_eq!(bare.get(20..24), Some(&[0xFF; 4][..]));
let full = bytes(&lap.totals(totals()).first_length(0x1E1F), 0x0102);
assert_eq!((&full[25..88], &full[88..]), (&TOTALS[..], &[0x1F, 0x1E][..]));
assert_eq!(lap.timestamp(), Some(T2));
}
#[test]
fn session() {
let session = Session::new(T, T2, 0x0001_0203, 0x0004_0506)
.heart_rate(121, 151)
.sport(Sport::TRAINING, SubSport::CARDIO_TRAINING)
.laps(3, 4);
let out = bytes(&session, 5);
assert_eq!(
out[..28],
[
5, 0, 0x80, 0x33, 0x22, 0x11, 8, 1, 0x44, 0x33, 0x22, 0x11, 10, 26, 0x03, 0x02,
0x01, 0x00, 0x06, 0x05, 0x04, 0x00, 121, 151, 3, 0, 4, 0
]
);
assert_eq!(out[28..91], NO_TOTALS);
assert_eq!(out[91..], [0xFF, 0xFF, 0xFF, trigger::ACTIVITY_END]);
let bare = bytes(&Session::new(T, T2, 0, 0), 0);
assert_eq!(bare.get(12..14), Some(&[0xFF; 2][..]));
assert_eq!(bare.get(22..28), Some(&[0xFF, 0xFF, 0, 0, 1, 0][..]));
let full = session.totals(totals()).pool(Pool::yards(25.0)).trigger(trigger::MANUAL);
let full = bytes(&full, 5);
assert_eq!((&full[28..91], &full[91..]), (&TOTALS[..], &[0xEE, 0x08, 1, 1][..]));
assert_eq!(session.timestamp(), Some(T2));
}
#[test]
fn activity() {
let a = Activity::new(T2, 0x0004_0506).sessions(2).utc_offset(-0x80);
assert_eq!(
bytes(&a, 0),
[
0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00, 2, 0, 0, 26, 1, 0x00, 0x33, 0x22,
0x11
]
);
let none = bytes(&Activity::new(T2, 0), 0);
assert_eq!(none.get(8..11), Some(&[1, 0, 0][..]), "one session, manual");
let auto = bytes(&Activity::new(T2, 0).auto_multisport(true), 0);
assert_eq!(auto.get(10), Some(&1), "auto_multi_sport");
assert_eq!(none.get(13..), Some(&[0xFF; 4][..]));
assert_eq!(a.timestamp(), Some(T2));
}
#[test]
fn sports() {
let named = SportMsg { sport: Sport::new(5), sub_sport: SubSport::new(18), name: "Swim" };
let mut want = [0u8; 26];
want[..6].copy_from_slice(&[5, 18, b'S', b'w', b'i', b'm']);
assert_eq!(bytes(&named, 0), want);
let unnamed = bytes(&SportMsg { name: "", ..named }, 0);
assert_eq!(unnamed, [&[5, 18][..], &[0; 24]].concat(), "a string's none");
let long = "a name of twenty-four by";
assert_eq!(long.len(), SPORT_NAME_MAX + 1);
assert_eq!(refused(&SportMsg { name: long, ..named }, 0), Some(FieldError::StringTooLong));
assert_eq!(named.timestamp(), None);
}
#[test]
fn local_timestamp_out_of_range_is_refused() {
let at = |t: u32, offset: i32| Activity::new(Timestamp::from_fit(t), 0).utc_offset(offset);
assert_eq!(at(10, -11).local_timestamp(), Some(INVALID_U32));
assert_eq!(at(10, -10).local_timestamp(), Some(0));
assert_eq!(at(u32::MAX - 1, 1).local_timestamp(), Some(INVALID_U32));
assert_eq!(at(u32::MAX - 2, 1).local_timestamp(), Some(u32::MAX - 1));
assert_eq!(at(100, 3600).local_timestamp(), Some(3700));
assert_eq!(Activity::new(T, 0).local_timestamp(), None);
assert_eq!(refused(&at(10, -11), 0), Some(FieldError::OutOfRange));
}
#[test]
fn record_layouts() {
assert_eq!(Record::new(T).heart_rate(99).fields(), RecordFields::HEART_RATE);
assert_eq!(Record::new(T).fields(), RecordFields(0));
assert_eq!(record_fields(RecordFields(0)).count(), 0);
let mut all = Record::new(T)
.position(Position::from_semicircles(1, 2).unwrap())
.altitude(Altitude::smoothed_meters(0.0))
.heart_rate(3)
.cadence_rpm(4)
.speed_meters_per_second(6.0)
.power_watts(7)
.temperature_celsius(-8);
all.distance = Some(500);
let defs: std::vec::Vec<FieldDef> = record_fields(all.fields()).collect();
assert_eq!(defs.len(), 9);
let mut out = VecPut(vec![]);
let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
all.encode(&mut fields);
assert_eq!(fields.refused(), None);
fields.finish();
#[rustfmt::skip]
let want = [
1, 0, 0, 0, 2, 0, 0, 0, 0xC4, 0x09, 3, 4,
0xF4, 0x01, 0, 0, 0x70, 0x17, 7, 0,
0xF8, ];
assert_eq!(out.0, want);
assert_eq!(
record_fields(RecordFields::HEART_RATE).collect::<std::vec::Vec<_>>(),
[field(3, 1, base::UINT8)]
);
assert!(!RecordFields(0).contains(RecordFields::HEART_RATE));
assert!(RecordFields::HEART_RATE.contains(RecordFields(0)));
}
#[test]
fn values_fill_their_fields_exactly() {
let defs = [
field(0, 2, base::UINT16),
field(1, 1, base::UINT8),
field(2, 3, base::STRING),
field(3, 4, base::UINT32Z),
field(4, 2, base::UINT16),
field(5, 1, base::ENUM),
];
let mut out = VecPut(vec![]);
let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
fields.u8(7);
fields.u32(9);
fields.str("ab");
fields.none();
fields.finish();
assert_eq!(
fields_refused(&defs, |f| {
f.u8(7);
f.u32(9);
}),
None
);
assert_eq!(out.0, [7, 0, 9, b'a', b'b', 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF]);
let mut out = VecPut(vec![]);
let mut fields = Fields::new([field(0, 1, base::UINT8)].into_iter(), Some(&mut out));
fields.u8(1);
fields.u8(2);
fields.str("x");
fields.none();
fields.finish();
assert_eq!(out.0, [1], "values past the table are dropped");
}
fn fields_refused(
defs: &[FieldDef],
f: impl Fn(&mut Fields<'_, core::iter::Copied<core::slice::Iter<'_, FieldDef>>>),
) -> Option<FieldError> {
let mut fields = Fields::new(defs.iter().copied(), None);
f(&mut fields);
fields.refused()
}
#[test]
fn a_value_that_is_none_or_too_wide_is_refused() {
let s8 = [field(0, 1, base::SINT8)];
let s32 = [field(0, 4, base::SINT32)];
assert_eq!(fields_refused(&s8, |f| f.i8(i8::MAX)), Some(FieldError::OutOfRange));
assert_eq!(fields_refused(&s8, |f| f.i8(-1)), None);
assert_eq!(fields_refused(&s32, |f| f.i32(i32::MAX)), Some(FieldError::OutOfRange));
assert_eq!(fields_refused(&s32, |f| f.i32(-1)), None);
let u8_ = [field(0, 1, base::UINT8)];
let u16_ = [field(0, 2, base::UINT16)];
let z = [field(0, 4, base::UINT32Z)];
let e = Some(FieldError::OutOfRange);
assert_eq!(fields_refused(&u8_, |f| f.u8(0xFF)), e);
assert_eq!(fields_refused(&u8_, |f| f.u8(0xFE)), None);
assert_eq!(fields_refused(&u8_, |f| f.u16(0x0100)), e);
assert_eq!(fields_refused(&u8_, |f| f.u16(0x00FE)), None);
assert_eq!(fields_refused(&u16_, |f| f.u16(0xFFFF)), e);
assert_eq!(fields_refused(&u16_, |f| f.u8(0xFF)), None, "widened, it is 0x00FF");
assert_eq!(fields_refused(&z, |f| f.u32(0)), e);
assert_eq!(fields_refused(&z, |f| f.u32(u32::MAX)), None);
assert_eq!(fields_refused(&z, |f| f.none()), None);
let two = [field(0, 1, base::STRING), field(1, 1, base::UINT8)];
assert_eq!(
fields_refused(&two, |f| {
f.str("x");
f.u8(0xFF);
}),
Some(FieldError::StringTooLong)
);
}
#[test]
fn messages_refuse_none_as_a_value() {
let e = Some(FieldError::OutOfRange);
let id = |t| FileId::new(t, Manufacturer::DEVELOPMENT, 1, T);
assert_eq!(refused(&id(FileType::new(255)), 0), e);
assert_eq!(refused(&id(FileType::ACTIVITY).serial_number(0), 0), e);
assert_eq!(
refused(&FileId::new(FileType::ACTIVITY, Manufacturer::new(0xFFFF), 1, T), 0),
e
);
assert_eq!(refused(&DeviceInfo::new(T).product(0xFFFF), 0), e);
assert_eq!(refused(&Event::timer_start(Timestamp::from_fit(u32::MAX)), 0), e);
let lap = Lap::new(T, T2, 0, 0);
assert_eq!(refused(&lap.heart_rate(255, 255), 0), e);
assert_eq!(refused(&lap.sport(Sport::new(255), SubSport::GENERIC), 0), e);
assert_eq!(refused(&Lap::new(T, T2, u32::MAX, 0), 0), e);
assert_eq!(
refused(&Session::new(T, T2, 0, 0).sport(Sport::RUNNING, SubSport::new(255)), 0),
e
);
assert_eq!(
refused(&lap.heart_rate(254, 254).sport(Sport::new(254), SubSport::new(254)), 0),
None
);
}
#[test]
fn masks_hold_any_field_of_a_definition() {
let mut m = Mask::EMPTY;
for i in [0, 63, 64, 200, 255] {
assert!(!m.contains(i));
m.insert(i);
assert!(m.contains(i));
}
assert!(!m.contains(1) && !m.contains(65) && !m.contains(256));
m.insert(256);
assert!(!m.contains(256), "past a definition's last field");
let rest = Mask::ALL.without(m);
assert!(!rest.contains(64) && rest.contains(65) && rest.contains(254));
let defs = [field(1, 1, base::UINT8), field(2, 2, base::UINT16), field(3, 1, base::UINT8)];
let mut keep = Mask::EMPTY;
keep.insert(0);
keep.insert(2);
assert_eq!(
kept(defs.into_iter(), keep).map(|f| f.num).collect::<std::vec::Vec<_>>(),
[1, 3]
);
}
#[test]
fn a_message_keeps_the_fields_it_has_values_for() {
let mut fields = Fields::new(DeviceInfo::FIELDS.iter().copied(), None);
DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
let present = fields.present();
let kept: std::vec::Vec<u8> =
kept(DeviceInfo::FIELDS.iter().copied(), present).map(|f| f.num).collect();
assert_eq!(kept, [TIMESTAMP, 0, 27], "timestamp, device_index and product_name");
let mut out = VecPut(vec![]);
let mut fields =
Fields::new(DeviceInfo::FIELDS.iter().copied(), Some(&mut out)).keep(present);
DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
fields.finish();
assert_eq!(out.0.len(), 4 + 1 + 20);
}
#[test]
fn lengths() {
let span = Span {
start_time: T,
timestamp: T2,
total_elapsed_ms: 0x0001_0203,
total_timer_ms: 0x0004_0506,
};
let swum = LengthMsg {
span,
swum: Some(Length::swum(SwimStroke::BACKSTROKE, 0x0708)),
avg_speed: Some(0x090A),
cadence: Some(11),
};
#[rustfmt::skip]
let want = [
3, 0, 0x80, 0x33, 0x22, 0x11, 28, 1, 0x44, 0x33, 0x22, 0x11,
0x03, 0x02, 0x01, 0x00, 0x06, 0x05, 0x04, 0x00,
0x08, 0x07, 0x0A, 0x09, 1, 11, 1,
];
assert_eq!(bytes(&swum, 3), want);
let idle = LengthMsg { span, swum: None, avg_speed: None, cadence: None };
let out = bytes(&idle, 3);
assert_eq!((&out[20..26], out[26]), (&[0xFF; 6][..], 0));
let drill = LengthMsg { swum: Some(Length::drill()), ..idle };
assert_eq!(&bytes(&drill, 3)[20..], [0xFF, 0xFF, 0xFF, 0xFF, 4, 0xFF, 1]);
assert_eq!(idle.timestamp(), Some(T2));
}
#[test]
fn sets() {
let set = Set::new()
.exercise(Exercise::new(ExerciseCategory::SQUAT).name(0x0102))
.repetitions(10)
.weight_pounds(100.0);
let msg = SetMsg { start_time: T, timestamp: T2, duration_ms: 0x0004_0506, set: Some(set) };
#[rustfmt::skip]
let want = [
0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00,
10, 0, 0xD6, 0x02, 1, 0x44, 0x33, 0x22, 0x11, 28, 0, 0x02, 0x01, 2, 0, 7, 0,
];
assert_eq!(bytes(&msg, 7), want);
let rest = SetMsg { set: None, ..msg };
let out = bytes(&rest, 7);
assert_eq!((&out[8..12], out[12]), (&[0xFF; 4][..], 0));
assert_eq!(&out[17..23], &[0xFF; 6][..]);
let unnamed = SetMsg {
set: Some(Set::new().exercise(Exercise::new(ExerciseCategory::new(1)))),
..msg
};
assert_eq!(&bytes(&unnamed, 7)[17..21], [1, 0, 0xFF, 0xFF]);
assert_eq!(Set::new().weight_kilograms(60.0).weight, Some(960));
assert_eq!(Set::new().weight_kilograms(60.0).weight_unit, Some(1));
assert_eq!(Set::new().weight_kilograms(4095.875).weight, Some(65_534));
assert_eq!(Set::new().weight_kilograms(-1.0).weight, Some(u16::MAX));
}
#[test]
fn pools() {
assert_eq!(Pool::meters(25.0), Pool { centimetres: 2500, unit: 0 });
assert_eq!(Pool::yards(25.0), Pool { centimetres: 2286, unit: 1 });
assert_eq!(Pool::meters(33.333), Pool { centimetres: 3333, unit: 0 });
assert_eq!(Pool::meters(1000.0).centimetres, u16::MAX);
}
#[test]
fn pool_limits_hold_once_rounded() {
let check = |pool| Leg::pool_swim(pool).check();
for (largest, pool) in [
(655.344_999_999_999_9, Pool::meters as fn(f64) -> Pool),
(716.694_006_999_125, Pool::yards),
] {
assert_eq!(pool(largest).centimetres, 65_534);
assert_eq!(check(pool(largest)), Ok(()));
assert_eq!(check(pool(largest.next_up())), Err(crate::Error::OutOfRange));
}
assert_eq!(check(Pool::meters(0.005)), Ok(()));
assert_eq!(check(Pool::meters(0.004_999_999_999_999_998)), Err(crate::Error::OutOfRange));
}
#[test]
fn speed_and_weight_limits_hold_once_rounded() {
let speed = |s| Record::new(Timestamp::from_fit(0)).speed_meters_per_second(s).speed;
assert_eq!(speed(65.5345), Some(65_534));
assert_eq!(speed(65.5345_f64.next_up()), Some(u16::MAX));
let kg = |k| Set::new().weight_kilograms(k).weight;
assert_eq!(kg(4_095.906_249_999_999_5), Some(65_534));
assert_eq!(kg(4_095.906_25), Some(u16::MAX));
let lb = |p| Set::new().weight_pounds(p).weight;
assert_eq!(lb(9_029.927_575_721_786), Some(65_534));
assert_eq!(lb(9_029.927_575_721_787), Some(u16::MAX));
}
#[test]
fn beat_intervals_fill_five_slots() {
let out = bytes(&Hrv(&[0x0102, 0x0304]), 0);
assert_eq!(out, [0x02, 0x01, 0x04, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
assert_eq!(bytes(&Hrv(&[1, 2, 3, 4, 5]), 0), [1, 0, 2, 0, 3, 0, 4, 0, 5, 0]);
assert_eq!(refused(&Hrv(&[1, 2, 3, 4, 5, 6]), 0), Some(FieldError::OutOfRange));
assert_eq!(refused(&Hrv(&[1, u16::MAX]), 0), Some(FieldError::OutOfRange));
assert_eq!(bytes(&Hrv(&[]), 0), [0xFF; 10], "none");
assert_eq!(Hrv(&[]).timestamp(), None);
}
#[test]
fn bytes_fill_their_field_exactly() {
let defs = [field(0, 2, base::BYTE)];
let e = Some(FieldError::OutOfRange);
assert_eq!(fields_refused(&defs, |f| f.bytes(&[1, 2, 3])), e);
assert_eq!(fields_refused(&defs, |f| f.bytes(&[1])), e);
assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0xFF])), e);
assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0])), None);
}
#[test]
fn strings_need_room_for_their_nul() {
let defs = [field(0, 3, base::STRING)];
let mut fields = Fields::new(defs.into_iter(), None);
fields.str("abc");
assert_eq!(fields.refused(), Some(FieldError::StringTooLong));
let mut fields = Fields::new(defs.into_iter(), None);
fields.str("ab");
assert_eq!(fields.refused(), None);
}
#[test]
fn strings_hold_no_nul() {
let defs = [field(0, 8, base::STRING)];
for s in ["a\0b", "\0", "ab\0"] {
let mut fields = Fields::new(defs.into_iter(), None);
fields.str(s);
assert_eq!(fields.refused(), Some(FieldError::OutOfRange), "{s:?}");
}
}
}