rustyfit 0.10.0

The #![no_std] Rust implementation of The Flexible and Interoperable Data Transfer (FIT) Protocol for decoding and encoding Garmin FIT files, supporting FIT Protocol V2.
Documentation
// Code generated by fitgen/main.go. DO NOT EDIT.

// Copyright 2025 The RustyFIT Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

use crate::profile::typedef::{self, FitBaseType};
use crate::proto::*;
use alloc::vec::Vec;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};

/// Three D Sensor Calibration message.
#[cfg_attr(feature = "serde", derive(Deserialize), serde(from = "De"))]
#[derive(Debug, Clone)]
pub struct ThreeDSensorCalibration {
    /// Units: s; Whole second part of the timestamp
    pub timestamp: typedef::DateTime,
    /// Indicates which sensor the calibration is for
    pub sensor_type: typedef::SensorType,
    /// Calibration factor used to convert from raw ADC value to degrees, g, etc.
    pub calibration_factor: u32,
    /// Units: counts; Calibration factor divisor
    pub calibration_divisor: u32,
    /// Level shift value used to shift the ADC value back into range
    pub level_shift: u32,
    /// Array: \[3\]; Internal calibration factors, one for each: xy, yx, zx
    pub offset_cal: [i32; 3],
    /// Array: \[9\]; Scale: 65535; 3 x 3 rotation matrix (row major)
    pub orientation_matrix: [i32; 9],
    /// unknown_fields are fields that are exist but they are not defined in Profile.xlsx
    pub unknown_fields: Vec<Field>,
    /// developer_fields are custom data fields (Added since protocol version 2.0)
    pub developer_fields: Vec<DeveloperField>,
}

impl ThreeDSensorCalibration {
    /// Value's type: `u32`; FitBaseType::UINT32; ProfileType::DateTime; Units: `s`
    pub const TIMESTAMP: u8 = 253;
    /// Value's type: `u8`; FitBaseType::ENUM; ProfileType::SensorType
    pub const SENSOR_TYPE: u8 = 0;
    /// Value's type: `u32`; FitBaseType::UINT32; ProfileType::Uint32
    pub const CALIBRATION_FACTOR: u8 = 1;
    /// Value's type: `u32`; FitBaseType::UINT32; ProfileType::Uint32; Units: `counts`
    pub const CALIBRATION_DIVISOR: u8 = 2;
    /// Value's type: `u32`; FitBaseType::UINT32; ProfileType::Uint32
    pub const LEVEL_SHIFT: u8 = 3;
    /// Value's type: `[i32; 3]`; FitBaseType::SINT32; ProfileType::Sint32
    pub const OFFSET_CAL: u8 = 4;
    /// Value's type: `[i32; 9]`; FitBaseType::SINT32; ProfileType::Sint32; Scale: `65535`
    pub const ORIENTATION_MATRIX: u8 = 5;

    /// Create new ThreeDSensorCalibration with all fields being set to its corresponding invalid value.
    pub const fn new() -> Self {
        Self {
            timestamp: typedef::DateTime(u32::MAX),
            sensor_type: typedef::SensorType(u8::MAX),
            calibration_factor: u32::MAX,
            calibration_divisor: u32::MAX,
            level_shift: u32::MAX,
            offset_cal: [i32::MAX; 3],
            orientation_matrix: [i32::MAX; 9],
            unknown_fields: Vec::new(),
            developer_fields: Vec::new(),
        }
    }

    /// Returns `orientation_matrix` in its scaled value. It returns `None` when value is invalid.
    pub fn orientation_matrix_scaled(&self) -> Option<[f64; 9]> {
        if self.orientation_matrix == [i32::MAX; 9] {
            return None;
        }
        let mut v = [f64::from_bits(u64::MAX); 9];
        for (i, &x) in self.orientation_matrix.iter().enumerate() {
            if x == i32::MAX {
                continue;
            }
            v[i] = x as f64 / 65535.0 - 0.0;
        }
        Some(v)
    }

    /// Set `orientation_matrix` with scaled value, it will automatically be converted to its corresponding integer value.
    pub fn set_orientation_matrix_scaled(&mut self, v: [f64; 9]) -> &mut Self {
        self.orientation_matrix = [i32::MAX; 9];
        for (i, &x) in v.iter().enumerate() {
            let unscaled = (x + 0.0) * 65535.0;
            if unscaled.is_nan() || unscaled.is_infinite() || unscaled > i32::MAX as f64 {
                continue;
            }
            self.orientation_matrix[i] = unscaled as i32;
        }
        self
    }

    fn count_valid_fields(&self) -> usize {
        (self.timestamp.0 != u32::MAX) as usize
            + (self.sensor_type.0 != u8::MAX) as usize
            + (self.calibration_factor != u32::MAX) as usize
            + (self.calibration_divisor != u32::MAX) as usize
            + (self.level_shift != u32::MAX) as usize
            + (self.offset_cal != [i32::MAX; 3]) as usize
            + (self.orientation_matrix != [i32::MAX; 9]) as usize
    }
}

impl Default for ThreeDSensorCalibration {
    fn default() -> Self {
        Self::new()
    }
}

impl From<&Message> for ThreeDSensorCalibration {
    /// from creates new ThreeDSensorCalibration struct based on given mesg.
    fn from(mesg: &Message) -> Self {
        const KNOWN_NUMS: [u64; 4] = [63, 0, 0, 2305843009213693952];
        let mut n = 0u64;
        for field in &mesg.fields {
            n += (KNOWN_NUMS[field.num as usize >> 6] >> (field.num & 63)) & 1 ^ 1
        }

        let mut v = Self::new();
        v.unknown_fields = Vec::<Field>::with_capacity(n as usize);
        v.developer_fields = mesg.developer_fields.clone();

        for field in &mesg.fields {
            match field.num {
                253 => v.timestamp = typedef::DateTime(field.value.as_u32()),
                0 => v.sensor_type = typedef::SensorType(field.value.as_u8()),
                1 => v.calibration_factor = field.value.as_u32(),
                2 => v.calibration_divisor = field.value.as_u32(),
                3 => v.level_shift = field.value.as_u32(),
                4 => {
                    v.offset_cal = match &field.value {
                        Value::VecInt32(v) => {
                            let mut arr = [i32::MAX; 3];
                            for (i, x) in v.iter().take(3).enumerate() {
                                arr[i] = *x;
                            }
                            arr
                        }
                        _ => [i32::MAX; 3],
                    }
                }
                5 => {
                    v.orientation_matrix = match &field.value {
                        Value::VecInt32(v) => {
                            let mut arr = [i32::MAX; 9];
                            for (i, x) in v.iter().take(9).enumerate() {
                                arr[i] = *x;
                            }
                            arr
                        }
                        _ => [i32::MAX; 9],
                    }
                }
                _ => v.unknown_fields.push(field.clone()),
            };
        }

        v
    }
}

impl From<ThreeDSensorCalibration> for Message {
    fn from(m: ThreeDSensorCalibration) -> Self {
        let mut fields =
            Vec::<Field>::with_capacity(m.count_valid_fields() + m.unknown_fields.len());

        if m.timestamp.0 != u32::MAX {
            fields.push(Field {
                num: 253,
                base_type: FitBaseType::UINT32,
                value: Value::Uint32(m.timestamp.0),
                is_expanded: false,
            });
        };
        if m.sensor_type.0 != u8::MAX {
            fields.push(Field {
                num: 0,
                base_type: FitBaseType::ENUM,
                value: Value::Uint8(m.sensor_type.0),
                is_expanded: false,
            });
        };
        if m.calibration_factor != u32::MAX {
            fields.push(Field {
                num: 1,
                base_type: FitBaseType::UINT32,
                value: Value::Uint32(m.calibration_factor),
                is_expanded: false,
            });
        };
        if m.calibration_divisor != u32::MAX {
            fields.push(Field {
                num: 2,
                base_type: FitBaseType::UINT32,
                value: Value::Uint32(m.calibration_divisor),
                is_expanded: false,
            });
        };
        if m.level_shift != u32::MAX {
            fields.push(Field {
                num: 3,
                base_type: FitBaseType::UINT32,
                value: Value::Uint32(m.level_shift),
                is_expanded: false,
            });
        };
        if m.offset_cal != [i32::MAX; 3] {
            fields.push(Field {
                num: 4,
                base_type: FitBaseType::SINT32,
                value: Value::VecInt32(Vec::from(&m.offset_cal)),
                is_expanded: false,
            });
        };
        if m.orientation_matrix != [i32::MAX; 9] {
            fields.push(Field {
                num: 5,
                base_type: FitBaseType::SINT32,
                value: Value::VecInt32(Vec::from(&m.orientation_matrix)),
                is_expanded: false,
            });
        };

        fields.extend_from_slice(&m.unknown_fields);

        Self {
            header: 0,
            num: typedef::MesgNum::THREE_D_SENSOR_CALIBRATION,
            fields,
            developer_fields: m.developer_fields,
        }
    }
}

#[cfg(feature = "serde")]
impl Serialize for ThreeDSensorCalibration {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let n = self.count_valid_fields() + 2;
        let mut state = serializer.serialize_struct("ThreeDSensorCalibration", n)?;
        if let Some(v) = self.timestamp.unix_timestamp() {
            state.serialize_field("timestamp", &v)?;
        }
        if self.sensor_type.0 != u8::MAX {
            state.serialize_field("sensor_type", &self.sensor_type)?;
        }
        if self.calibration_factor != u32::MAX {
            state.serialize_field("calibration_factor", &self.calibration_factor)?;
        }
        if self.calibration_divisor != u32::MAX {
            state.serialize_field("calibration_divisor", &self.calibration_divisor)?;
        }
        if self.level_shift != u32::MAX {
            state.serialize_field("level_shift", &self.level_shift)?;
        }
        if self.offset_cal != [i32::MAX; 3] {
            state.serialize_field("offset_cal", &self.offset_cal)?;
        }
        if let Some(v) = self.orientation_matrix_scaled() {
            state.serialize_field("orientation_matrix", &v)?;
        }
        if !self.unknown_fields.is_empty() {
            state.serialize_field("unknown_fields", &self.unknown_fields)?;
        }
        if !self.developer_fields.is_empty() {
            state.serialize_field("developer_fields", &self.developer_fields)?;
        }
        state.end()
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(feature = "serde", derive(Deserialize), serde(default))]
struct De {
    timestamp: Option<i64>,
    sensor_type: typedef::SensorType,
    calibration_factor: u32,
    calibration_divisor: u32,
    level_shift: u32,
    offset_cal: [i32; 3],
    orientation_matrix: [f64; 9],
    unknown_fields: Vec<Field>,
    developer_fields: Vec<DeveloperField>,
}

#[cfg(feature = "serde")]
impl From<De> for ThreeDSensorCalibration {
    fn from(m: De) -> Self {
        Self {
            timestamp: m.timestamp.map_or_else(
                || typedef::DateTime(u32::MAX),
                typedef::DateTime::from_unix_timestamp,
            ),
            sensor_type: m.sensor_type,
            calibration_factor: m.calibration_factor,
            calibration_divisor: m.calibration_divisor,
            level_shift: m.level_shift,
            offset_cal: m.offset_cal,
            orientation_matrix: {
                let mut vals = [i32::MAX; 9];
                for (i, &x) in m.orientation_matrix.iter().enumerate() {
                    let unscaled = (x + 0.0) * 65535.0;
                    if unscaled.is_nan() || unscaled.is_infinite() || unscaled > i32::MAX as f64 {
                        continue;
                    }
                    vals[i] = unscaled as i32;
                }
                vals
            },
            unknown_fields: m.unknown_fields,
            developer_fields: m.developer_fields,
        }
    }
}

#[cfg(feature = "serde")]
impl Default for De {
    fn default() -> Self {
        Self {
            timestamp: None,
            sensor_type: typedef::SensorType(u8::MAX),
            calibration_factor: u32::MAX,
            calibration_divisor: u32::MAX,
            level_shift: u32::MAX,
            offset_cal: [i32::MAX; 3],
            orientation_matrix: [const { f64::from_bits(u64::MAX) }; 9],
            unknown_fields: Vec::new(),
            developer_fields: Vec::new(),
        }
    }
}