Skip to main content

strata_device/
types.rs

1//! Data models and enums representing native device telemetry and hardware states.
2
3/// Battery charging state.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
5pub enum BatteryState {
6    Charging,
7    Discharging,
8    #[default]
9    Full,
10    NotCharging,
11    Unknown,
12}
13
14/// Comprehensive battery telemetry.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct BatteryInfo {
17    /// Battery level in range [0.0, 1.0].
18    pub level: f32,
19    /// Current battery charging state.
20    pub state: BatteryState,
21    /// Whether OS low power / battery saver mode is active.
22    pub is_low_power_mode: bool,
23    /// Estimated seconds remaining until battery reaches 0%.
24    pub time_to_empty_secs: Option<u32>,
25    /// Estimated seconds remaining until battery reaches 100%.
26    pub time_to_full_secs: Option<u32>,
27}
28
29impl Default for BatteryInfo {
30    fn default() -> Self {
31        Self {
32            level: 1.0,
33            state: BatteryState::Full,
34            is_low_power_mode: false,
35            time_to_empty_secs: None,
36            time_to_full_secs: None,
37        }
38    }
39}
40
41/// Thermal throttling state of the device.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
43pub enum ThermalState {
44    /// Normal operating thermal conditions.
45    #[default]
46    Nominal,
47    /// Elevated thermal conditions; active cooling (fans) engaged.
48    Fair,
49    /// Heavy thermal throttling; frame rates capped to 60Hz.
50    Serious,
51    /// Extreme thermal state; immediate power throttling, cap to 30Hz, disable 3D.
52    Critical,
53}
54
55/// System-wide memory pressure level.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
57pub enum MemoryPressure {
58    /// Memory consumption is within normal operational boundaries.
59    #[default]
60    Normal,
61    /// High memory pressure; caches, glyph atlases, and inactive subtrees should be purged.
62    Warning,
63    /// Imminent OS process termination; emergency eviction of all non-essential allocations.
64    Critical,
65}
66
67/// Underlying GPU rendering backend.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub enum GpuBackend {
70    Metal,
71    Vulkan,
72    Direct3D12,
73    WebGpu,
74    OpenGl,
75    #[default]
76    Software,
77}
78
79/// GPU hardware introspection information.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct GpuInfo {
82    pub backend: GpuBackend,
83    pub device_name: String,
84    pub driver_version: String,
85    pub vram_total_bytes: u64,
86    pub vram_used_bytes: u64,
87}
88
89impl Default for GpuInfo {
90    fn default() -> Self {
91        Self {
92            backend: GpuBackend::Software,
93            device_name: "Strata Software Rasterizer".to_string(),
94            driver_version: "1.0.0".to_string(),
95            vram_total_bytes: 0,
96            vram_used_bytes: 0,
97        }
98    }
99}
100
101/// Display refresh rate characteristics and capabilities.
102#[derive(Debug, Clone, Copy, PartialEq)]
103pub struct DisplayRefreshInfo {
104    pub current_hz: f32,
105    pub max_hz: f32,
106    pub is_variable_refresh_rate: bool,
107    pub is_high_refresh_rate: bool,
108}
109
110impl Default for DisplayRefreshInfo {
111    fn default() -> Self {
112        Self {
113            current_hz: 60.0,
114            max_hz: 60.0,
115            is_variable_refresh_rate: false,
116            is_high_refresh_rate: false,
117        }
118    }
119}
120
121/// Active network interface connection type.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
123pub enum ConnectionType {
124    #[default]
125    Wifi,
126    Cellular,
127    Ethernet,
128    Bluetooth,
129    Unknown,
130    None,
131}
132
133/// Cellular radio generation.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum CellularGen {
136    TwoG,
137    ThreeG,
138    FourG,
139    FiveG,
140}
141
142/// Network connectivity and bandwidth telemetry.
143#[derive(Debug, Clone, Copy, PartialEq)]
144pub struct NetworkStatus {
145    pub is_online: bool,
146    pub connection_type: ConnectionType,
147    pub cellular_generation: Option<CellularGen>,
148    pub downlink_mbps: Option<f32>,
149    pub rtt_ms: Option<u32>,
150    pub is_metered: bool,
151}
152
153impl Default for NetworkStatus {
154    fn default() -> Self {
155        Self {
156            is_online: true,
157            connection_type: ConnectionType::Wifi,
158            cellular_generation: None,
159            downlink_mbps: Some(100.0),
160            rtt_ms: Some(20),
161            is_metered: false,
162        }
163    }
164}
165
166/// Screen safe area insets for notches, Dynamic Island, and curved display bezels.
167#[derive(Debug, Clone, Copy, PartialEq, Default)]
168pub struct SafeAreaInsets {
169    pub top: f32,
170    pub right: f32,
171    pub bottom: f32,
172    pub left: f32,
173}
174
175impl SafeAreaInsets {
176    pub const fn zero() -> Self {
177        Self {
178            top: 0.0,
179            right: 0.0,
180            bottom: 0.0,
181            left: 0.0,
182        }
183    }
184
185    pub const fn all(val: f32) -> Self {
186        Self {
187            top: val,
188            right: val,
189            bottom: val,
190            left: val,
191        }
192    }
193
194    pub const fn symmetric(vertical: f32, horizontal: f32) -> Self {
195        Self {
196            top: vertical,
197            right: horizontal,
198            bottom: vertical,
199            left: horizontal,
200        }
201    }
202}
203
204/// Supported display color gamut standard.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
206pub enum ColorGamut {
207    #[default]
208    Srgb,
209    DisplayP3,
210    Rec2020,
211}
212
213/// Geometry, scale factor, and color capabilities of the active display.
214#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct ScreenGeometry {
216    pub width_px: u32,
217    pub height_px: u32,
218    pub scale_factor: f32,
219    pub safe_area: SafeAreaInsets,
220    pub color_gamut: ColorGamut,
221}
222
223impl Default for ScreenGeometry {
224    fn default() -> Self {
225        Self {
226            width_px: 1280,
227            height_px: 800,
228            scale_factor: 1.0,
229            safe_area: SafeAreaInsets::zero(),
230            color_gamut: ColorGamut::Srgb,
231        }
232    }
233}
234
235/// Origin source of a geolocation fix.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
237pub enum GeolocationSource {
238    #[default]
239    None,
240    MockOverride,
241    EnvOverride,
242    OsNativeDaemon,
243    HardwareGpsNmea,
244    IpGeolocationFallback,
245}
246
247/// Complete geolocation telemetry fix for reactive UI and map centering.
248#[derive(Debug, Clone, PartialEq)]
249pub struct GeolocationInfo {
250    pub is_available: bool,
251    pub latitude: f64,
252    pub longitude: f64,
253    pub altitude_m: Option<f64>,
254    pub accuracy_m: f64,
255    pub heading_deg: Option<f64>,
256    pub speed_mps: Option<f64>,
257    pub timestamp_ms: u64,
258    pub source: GeolocationSource,
259}
260
261impl Default for GeolocationInfo {
262    fn default() -> Self {
263        Self {
264            is_available: false,
265            latitude: 0.0,
266            longitude: 0.0,
267            altitude_m: None,
268            accuracy_m: 0.0,
269            heading_deg: None,
270            speed_mps: None,
271            timestamp_ms: 0,
272            source: GeolocationSource::None,
273        }
274    }
275}
276
277impl GeolocationInfo {
278    /// Constructs an available geolocation fix stamped with current wall-clock milliseconds.
279    pub fn available(
280        latitude: f64,
281        longitude: f64,
282        accuracy_m: f64,
283        source: GeolocationSource,
284    ) -> Self {
285        let timestamp_ms = std::time::SystemTime::now()
286            .duration_since(std::time::UNIX_EPOCH)
287            .map(|d| d.as_millis() as u64)
288            .unwrap_or(0);
289        Self {
290            is_available: true,
291            latitude,
292            longitude,
293            altitude_m: None,
294            accuracy_m: accuracy_m.max(0.0),
295            heading_deg: None,
296            speed_mps: None,
297            timestamp_ms,
298            source,
299        }
300    }
301
302    pub fn with_altitude(mut self, altitude_m: Option<f64>) -> Self {
303        self.altitude_m = altitude_m;
304        self
305    }
306
307    pub fn with_motion(mut self, heading_deg: Option<f64>, speed_mps: Option<f64>) -> Self {
308        self.heading_deg = heading_deg.map(|h| h.rem_euclid(360.0));
309        self.speed_mps = speed_mps.filter(|s| s.is_finite() && *s >= 0.0);
310        self
311    }
312}
313
314/// Magnetometer / compass telemetry.
315#[derive(Debug, Clone, Copy, PartialEq)]
316pub struct CompassReading {
317    pub available: bool,
318    /// Magnetic heading in degrees `[0.0, 360.0)` clockwise from magnetic north.
319    pub magnetic_heading_deg: f32,
320    /// True geographic heading in degrees `[0.0, 360.0)` clockwise from true north.
321    pub true_heading_deg: f32,
322    /// Estimated heading uncertainty in degrees.
323    pub heading_accuracy_deg: f32,
324    /// Raw magnetic flux density vector `[x, y, z]` in microteslas (uT).
325    pub magnetic_field_ut: [f32; 3],
326}
327
328impl Default for CompassReading {
329    fn default() -> Self {
330        Self {
331            available: false,
332            magnetic_heading_deg: 0.0,
333            true_heading_deg: 0.0,
334            heading_accuracy_deg: 0.0,
335            magnetic_field_ut: [0.0; 3],
336        }
337    }
338}
339
340impl CompassReading {
341    /// Computes normalized compass heading from a horizontal/3-axis magnetometer reading `[mx, my, mz]`
342    /// in microteslas (uT) and optional magnetic declination in degrees.
343    pub fn from_magnetic_field_ut(magnetic_field_ut: [f32; 3], declination_deg: f32) -> Self {
344        let [mx, my, _mz] = magnetic_field_ut;
345        let heading = mx.atan2(my).to_degrees().rem_euclid(360.0);
346        let true_heading = (heading + declination_deg).rem_euclid(360.0);
347        let mag_norm = (mx * mx + my * my + magnetic_field_ut[2] * magnetic_field_ut[2]).sqrt();
348        // Typical Earth magnetic field is ~25..65 uT; anomalies widen estimated accuracy.
349        let accuracy_deg = if (20.0..=75.0).contains(&mag_norm) {
350            5.0
351        } else {
352            18.0
353        };
354        Self {
355            available: true,
356            magnetic_heading_deg: heading,
357            true_heading_deg: true_heading,
358            heading_accuracy_deg: accuracy_deg,
359            magnetic_field_ut,
360        }
361    }
362}
363
364/// 6-DoF Inertial Measurement Unit (accelerometer + gyroscope + fused attitude) reading.
365#[derive(Debug, Clone, Copy, PartialEq)]
366pub struct ImuReading {
367    pub available: bool,
368    /// Linear acceleration including gravity `[ax, ay, az]` in m/s^2.
369    pub accel_mps2: [f32; 3],
370    /// Angular velocity `[gx, gy, gz]` in rad/s.
371    pub gyro_rps: [f32; 3],
372    /// Fused orientation Euler angles `(roll_deg, pitch_deg, yaw_deg)`.
373    pub attitude_deg: [f32; 3],
374    /// Unit quaternion `[x, y, z, w]`.
375    pub quaternion: [f32; 4],
376}
377
378impl Default for ImuReading {
379    fn default() -> Self {
380        Self {
381            available: false,
382            accel_mps2: [0.0, 0.0, 9.80665],
383            gyro_rps: [0.0; 3],
384            attitude_deg: [0.0; 3],
385            quaternion: [0.0, 0.0, 0.0, 1.0],
386        }
387    }
388}
389
390impl ImuReading {
391    /// Computes static gravity-aligned roll/pitch and unit quaternion from raw accelerometer (`m/s^2`)
392    /// and gyroscope (`rad/s`) vectors.
393    pub fn from_accel_gyro(accel_mps2: [f32; 3], gyro_rps: [f32; 3]) -> Self {
394        let [ax, ay, az] = accel_mps2;
395        let roll_rad = ay.atan2(az);
396        let pitch_rad = (-ax).atan2((ay * ay + az * az).sqrt());
397        let yaw_rad = 0.0_f32;
398
399        let (sr, cr) = (roll_rad * 0.5).sin_cos();
400        let (sp, cp) = (pitch_rad * 0.5).sin_cos();
401        let (sy, cy) = (yaw_rad * 0.5).sin_cos();
402
403        let qx = sr * cp * cy - cr * sp * sy;
404        let qy = cr * sp * cy + sr * cp * sy;
405        let qz = cr * cp * sy - sr * sp * cy;
406        let qw = cr * cp * cy + sr * sp * sy;
407        let q_len = (qx * qx + qy * qy + qz * qz + qw * qw).sqrt().max(1e-6);
408
409        Self {
410            available: true,
411            accel_mps2,
412            gyro_rps,
413            attitude_deg: [roll_rad.to_degrees(), pitch_rad.to_degrees(), 0.0],
414            quaternion: [qx / q_len, qy / q_len, qz / q_len, qw / q_len],
415        }
416    }
417}
418
419/// Computes International Standard Atmosphere (ISA) pressure altitude in meters from barometric
420/// pressure in hectopascals (hPa / mbar):
421/// `h = 44330.0 * (1.0 - (P / 1013.25)^0.190295)`.
422#[inline]
423pub fn isa_pressure_altitude_m(pressure_hpa: f32) -> f32 {
424    if !pressure_hpa.is_finite() || pressure_hpa <= 0.0 {
425        return 0.0;
426    }
427    44330.0 * (1.0 - (pressure_hpa / 1013.25).powf(0.190295))
428}
429
430/// Barometric pressure and ISA pressure-altitude sensor reading.
431#[derive(Debug, Clone, Copy, PartialEq)]
432pub struct BarometerReading {
433    pub available: bool,
434    /// Atmospheric pressure in hectopascals (hPa / mbar).
435    pub pressure_hpa: f32,
436    /// Estimated altitude above mean sea level in meters using the ISA barometric formula.
437    pub pressure_altitude_m: f32,
438    /// Sensor die temperature in Celsius, if available.
439    pub temperature_c: Option<f32>,
440}
441
442impl Default for BarometerReading {
443    fn default() -> Self {
444        Self {
445            available: false,
446            pressure_hpa: 1013.25,
447            pressure_altitude_m: 0.0,
448            temperature_c: None,
449        }
450    }
451}
452
453impl BarometerReading {
454    pub fn from_hpa(pressure_hpa: f32, temperature_c: Option<f32>) -> Self {
455        Self {
456            available: true,
457            pressure_hpa,
458            pressure_altitude_m: isa_pressure_altitude_m(pressure_hpa),
459            temperature_c,
460        }
461    }
462}
463
464/// Maps illuminance in lux to a smooth perceptual daylight factor in `[0.0, 1.0]`
465/// (`0.0` = dark room, `1.0` = bright outdoor daylight >= 10,000 lux).
466#[inline]
467pub fn lux_to_daylight_factor(illuminance_lux: f32) -> f32 {
468    if !illuminance_lux.is_finite() || illuminance_lux <= 0.0 {
469        return 0.0;
470    }
471    ((1.0 + illuminance_lux).ln() / (1.0 + 10_000.0_f32).ln()).clamp(0.0, 1.0)
472}
473
474/// Ambient light sensor (ALS) reading.
475#[derive(Debug, Clone, Copy, PartialEq)]
476pub struct AmbientLightReading {
477    pub available: bool,
478    /// Ambient illuminance in lux.
479    pub illuminance_lux: f32,
480    /// Suggested UI daylight adaptation factor in `[0.0, 1.0]`.
481    pub daylight_factor: f32,
482}
483
484impl Default for AmbientLightReading {
485    fn default() -> Self {
486        Self {
487            available: false,
488            illuminance_lux: 0.0,
489            daylight_factor: 0.0,
490        }
491    }
492}
493
494impl AmbientLightReading {
495    pub fn from_lux(illuminance_lux: f32) -> Self {
496        let lux = illuminance_lux.max(0.0);
497        Self {
498            available: true,
499            illuminance_lux: lux,
500            daylight_factor: lux_to_daylight_factor(lux),
501        }
502    }
503}