Skip to main content

mecha10_core/
sensor.rs

1//! Shared sensor message types
2//!
3//! This module contains common sensor message types used across drivers and nodes.
4//! Previously these were duplicated in each driver, now they are centralized here.
5
6use crate::messages::Message;
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct RgbImage {
12    pub timestamp: u64,
13    pub frame_id: u64,
14    pub width: u32,
15    pub height: u32,
16    pub encoding: String,
17    pub data: Vec<u8>,
18}
19
20impl Message for RgbImage {}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct DepthImage {
24    pub timestamp: u64,
25    pub frame_id: u64,
26    pub width: u32,
27    pub height: u32,
28    pub data: Vec<f32>,
29}
30
31impl Message for DepthImage {}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct CameraInfo {
35    pub timestamp: u64,
36    pub width: u32,
37    pub height: u32,
38    pub fps: f32,
39}
40
41impl Message for CameraInfo {}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct LaserScan {
45    pub timestamp: u64,
46    pub scan_id: u64,
47    pub angle_min: f32,
48    pub angle_max: f32,
49    pub angle_increment: f32,
50    pub range_min: f32,
51    pub range_max: f32,
52    pub ranges: Vec<f32>,
53    pub intensities: Vec<f32>,
54}
55
56impl Message for LaserScan {}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct Odometry {
60    pub timestamp: u64,
61    pub x: f32,
62    pub y: f32,
63    pub theta: f32,
64    pub linear_vel: f32,
65    pub angular_vel: f32,
66}
67
68impl Message for Odometry {}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct ImuData {
72    #[serde(default = "default_imu_id")]
73    pub imu_id: String,
74    pub timestamp: u64,
75    pub roll: f32,
76    pub pitch: f32,
77    pub yaw: f32,
78    pub angular_velocity_x: f32,
79    pub angular_velocity_y: f32,
80    pub angular_velocity_z: f32,
81    pub linear_acceleration_x: f32,
82    pub linear_acceleration_y: f32,
83    pub linear_acceleration_z: f32,
84}
85
86fn default_imu_id() -> String {
87    "imu-0".to_string()
88}
89
90impl Message for ImuData {}
91
92#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
93#[serde(try_from = "u16", into = "u16")]
94#[schemars(with = "u16")]
95pub enum GyroScale {
96    #[default]
97    Dps250 = 250,
98    Dps500 = 500,
99    Dps1000 = 1000,
100    Dps2000 = 2000,
101}
102
103#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
104#[serde(try_from = "u8", into = "u8")]
105#[schemars(with = "u8")]
106pub enum AccelScale {
107    #[default]
108    G2 = 2,
109    G4 = 4,
110    G8 = 8,
111    G16 = 16,
112}
113
114macro_rules! impl_scale_enum {
115    ($ty:ident: $repr:ty { $($variant:ident = $val:literal),+ $(,)? }, $field:literal, $values:literal, $unit:literal) => {
116        impl TryFrom<$repr> for $ty {
117            type Error = String;
118
119            fn try_from(value: $repr) -> Result<Self, Self::Error> {
120                match value {
121                    $($val => Ok(Self::$variant),)+
122                    other => Err(format!("invalid {} {other}: must be one of {} ({})", $field, $values, $unit)),
123                }
124            }
125        }
126
127        impl From<$ty> for $repr {
128            fn from(value: $ty) -> Self {
129                value as $repr
130            }
131        }
132
133        impl std::fmt::Display for $ty {
134            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135                write!(f, "{}", <$repr>::from(*self))
136            }
137        }
138    };
139}
140
141impl_scale_enum!(
142    GyroScale: u16 { Dps250 = 250, Dps500 = 500, Dps1000 = 1000, Dps2000 = 2000 },
143    "gyro_scale", "250, 500, 1000, 2000", "dps"
144);
145impl_scale_enum!(
146    AccelScale: u8 { G2 = 2, G4 = 4, G8 = 8, G16 = 16 },
147    "accel_scale", "2, 4, 8, 16", "g"
148);
149
150#[cfg(test)]
151mod scale_tests {
152    use super::*;
153
154    #[test]
155    fn gyro_scale_try_from_valid() {
156        for (raw, expected) in [
157            (250u16, GyroScale::Dps250),
158            (500, GyroScale::Dps500),
159            (1000, GyroScale::Dps1000),
160            (2000, GyroScale::Dps2000),
161        ] {
162            assert_eq!(GyroScale::try_from(raw).unwrap(), expected);
163            assert_eq!(u16::from(expected), raw);
164        }
165    }
166
167    #[test]
168    fn gyro_scale_try_from_invalid() {
169        let err = GyroScale::try_from(100u16).unwrap_err();
170        assert!(err.contains("invalid gyro_scale 100"));
171    }
172
173    #[test]
174    fn accel_scale_try_from_valid() {
175        for (raw, expected) in [
176            (2u8, AccelScale::G2),
177            (4, AccelScale::G4),
178            (8, AccelScale::G8),
179            (16, AccelScale::G16),
180        ] {
181            assert_eq!(AccelScale::try_from(raw).unwrap(), expected);
182            assert_eq!(u8::from(expected), raw);
183        }
184    }
185
186    #[test]
187    fn accel_scale_try_from_invalid() {
188        let err = AccelScale::try_from(32u8).unwrap_err();
189        assert!(err.contains("invalid accel_scale 32"));
190    }
191
192    #[test]
193    fn display_formats_as_bare_number() {
194        assert_eq!(GyroScale::Dps500.to_string(), "500");
195        assert_eq!(AccelScale::G8.to_string(), "8");
196    }
197
198    #[test]
199    fn defaults_match_datasheet_power_on_state() {
200        assert_eq!(GyroScale::default(), GyroScale::Dps250);
201        assert_eq!(AccelScale::default(), AccelScale::G2);
202    }
203}