pub const FIT_EPOCH_UNIX: i64 = 631_065_600;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(u32);
impl Timestamp {
pub const FIRST_DATE: Self = Self(0x1000_0000);
#[must_use]
pub const fn from_fit(seconds: u32) -> Self {
Self(seconds)
}
#[must_use]
pub const fn from_unix(seconds: i64) -> Option<Self> {
let Some(fit) = seconds.checked_sub(FIT_EPOCH_UNIX) else {
return None;
};
if fit < Self::FIRST_DATE.0 as i64 || fit >= u32::MAX as i64 {
return None;
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Some(Self(fit as u32))
}
#[cfg(feature = "std")]
#[must_use]
pub fn from_system_time(t: std::time::SystemTime) -> Option<Self> {
let unix = t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
Self::from_unix(i64::try_from(unix).ok()?)
}
#[must_use]
pub const fn fit(self) -> u32 {
self.0
}
#[must_use]
pub const fn unix(self) -> i64 {
(self.0 as i64).wrapping_add(FIT_EPOCH_UNIX)
}
#[must_use]
pub const fn checked_add(self, seconds: u32) -> Option<Self> {
match self.0.checked_add(seconds) {
Some(t) if t != u32::MAX => Some(Self(t)),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Position {
lat: i32,
long: i32,
}
const SEMICIRCLES_PER_DEGREE: f64 = 2_147_483_648.0 / 180.0;
impl Position {
#[must_use]
pub fn from_degrees(lat: f64, long: f64) -> Option<Self> {
if !((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&long)) {
return None;
}
Self::from_semicircles(
round(lat * SEMICIRCLES_PER_DEGREE)?,
round(long * SEMICIRCLES_PER_DEGREE).filter(|&l| l != i32::MAX).unwrap_or(i32::MIN),
)
}
#[must_use]
pub const fn from_semicircles(lat: i32, long: i32) -> Option<Self> {
const QUARTER: i32 = 1 << 30;
if lat == i32::MAX || long == i32::MAX || lat > QUARTER || lat < -QUARTER {
return None;
}
Some(Self { lat, long })
}
#[must_use]
pub const fn semicircles(self) -> (i32, i32) {
(self.lat, self.long)
}
#[must_use]
pub fn degrees(self) -> (f64, f64) {
(
f64::from(self.lat) / SEMICIRCLES_PER_DEGREE,
f64::from(self.long) / SEMICIRCLES_PER_DEGREE,
)
}
}
fn round(x: f64) -> Option<i32> {
let r = if x.is_sign_negative() { x - 0.5 } else { x + 0.5 };
if !(r > -2_147_483_649.0 && r < 2_147_483_648.0) {
return None;
}
#[allow(clippy::cast_possible_truncation)]
Some(r as i32)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Manufacturer(u16);
impl Manufacturer {
pub const DEVELOPMENT: Self = Self(255);
#[must_use]
pub const fn new(id: u16) -> Self {
Self(id)
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BaseType(u8);
impl BaseType {
pub const ENUM: Self = Self(0x00);
pub const SINT8: Self = Self(0x01);
pub const UINT8: Self = Self(0x02);
pub const STRING: Self = Self(0x07);
pub const UINT8Z: Self = Self(0x0A);
pub const BYTE: Self = Self(0x0D);
pub const SINT16: Self = Self(0x83);
pub const UINT16: Self = Self(0x84);
pub const SINT32: Self = Self(0x85);
pub const UINT32: Self = Self(0x86);
pub const FLOAT32: Self = Self(0x88);
pub const FLOAT64: Self = Self(0x89);
pub const UINT16Z: Self = Self(0x8B);
pub const UINT32Z: Self = Self(0x8C);
pub const SINT64: Self = Self(0x8E);
pub const UINT64: Self = Self(0x8F);
pub const UINT64Z: Self = Self(0x90);
pub(crate) const fn from_byte(base: u8) -> Self {
Self(base)
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
#[must_use]
pub const fn size(self) -> u8 {
match self.0 & 0x1F {
0x03 | 0x04 | 0x0B => 2,
0x05 | 0x06 | 0x08 | 0x0C => 4,
0x09 | 0x0E | 0x0F | 0x10 => 8,
_ => 1,
}
}
}
macro_rules! profile_enum {
($(#[$doc:meta])* $ty:ident { $($name:ident = $value:literal, $profile:literal;)* }) => {
profile_enum! { $(#[$doc])* $ty(u8) { $($name = $value, $profile;)* } }
};
($(#[$doc:meta])* $ty:ident($repr:ty) { $($name:ident = $value:literal, $profile:literal;)* }) => {
$(#[$doc])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct $ty($repr);
#[allow(dead_code, reason = "FileType is not exported")]
impl $ty {
$(
#[doc = concat!("`", $profile, "` (", stringify!($value), ").")]
pub const $name: Self = Self($value);
)*
#[doc = concat!("Any value. ", stringify!($repr), "::MAX is FIT's \"none\", which the encoder refuses to write.")]
#[must_use]
pub const fn new(value: $repr) -> Self {
Self(value)
}
#[must_use]
pub const fn get(self) -> $repr {
self.0
}
#[must_use]
pub const fn name(self) -> Option<&'static str> {
match self.0 {
$($value => Some($profile),)*
_ => None,
}
}
}
impl core::fmt::Display for $ty {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "{}", self.0),
}
}
}
};
}
profile_enum! {
FileType {
ACTIVITY = 4, "activity";
}
}
profile_enum! {
Sport {
GENERIC = 0, "generic";
RUNNING = 1, "running";
CYCLING = 2, "cycling";
TRANSITION = 3, "transition";
FITNESS_EQUIPMENT = 4, "fitness_equipment";
SWIMMING = 5, "swimming";
TRAINING = 10, "training";
WALKING = 11, "walking";
ROWING = 15, "rowing";
HIKING = 17, "hiking";
HIIT = 62, "hiit";
}
}
profile_enum! {
SubSport {
GENERIC = 0, "generic";
TREADMILL = 1, "treadmill";
STREET = 2, "street";
TRAIL = 3, "trail";
TRACK = 4, "track";
SPIN = 5, "spin";
INDOOR_CYCLING = 6, "indoor_cycling";
ROAD = 7, "road";
MOUNTAIN = 8, "mountain";
INDOOR_ROWING = 14, "indoor_rowing";
ELLIPTICAL = 15, "elliptical";
STAIR_CLIMBING = 16, "stair_climbing";
LAP_SWIMMING = 17, "lap_swimming";
OPEN_WATER = 18, "open_water";
STRENGTH_TRAINING = 20, "strength_training";
CARDIO_TRAINING = 26, "cardio_training";
INDOOR_WALKING = 27, "indoor_walking";
BIKE_TO_RUN_TRANSITION = 32, "bike_to_run_transition";
RUN_TO_BIKE_TRANSITION = 33, "run_to_bike_transition";
SWIM_TO_BIKE_TRANSITION = 34, "swim_to_bike_transition";
INDOOR_RUNNING = 45, "indoor_running";
}
}
profile_enum! {
SwimStroke {
FREESTYLE = 0, "freestyle";
BACKSTROKE = 1, "backstroke";
BREASTSTROKE = 2, "breaststroke";
BUTTERFLY = 3, "butterfly";
DRILL = 4, "drill";
MIXED = 5, "mixed";
IM = 6, "im";
}
}
profile_enum! {
ExerciseCategory(u16) {
BENCH_PRESS = 0, "bench_press";
CALF_RAISE = 1, "calf_raise";
CARDIO = 2, "cardio";
CARRY = 3, "carry";
CHOP = 4, "chop";
CORE = 5, "core";
CRUNCH = 6, "crunch";
CURL = 7, "curl";
DEADLIFT = 8, "deadlift";
FLYE = 9, "flye";
HIP_RAISE = 10, "hip_raise";
HIP_STABILITY = 11, "hip_stability";
HIP_SWING = 12, "hip_swing";
HYPEREXTENSION = 13, "hyperextension";
LATERAL_RAISE = 14, "lateral_raise";
LEG_CURL = 15, "leg_curl";
LEG_RAISE = 16, "leg_raise";
LUNGE = 17, "lunge";
OLYMPIC_LIFT = 18, "olympic_lift";
PLANK = 19, "plank";
PLYO = 20, "plyo";
PULL_UP = 21, "pull_up";
PUSH_UP = 22, "push_up";
ROW = 23, "row";
SHOULDER_PRESS = 24, "shoulder_press";
SHOULDER_STABILITY = 25, "shoulder_stability";
SHRUG = 26, "shrug";
SIT_UP = 27, "sit_up";
SQUAT = 28, "squat";
TOTAL_BODY = 29, "total_body";
TRICEPS_EXTENSION = 30, "triceps_extension";
WARM_UP = 31, "warm_up";
RUN = 32, "run";
BIKE = 33, "bike";
CARDIO_SENSORS = 34, "cardio_sensors";
MOVE = 35, "move";
POSE = 36, "pose";
BANDED_EXERCISES = 37, "banded_exercises";
BATTLE_ROPE = 38, "battle_rope";
ELLIPTICAL = 39, "elliptical";
FLOOR_CLIMB = 40, "floor_climb";
INDOOR_BIKE = 41, "indoor_bike";
INDOOR_ROW = 42, "indoor_row";
LADDER = 43, "ladder";
SANDBAG = 44, "sandbag";
SLED = 45, "sled";
SLEDGE_HAMMER = 46, "sledge_hammer";
STAIR_STEPPER = 47, "stair_stepper";
SUSPENSION = 49, "suspension";
TIRE = 50, "tire";
RUN_INDOOR = 52, "run_indoor";
BIKE_OUTDOOR = 53, "bike_outdoor";
UNKNOWN = 65534, "unknown";
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::string::ToString;
#[test]
fn unix_and_fit_epochs() {
let first = FIT_EPOCH_UNIX + 0x1000_0000;
assert_eq!(first, 899_501_056, "1998-07-03T21:24:16Z");
assert_eq!(Timestamp::from_unix(first), Some(Timestamp::FIRST_DATE));
assert_eq!(Timestamp::from_unix(first - 1), None, "a time since the device started");
assert_eq!(Timestamp::from_unix(FIT_EPOCH_UNIX), None);
assert_eq!(Timestamp::from_unix(FIT_EPOCH_UNIX - 1), None);
assert_eq!(Timestamp::from_unix(i64::MIN), None);
let last = FIT_EPOCH_UNIX + i64::from(u32::MAX - 1);
assert_eq!(Timestamp::from_unix(last), Some(Timestamp::from_fit(u32::MAX - 1)));
assert_eq!(Timestamp::from_unix(last + 1), None);
assert_eq!(Timestamp::from_fit(u32::MAX).unix(), last + 1);
assert_eq!(Timestamp::from_fit(7).fit(), 7);
}
#[test]
fn system_times() {
use std::time::{Duration, UNIX_EPOCH};
let t = UNIX_EPOCH + Duration::from_millis(1_764_547_200_999);
assert_eq!(Timestamp::from_system_time(t), Timestamp::from_unix(1_764_547_200));
assert_eq!(Timestamp::from_system_time(UNIX_EPOCH), None);
let first = UNIX_EPOCH + Duration::from_secs(899_501_056);
assert_eq!(Timestamp::from_system_time(first), Some(Timestamp::FIRST_DATE));
assert_eq!(Timestamp::from_system_time(first - Duration::from_millis(1)), None);
assert_eq!(Timestamp::from_system_time(UNIX_EPOCH - Duration::from_secs(1)), None);
}
#[test]
fn checked_add_stops_at_the_end() {
assert_eq!(Timestamp::from_fit(1).checked_add(2), Some(Timestamp::from_fit(3)));
assert_eq!(Timestamp::from_fit(u32::MAX).checked_add(1), None);
assert_eq!(Timestamp::from_fit(u32::MAX - 1).checked_add(1), None);
assert_eq!(
Timestamp::from_fit(u32::MAX - 2).checked_add(1),
Some(Timestamp::from_fit(u32::MAX - 1))
);
}
#[test]
fn positions() {
let p = Position::from_degrees(45.0, -75.5).unwrap();
assert_eq!(p.semicircles(), (536_870_912, -900_750_086));
let (lat, long) = p.degrees();
assert!((lat - 45.0).abs() < 1e-7 && (long + 75.5).abs() < 1e-7);
assert_eq!(Position::from_degrees(90.0, 0.0).unwrap().semicircles(), (1 << 30, 0));
assert_eq!(
Position::from_degrees(-90.0, 180.0).unwrap().semicircles(),
(-(1 << 30), i32::MIN)
);
let east = |long| Position::from_degrees(0.0, long).map(|p| p.semicircles().1);
assert_eq!(east(179.999_999_85), Some(i32::MAX - 1));
assert_eq!(east(179.999_999_9), Some(i32::MIN));
assert_eq!(east(179.999_999_99), Some(i32::MIN));
assert_eq!(Position::from_degrees(90.1, 0.0), None);
assert_eq!(Position::from_degrees(0.0, -180.1), None);
assert_eq!(Position::from_degrees(0.0, 200.0), None);
assert_eq!(Position::from_degrees(-91.0, 0.0), None);
assert_eq!(Position::from_degrees(f64::NAN, 0.0), None);
assert_eq!(Position::from_degrees(0.0, f64::INFINITY), None);
assert_eq!(Position::from_semicircles(i32::MAX, 0), None);
assert_eq!(Position::from_semicircles(0, i32::MAX), None);
assert_eq!(Position::from_semicircles((1 << 30) + 1, 0), None);
assert_eq!(Position::from_semicircles(-(1 << 30) - 1, 0), None);
assert!(Position::from_semicircles(-(1 << 30), i32::MAX - 1).is_some());
assert_eq!(round(-0.5), Some(-1));
assert_eq!(round(0.49), Some(0));
assert_eq!(round(2_147_483_647.4), Some(i32::MAX));
assert_eq!(round(2_147_483_647.5), None);
assert_eq!(round(-2_147_483_648.4), Some(i32::MIN));
assert_eq!(round(-2_147_483_648.5), None);
assert_eq!(round(f64::NAN), None);
}
#[test]
fn base_type_sizes() {
let sizes = [
(BaseType::ENUM, 1),
(BaseType::SINT8, 1),
(BaseType::UINT8, 1),
(BaseType::STRING, 1),
(BaseType::UINT8Z, 1),
(BaseType::BYTE, 1),
(BaseType::SINT16, 2),
(BaseType::UINT16, 2),
(BaseType::SINT32, 4),
(BaseType::UINT32, 4),
(BaseType::FLOAT32, 4),
(BaseType::FLOAT64, 8),
(BaseType::UINT16Z, 2),
(BaseType::UINT32Z, 4),
(BaseType::SINT64, 8),
(BaseType::UINT64, 8),
(BaseType::UINT64Z, 8),
];
for (base, size) in sizes {
assert_eq!(base.size(), size, "{:#x}", base.get());
assert_eq!(BaseType::from_byte(base.get()), base);
}
}
#[test]
fn identities() {
assert_eq!(Manufacturer::DEVELOPMENT.get(), 255);
assert_eq!(Manufacturer::new(1).get(), 1);
assert_eq!(FileType::ACTIVITY.get(), 4);
assert_eq!(FileType::new(9).get(), 9);
assert_eq!(Sport::new(1), Sport::RUNNING);
assert_eq!(SubSport::new(58).get(), 58);
assert_eq!((Sport::RUNNING.name(), Sport::new(30).name()), (Some("running"), None));
assert_eq!([Sport::CYCLING.to_string(), SubSport::new(58).to_string()], ["cycling", "58"]);
}
}