aranet-types 0.2.0

Platform-agnostic types for Aranet environmental sensors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! Core types for Aranet sensor data.

use core::fmt;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::error::ParseError;

/// Type of Aranet device.
///
/// This enum is marked `#[non_exhaustive]` to allow adding new device types
/// in future versions without breaking downstream code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum DeviceType {
    /// Aranet4 CO2, temperature, humidity, and pressure sensor.
    Aranet4 = 0xF1,
    /// Aranet2 temperature and humidity sensor.
    Aranet2 = 0xF2,
    /// Aranet Radon sensor.
    AranetRadon = 0xF3,
    /// Aranet Radiation sensor.
    AranetRadiation = 0xF4,
}

impl DeviceType {
    /// Detect device type from a device name.
    ///
    /// Analyzes the device name (case-insensitive) to determine the device type
    /// based on common naming patterns. Uses word-boundary-aware matching to avoid
    /// false positives (e.g., `"Aranet4"` won't match `"NotAranet4Device"`).
    ///
    /// # Examples
    ///
    /// ```
    /// use aranet_types::DeviceType;
    ///
    /// assert_eq!(DeviceType::from_name("Aranet4 12345"), Some(DeviceType::Aranet4));
    /// assert_eq!(DeviceType::from_name("Aranet2 Home"), Some(DeviceType::Aranet2));
    /// assert_eq!(DeviceType::from_name("Aranet4"), Some(DeviceType::Aranet4));
    /// assert_eq!(DeviceType::from_name("AranetRn+ 306B8"), Some(DeviceType::AranetRadon));
    /// assert_eq!(DeviceType::from_name("RN+ Radon"), Some(DeviceType::AranetRadon));
    /// assert_eq!(DeviceType::from_name("Aranet Radiation"), Some(DeviceType::AranetRadiation));
    /// assert_eq!(DeviceType::from_name("Aranet\u{2622} 30ED1"), Some(DeviceType::AranetRadiation));
    /// assert_eq!(DeviceType::from_name("Unknown Device"), None);
    /// ```
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        let name_lower = name.to_lowercase();

        // Check for Aranet4 - must be at word boundary (start or after non-alphanumeric)
        if Self::contains_word(&name_lower, "aranet4") {
            return Some(DeviceType::Aranet4);
        }

        // Check for Aranet2
        if Self::contains_word(&name_lower, "aranet2") {
            return Some(DeviceType::Aranet2);
        }

        // Check for Radon devices (AranetRn+, RN+, or Radon keyword)
        if name_lower.contains("aranetrn+")
            || Self::contains_word(&name_lower, "rn+")
            || Self::contains_word(&name_lower, "aranet radon")
            || Self::contains_word(&name_lower, "radon")
        {
            return Some(DeviceType::AranetRadon);
        }

        // Check for Radiation devices (name may contain ☢ symbol instead of "radiation")
        if Self::contains_word(&name_lower, "radiation") || name_lower.contains('\u{2622}') {
            return Some(DeviceType::AranetRadiation);
        }

        None
    }

    /// Check if a string contains a word at a word boundary.
    ///
    /// A word boundary is defined as the start/end of the string or a non-alphanumeric character.
    /// Checks all occurrences, not just the first.
    fn contains_word(haystack: &str, needle: &str) -> bool {
        let mut start = 0;
        while let Some(pos) = haystack[start..].find(needle) {
            let abs_pos = start + pos;

            // Check character before the match (if any)
            let before_ok = abs_pos == 0
                || haystack[..abs_pos]
                    .chars()
                    .last()
                    .is_none_or(|c| !c.is_alphanumeric());

            // Check character after the match (if any)
            let end_pos = abs_pos + needle.len();
            let after_ok = end_pos >= haystack.len()
                || haystack[end_pos..]
                    .chars()
                    .next()
                    .is_none_or(|c| !c.is_alphanumeric());

            if before_ok && after_ok {
                return true;
            }

            start = abs_pos + 1;
            if start >= haystack.len() {
                break;
            }
        }
        false
    }

    /// Returns `true` if this device type has a CO2 sensor.
    #[must_use]
    pub fn has_co2(&self) -> bool {
        matches!(self, DeviceType::Aranet4)
    }

    /// Returns `true` if this device type has a temperature sensor.
    #[must_use]
    pub fn has_temperature(&self) -> bool {
        !matches!(self, DeviceType::AranetRadiation)
    }

    /// Returns `true` if this device type has a humidity sensor.
    #[must_use]
    pub fn has_humidity(&self) -> bool {
        self.has_temperature()
    }

    /// Returns `true` if this device type has a pressure sensor.
    #[must_use]
    pub fn has_pressure(&self) -> bool {
        matches!(self, DeviceType::Aranet4 | DeviceType::AranetRadon)
    }

    /// Returns the BLE characteristic UUID for reading current sensor values.
    ///
    /// - **Aranet4**: Uses `CURRENT_READINGS_DETAIL` (f0cd3001)
    /// - **Other devices**: Use `CURRENT_READINGS_DETAIL_ALT` (f0cd3003)
    ///
    /// # Examples
    ///
    /// ```
    /// use aranet_types::DeviceType;
    /// use aranet_types::ble;
    ///
    /// assert_eq!(DeviceType::Aranet4.readings_characteristic(), ble::CURRENT_READINGS_DETAIL);
    /// assert_eq!(DeviceType::Aranet2.readings_characteristic(), ble::CURRENT_READINGS_DETAIL_ALT);
    /// ```
    #[must_use]
    pub fn readings_characteristic(&self) -> uuid::Uuid {
        match self {
            DeviceType::Aranet4 => crate::uuid::CURRENT_READINGS_DETAIL,
            _ => crate::uuid::CURRENT_READINGS_DETAIL_ALT,
        }
    }
}

impl TryFrom<u8> for DeviceType {
    type Error = ParseError;

    /// Convert a byte value to a `DeviceType`.
    ///
    /// # Examples
    ///
    /// ```
    /// use aranet_types::DeviceType;
    ///
    /// assert_eq!(DeviceType::try_from(0xF1), Ok(DeviceType::Aranet4));
    /// assert_eq!(DeviceType::try_from(0xF2), Ok(DeviceType::Aranet2));
    /// assert!(DeviceType::try_from(0x00).is_err());
    /// ```
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0xF1 => Ok(DeviceType::Aranet4),
            0xF2 => Ok(DeviceType::Aranet2),
            0xF3 => Ok(DeviceType::AranetRadon),
            0xF4 => Ok(DeviceType::AranetRadiation),
            _ => Err(ParseError::UnknownDeviceType(value)),
        }
    }
}

impl fmt::Display for DeviceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DeviceType::Aranet4 => write!(f, "Aranet4"),
            DeviceType::Aranet2 => write!(f, "Aranet2"),
            DeviceType::AranetRadon => write!(f, "Aranet Radon"),
            DeviceType::AranetRadiation => write!(f, "Aranet Radiation"),
        }
    }
}

/// CO2 level status indicator.
///
/// This enum is marked `#[non_exhaustive]` to allow adding new status levels
/// in future versions without breaking downstream code.
///
/// # Ordering
///
/// Status values are ordered by severity: `Error < Green < Yellow < Red`.
/// This allows threshold comparisons like `if status >= Status::Yellow { warn!(...) }`.
///
/// # Display vs Serialization
///
/// **Note:** The `Display` trait returns human-readable labels ("Good", "Moderate", "High"),
/// while serde serialization uses the variant names ("Green", "Yellow", "Red").
///
/// ```
/// use aranet_types::Status;
///
/// // Display is human-readable
/// assert_eq!(format!("{}", Status::Green), "Good");
///
/// // Ordering works for threshold comparisons
/// assert!(Status::Red > Status::Yellow);
/// assert!(Status::Yellow > Status::Green);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum Status {
    /// Error or invalid reading.
    Error = 0,
    /// CO2 level is good (green).
    Green = 1,
    /// CO2 level is moderate (yellow).
    Yellow = 2,
    /// CO2 level is high (red).
    Red = 3,
}

impl From<u8> for Status {
    fn from(value: u8) -> Self {
        match value {
            1 => Status::Green,
            2 => Status::Yellow,
            3 => Status::Red,
            _ => Status::Error,
        }
    }
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Status::Error => write!(f, "Error"),
            Status::Green => write!(f, "Good"),
            Status::Yellow => write!(f, "Moderate"),
            Status::Red => write!(f, "High"),
        }
    }
}

/// Minimum number of bytes required to parse an Aranet4 [`CurrentReading`].
pub const MIN_CURRENT_READING_BYTES: usize = 13;

/// Minimum number of bytes required to parse an Aranet2 [`CurrentReading`].
pub const MIN_ARANET2_READING_BYTES: usize = 12;

/// Minimum number of bytes required to parse an Aranet Radon [`CurrentReading`] (advertisement format).
pub const MIN_RADON_READING_BYTES: usize = 15;

/// Minimum number of bytes required to parse an Aranet Radon GATT [`CurrentReading`].
pub const MIN_RADON_GATT_READING_BYTES: usize = 18;

/// Minimum number of bytes required to parse an Aranet Radiation [`CurrentReading`].
pub const MIN_RADIATION_READING_BYTES: usize = 28;

/// Sentinel value used by the Aranet Radon firmware to indicate that an
/// averaging period is still accumulating data and no result is available yet.
///
/// Radon average values (24h, 7d, 30d) at or above this threshold should be
/// treated as "in progress" rather than valid measurements.
pub const RADON_AVERAGE_IN_PROGRESS: u32 = 0xFF00_0000;

/// Current reading from an Aranet sensor.
///
/// This struct supports all Aranet device types:
/// - **Aranet4**: CO2, temperature, pressure, humidity
/// - **Aranet2**: Temperature, humidity (co2 and pressure will be 0)
/// - **`AranetRn+` (Radon)**: Radon, temperature, pressure, humidity (co2 will be 0)
/// - **Aranet Radiation**: Radiation dose, temperature (uses `radiation_*` fields)
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CurrentReading {
    /// CO2 concentration in ppm (Aranet4 only, 0 for other devices).
    pub co2: u16,
    /// Temperature in degrees Celsius.
    pub temperature: f32,
    /// Atmospheric pressure in hPa (0 for Aranet2).
    pub pressure: f32,
    /// Relative humidity percentage (0-100).
    pub humidity: u8,
    /// Battery level percentage (0-100).
    pub battery: u8,
    /// CO2 status indicator.
    pub status: Status,
    /// Measurement interval in seconds.
    pub interval: u16,
    /// Age of reading in seconds since last measurement.
    pub age: u16,
    /// Timestamp when the reading was captured (if known).
    ///
    /// This is typically set by the library when reading from a device,
    /// calculated as `now - age`.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub captured_at: Option<time::OffsetDateTime>,
    /// Radon concentration in Bq/m³ (`AranetRn+` only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radon: Option<u32>,
    /// Radiation dose rate in µSv/h (Aranet Radiation only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radiation_rate: Option<f32>,
    /// Total radiation dose in mSv (Aranet Radiation only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radiation_total: Option<f64>,
    /// 24-hour average radon concentration in Bq/m³ (`AranetRn+` only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radon_avg_24h: Option<u32>,
    /// 7-day average radon concentration in Bq/m³ (`AranetRn+` only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radon_avg_7d: Option<u32>,
    /// 30-day average radon concentration in Bq/m³ (`AranetRn+` only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radon_avg_30d: Option<u32>,
}

impl Default for CurrentReading {
    fn default() -> Self {
        Self {
            co2: 0,
            temperature: 0.0,
            pressure: 0.0,
            humidity: 0,
            battery: 0,
            status: Status::Error,
            interval: 0,
            age: 0,
            captured_at: None,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
            radon_avg_24h: None,
            radon_avg_7d: None,
            radon_avg_30d: None,
        }
    }
}

impl CurrentReading {
    /// Parse a `CurrentReading` from raw bytes (Aranet4 format).
    ///
    /// The byte format is:
    /// - bytes 0-1: CO2 (u16 LE)
    /// - bytes 2-3: Temperature (u16 LE, divide by 20 for Celsius)
    /// - bytes 4-5: Pressure (u16 LE, divide by 10 for hPa)
    /// - byte 6: Humidity (u8)
    /// - byte 7: Battery (u8)
    /// - byte 8: Status (u8)
    /// - bytes 9-10: Interval (u16 LE)
    /// - bytes 11-12: Age (u16 LE)
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InsufficientBytes`] if `data` contains fewer than
    /// [`MIN_CURRENT_READING_BYTES`] (13) bytes.
    #[must_use = "parsing returns a Result that should be handled"]
    pub fn from_bytes(data: &[u8]) -> Result<Self, ParseError> {
        Self::from_bytes_aranet4(data)
    }

    /// Parse a `CurrentReading` from raw bytes (Aranet4 format).
    ///
    /// This is an alias for [`from_bytes`](Self::from_bytes) for explicit device type parsing.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InsufficientBytes`] if `data` contains fewer than
    /// [`MIN_CURRENT_READING_BYTES`] (13) bytes.
    #[must_use = "parsing returns a Result that should be handled"]
    pub fn from_bytes_aranet4(data: &[u8]) -> Result<Self, ParseError> {
        use bytes::Buf;

        if data.len() < MIN_CURRENT_READING_BYTES {
            return Err(ParseError::InsufficientBytes {
                expected: MIN_CURRENT_READING_BYTES,
                actual: data.len(),
            });
        }

        let mut buf = data;
        let co2 = buf.get_u16_le();
        let temp_raw = buf.get_i16_le();
        let pressure_raw = buf.get_u16_le();
        let humidity = buf.get_u8();
        let battery = buf.get_u8();
        let status = Status::from(buf.get_u8());
        let interval = buf.get_u16_le();
        let age = buf.get_u16_le();

        Ok(CurrentReading {
            co2,
            temperature: f32::from(temp_raw) / 20.0,
            pressure: f32::from(pressure_raw) / 10.0,
            humidity,
            battery,
            status,
            interval,
            age,
            captured_at: None,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
            radon_avg_24h: None,
            radon_avg_7d: None,
            radon_avg_30d: None,
        })
    }

    /// Parse a `CurrentReading` from raw bytes (Aranet2 GATT format).
    ///
    /// The byte format is:
    /// - bytes 0-1: Unknown/header (u16 LE)
    /// - bytes 2-3: Interval (u16 LE, seconds)
    /// - bytes 4-5: Age (u16 LE, seconds since last reading)
    /// - byte 6: Battery (u8)
    /// - bytes 7-8: Temperature (u16 LE, divide by 20 for Celsius)
    /// - bytes 9-10: Humidity (u16 LE, divide by 10 for %)
    /// - byte 11: Status flags (bits\[0:1] = humidity, bits\[2:3] = temperature)
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InsufficientBytes`] if `data` contains fewer than
    /// [`MIN_ARANET2_READING_BYTES`] (12) bytes.
    #[must_use = "parsing returns a Result that should be handled"]
    pub fn from_bytes_aranet2(data: &[u8]) -> Result<Self, ParseError> {
        use bytes::Buf;

        if data.len() < MIN_ARANET2_READING_BYTES {
            return Err(ParseError::InsufficientBytes {
                expected: MIN_ARANET2_READING_BYTES,
                actual: data.len(),
            });
        }

        let mut buf = data;
        let _header = buf.get_u16_le();
        let interval = buf.get_u16_le();
        let age = buf.get_u16_le();
        let battery = buf.get_u8();
        let temp_raw = buf.get_i16_le();
        let humidity_raw = buf.get_u16_le();
        let status_flags = buf.get_u8();

        // Status flags: bits[2:3] = temperature status (use as overall status)
        let status = Status::from((status_flags >> 2) & 0x03);

        Ok(CurrentReading {
            co2: 0, // Aranet2 doesn't have CO2
            temperature: f32::from(temp_raw) / 20.0,
            pressure: 0.0, // Aranet2 doesn't have pressure
            // Humidity is reported in tenths of a percent; clamp to 100% as a
            // safeguard against sensor malfunction reporting out-of-range values.
            humidity: (humidity_raw / 10).min(100) as u8,
            battery,
            status,
            interval,
            age,
            captured_at: None,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
            radon_avg_24h: None,
            radon_avg_7d: None,
            radon_avg_30d: None,
        })
    }

    /// Parse a `CurrentReading` from raw bytes (Aranet Radon GATT format).
    ///
    /// The byte format is:
    /// - bytes 0-1: Device type marker (u16 LE, 0x0003 for radon)
    /// - bytes 2-3: Interval (u16 LE, seconds)
    /// - bytes 4-5: Age (u16 LE, seconds since update)
    /// - byte 6: Battery (u8)
    /// - bytes 7-8: Temperature (u16 LE, divide by 20 for Celsius)
    /// - bytes 9-10: Pressure (u16 LE, divide by 10 for hPa)
    /// - bytes 11-12: Humidity (u16 LE, divide by 10 for percent)
    /// - bytes 13-16: Radon (u32 LE, Bq/m³)
    /// - byte 17: Status (u8)
    ///
    /// Extended format (47 bytes) includes working averages:
    /// - bytes 18-21: 24h average time (u32 LE)
    /// - bytes 22-25: 24h average value (u32 LE, Bq/m³)
    /// - bytes 26-29: 7d average time (u32 LE)
    /// - bytes 30-33: 7d average value (u32 LE, Bq/m³)
    /// - bytes 34-37: 30d average time (u32 LE)
    /// - bytes 38-41: 30d average value (u32 LE, Bq/m³)
    /// - bytes 42-45: Initial progress (u32 LE, optional)
    /// - byte 46: Display type (u8, optional)
    ///
    /// Note: If an average value >= 0xff000000, it indicates the average
    /// is still being calculated (in progress) and is not yet available.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InsufficientBytes`] if `data` contains fewer than
    /// [`MIN_RADON_GATT_READING_BYTES`] (18) bytes.
    #[must_use = "parsing returns a Result that should be handled"]
    pub fn from_bytes_radon(data: &[u8]) -> Result<Self, ParseError> {
        use bytes::Buf;

        if data.len() < MIN_RADON_GATT_READING_BYTES {
            return Err(ParseError::InsufficientBytes {
                expected: MIN_RADON_GATT_READING_BYTES,
                actual: data.len(),
            });
        }

        let mut buf = data;

        // Parse header
        let _device_type = buf.get_u16_le(); // 0x0003 for radon
        let interval = buf.get_u16_le();
        let age = buf.get_u16_le();
        let battery = buf.get_u8();

        // Parse sensor values
        let temp_raw = buf.get_i16_le();
        let pressure_raw = buf.get_u16_le();
        let humidity_raw = buf.get_u16_le();
        let radon = buf.get_u32_le();
        let status = Status::from(buf.get_u8());

        // Parse optional working averages (extended format, 47 bytes)
        // Each average is a pair: (time: u32, value: u32)
        // If value >= 0xff000000, the average is still being calculated
        let (radon_avg_24h, radon_avg_7d, radon_avg_30d) = if buf.remaining() >= 24 {
            let _time_24h = buf.get_u32_le();
            let avg_24h_raw = buf.get_u32_le();
            let _time_7d = buf.get_u32_le();
            let avg_7d_raw = buf.get_u32_le();
            let _time_30d = buf.get_u32_le();
            let avg_30d_raw = buf.get_u32_le();

            // Values at or above RADON_AVERAGE_IN_PROGRESS are reserved by the
            // firmware to indicate the averaging period is still accumulating.
            let avg_24h = if avg_24h_raw >= RADON_AVERAGE_IN_PROGRESS {
                None
            } else {
                Some(avg_24h_raw)
            };
            let avg_7d = if avg_7d_raw >= RADON_AVERAGE_IN_PROGRESS {
                None
            } else {
                Some(avg_7d_raw)
            };
            let avg_30d = if avg_30d_raw >= RADON_AVERAGE_IN_PROGRESS {
                None
            } else {
                Some(avg_30d_raw)
            };

            (avg_24h, avg_7d, avg_30d)
        } else {
            (None, None, None)
        };

        Ok(CurrentReading {
            co2: 0,
            temperature: f32::from(temp_raw) / 20.0,
            pressure: f32::from(pressure_raw) / 10.0,
            // Humidity is reported in tenths of a percent; clamp to 100% as a
            // safeguard against sensor malfunction reporting out-of-range values.
            humidity: (humidity_raw / 10).min(100) as u8,
            battery,
            status,
            interval,
            age,
            captured_at: None,
            radon: Some(radon),
            radiation_rate: None,
            radiation_total: None,
            radon_avg_24h,
            radon_avg_7d,
            radon_avg_30d,
        })
    }

    /// Parse a `CurrentReading` from raw bytes (Aranet Radiation GATT format).
    ///
    /// The byte format is:
    /// - bytes 0-1: Unknown/header (u16 LE)
    /// - bytes 2-3: Interval (u16 LE, seconds)
    /// - bytes 4-5: Age (u16 LE, seconds)
    /// - byte 6: Battery (u8)
    /// - bytes 7-10: Dose rate (u32 LE, nSv/h, divide by 1000 for µSv/h)
    /// - bytes 11-18: Total dose (u64 LE, nSv, divide by `1_000_000` for mSv)
    /// - bytes 19-26: Duration (u64 LE, seconds) - not stored in `CurrentReading`
    /// - byte 27: Status (u8)
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InsufficientBytes`] if `data` contains fewer than
    /// [`MIN_RADIATION_READING_BYTES`] (28) bytes.
    #[must_use = "parsing returns a Result that should be handled"]
    #[allow(clippy::similar_names, clippy::cast_precision_loss)]
    pub fn from_bytes_radiation(data: &[u8]) -> Result<Self, ParseError> {
        use bytes::Buf;

        if data.len() < MIN_RADIATION_READING_BYTES {
            return Err(ParseError::InsufficientBytes {
                expected: MIN_RADIATION_READING_BYTES,
                actual: data.len(),
            });
        }

        let mut buf = data;

        // Parse header
        let _unknown = buf.get_u16_le();
        let interval = buf.get_u16_le();
        let age = buf.get_u16_le();
        let battery = buf.get_u8();

        // Parse radiation values
        let dose_rate_nsv = buf.get_u32_le();
        let total_dose_nsv = buf.get_u64_le();
        let _duration = buf.get_u64_le(); // Duration in seconds (not stored)
        let status = Status::from(buf.get_u8());

        // Convert units: nSv/h -> µSv/h, nSv -> mSv
        let dose_rate_usv = dose_rate_nsv as f32 / 1000.0;
        let total_dose_msv = total_dose_nsv as f64 / 1_000_000.0;

        Ok(CurrentReading {
            co2: 0,
            temperature: 0.0, // Radiation devices don't report temperature
            pressure: 0.0,
            humidity: 0,
            battery,
            status,
            interval,
            age,
            captured_at: None,
            radon: None,
            radiation_rate: Some(dose_rate_usv),
            radiation_total: Some(total_dose_msv),
            radon_avg_24h: None,
            radon_avg_7d: None,
            radon_avg_30d: None,
        })
    }

    /// Parse a `CurrentReading` from raw bytes based on device type.
    ///
    /// This dispatches to the appropriate parsing method based on the device type.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InsufficientBytes`] if `data` doesn't contain enough bytes
    /// for the specified device type.
    #[must_use = "parsing returns a Result that should be handled"]
    pub fn from_bytes_for_device(data: &[u8], device_type: DeviceType) -> Result<Self, ParseError> {
        match device_type {
            DeviceType::Aranet4 => Self::from_bytes_aranet4(data),
            DeviceType::Aranet2 => Self::from_bytes_aranet2(data),
            DeviceType::AranetRadon => Self::from_bytes_radon(data),
            DeviceType::AranetRadiation => Self::from_bytes_radiation(data),
        }
    }

    /// Set the captured timestamp to the current time minus the age.
    ///
    /// This is useful for setting the timestamp when reading from a device.
    #[must_use]
    pub fn with_captured_at(mut self, now: time::OffsetDateTime) -> Self {
        self.captured_at = Some(now - time::Duration::seconds(i64::from(self.age)));
        self
    }

    /// Create a builder for constructing `CurrentReading` with optional fields.
    pub fn builder() -> CurrentReadingBuilder {
        CurrentReadingBuilder::default()
    }
}

/// Builder for constructing `CurrentReading` with device-specific fields.
///
/// Use [`build`](Self::build) for unchecked construction, or [`try_build`](Self::try_build)
/// for validation of field values.
#[derive(Debug, Default)]
#[must_use]
pub struct CurrentReadingBuilder {
    reading: CurrentReading,
}

impl CurrentReadingBuilder {
    /// Set CO2 concentration (Aranet4).
    pub fn co2(mut self, co2: u16) -> Self {
        self.reading.co2 = co2;
        self
    }

    /// Set temperature.
    pub fn temperature(mut self, temp: f32) -> Self {
        self.reading.temperature = temp;
        self
    }

    /// Set pressure.
    pub fn pressure(mut self, pressure: f32) -> Self {
        self.reading.pressure = pressure;
        self
    }

    /// Set humidity (0-100).
    pub fn humidity(mut self, humidity: u8) -> Self {
        self.reading.humidity = humidity;
        self
    }

    /// Set battery level (0-100).
    pub fn battery(mut self, battery: u8) -> Self {
        self.reading.battery = battery;
        self
    }

    /// Set status.
    pub fn status(mut self, status: Status) -> Self {
        self.reading.status = status;
        self
    }

    /// Set measurement interval.
    pub fn interval(mut self, interval: u16) -> Self {
        self.reading.interval = interval;
        self
    }

    /// Set reading age.
    pub fn age(mut self, age: u16) -> Self {
        self.reading.age = age;
        self
    }

    /// Set the captured timestamp.
    pub fn captured_at(mut self, timestamp: time::OffsetDateTime) -> Self {
        self.reading.captured_at = Some(timestamp);
        self
    }

    /// Set radon concentration (`AranetRn+`).
    pub fn radon(mut self, radon: u32) -> Self {
        self.reading.radon = Some(radon);
        self
    }

    /// Set radiation dose rate (Aranet Radiation).
    pub fn radiation_rate(mut self, rate: f32) -> Self {
        self.reading.radiation_rate = Some(rate);
        self
    }

    /// Set total radiation dose (Aranet Radiation).
    pub fn radiation_total(mut self, total: f64) -> Self {
        self.reading.radiation_total = Some(total);
        self
    }

    /// Set 24-hour average radon concentration (`AranetRn+`).
    pub fn radon_avg_24h(mut self, avg: u32) -> Self {
        self.reading.radon_avg_24h = Some(avg);
        self
    }

    /// Set 7-day average radon concentration (`AranetRn+`).
    pub fn radon_avg_7d(mut self, avg: u32) -> Self {
        self.reading.radon_avg_7d = Some(avg);
        self
    }

    /// Set 30-day average radon concentration (`AranetRn+`).
    pub fn radon_avg_30d(mut self, avg: u32) -> Self {
        self.reading.radon_avg_30d = Some(avg);
        self
    }

    /// Build the `CurrentReading` without validation.
    #[must_use]
    pub fn build(self) -> CurrentReading {
        self.reading
    }

    /// Build the `CurrentReading` with validation.
    ///
    /// Validates:
    /// - `humidity` is 0-100
    /// - `battery` is 0-100
    /// - `temperature` is within reasonable range (-40 to 100°C)
    /// - `pressure` is within reasonable range (800-1200 hPa) or 0
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidValue`] if any field has an invalid value.
    pub fn try_build(self) -> Result<CurrentReading, ParseError> {
        if self.reading.humidity > 100 {
            return Err(ParseError::InvalidValue(format!(
                "humidity {} exceeds maximum of 100",
                self.reading.humidity
            )));
        }

        if self.reading.battery > 100 {
            return Err(ParseError::InvalidValue(format!(
                "battery {} exceeds maximum of 100",
                self.reading.battery
            )));
        }

        // Temperature range check (typical sensor range)
        if self.reading.temperature < -40.0 || self.reading.temperature > 100.0 {
            return Err(ParseError::InvalidValue(format!(
                "temperature {} is outside valid range (-40 to 100°C)",
                self.reading.temperature
            )));
        }

        // Pressure range check (0 is valid for devices without pressure sensor)
        if self.reading.pressure != 0.0
            && (self.reading.pressure < 800.0 || self.reading.pressure > 1200.0)
        {
            return Err(ParseError::InvalidValue(format!(
                "pressure {} is outside valid range (800-1200 hPa)",
                self.reading.pressure
            )));
        }

        // CO2 range check (0 is valid for non-CO2 devices; sensor max is ~10000 ppm)
        if self.reading.co2 > 10_000 {
            return Err(ParseError::InvalidValue(format!(
                "co2 {} exceeds maximum sensor range of 10000 ppm",
                self.reading.co2
            )));
        }

        // Radon range check (typical indoor range: 0–10000 Bq/m³)
        if let Some(radon) = self.reading.radon
            && radon > 10_000
        {
            return Err(ParseError::InvalidValue(format!(
                "radon {} exceeds maximum expected range of 10000 Bq/m³",
                radon
            )));
        }

        Ok(self.reading)
    }
}

/// Device information from an Aranet sensor.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DeviceInfo {
    /// Device name.
    pub name: String,
    /// Model number.
    pub model: String,
    /// Serial number.
    pub serial: String,
    /// Firmware version.
    pub firmware: String,
    /// Hardware revision.
    pub hardware: String,
    /// Software revision.
    pub software: String,
    /// Manufacturer name.
    pub manufacturer: String,
}

impl DeviceInfo {
    /// Create a builder for constructing `DeviceInfo`.
    pub fn builder() -> DeviceInfoBuilder {
        DeviceInfoBuilder::default()
    }
}

/// Builder for constructing `DeviceInfo`.
#[derive(Debug, Default, Clone)]
#[must_use]
pub struct DeviceInfoBuilder {
    info: DeviceInfo,
}

impl DeviceInfoBuilder {
    /// Set the device name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.info.name = name.into();
        self
    }

    /// Set the model number.
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.info.model = model.into();
        self
    }

    /// Set the serial number.
    pub fn serial(mut self, serial: impl Into<String>) -> Self {
        self.info.serial = serial.into();
        self
    }

    /// Set the firmware version.
    pub fn firmware(mut self, firmware: impl Into<String>) -> Self {
        self.info.firmware = firmware.into();
        self
    }

    /// Set the hardware revision.
    pub fn hardware(mut self, hardware: impl Into<String>) -> Self {
        self.info.hardware = hardware.into();
        self
    }

    /// Set the software revision.
    pub fn software(mut self, software: impl Into<String>) -> Self {
        self.info.software = software.into();
        self
    }

    /// Set the manufacturer name.
    pub fn manufacturer(mut self, manufacturer: impl Into<String>) -> Self {
        self.info.manufacturer = manufacturer.into();
        self
    }

    /// Build the `DeviceInfo`.
    #[must_use]
    pub fn build(self) -> DeviceInfo {
        self.info
    }
}

/// A historical reading record from an Aranet sensor.
///
/// This struct supports all Aranet device types:
/// - **Aranet4**: CO2, temperature, pressure, humidity
/// - **Aranet2**: Temperature, humidity (co2 and pressure will be 0)
/// - **`AranetRn+`**: Radon, temperature, pressure, humidity (co2 will be 0)
/// - **Aranet Radiation**: Radiation rate/total, temperature (uses `radiation_*` fields)
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct HistoryRecord {
    /// Timestamp of the reading.
    pub timestamp: time::OffsetDateTime,
    /// CO2 concentration in ppm (Aranet4) or 0 for other devices.
    pub co2: u16,
    /// Temperature in degrees Celsius.
    pub temperature: f32,
    /// Atmospheric pressure in hPa (0 for Aranet2).
    pub pressure: f32,
    /// Relative humidity percentage (0-100).
    pub humidity: u8,
    /// Radon concentration in Bq/m³ (`AranetRn+` only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radon: Option<u32>,
    /// Radiation dose rate in µSv/h (Aranet Radiation only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radiation_rate: Option<f32>,
    /// Total radiation dose in mSv (Aranet Radiation only).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub radiation_total: Option<f64>,
}

impl Default for HistoryRecord {
    fn default() -> Self {
        Self {
            timestamp: time::OffsetDateTime::UNIX_EPOCH,
            co2: 0,
            temperature: 0.0,
            pressure: 0.0,
            humidity: 0,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
        }
    }
}

impl HistoryRecord {
    /// Create a builder for constructing `HistoryRecord` with optional fields.
    pub fn builder() -> HistoryRecordBuilder {
        HistoryRecordBuilder::default()
    }
}

/// Builder for constructing `HistoryRecord` with device-specific fields.
#[derive(Debug, Default)]
#[must_use]
pub struct HistoryRecordBuilder {
    record: HistoryRecord,
}

impl HistoryRecordBuilder {
    /// Set the timestamp.
    pub fn timestamp(mut self, timestamp: time::OffsetDateTime) -> Self {
        self.record.timestamp = timestamp;
        self
    }

    /// Set CO2 concentration (Aranet4).
    pub fn co2(mut self, co2: u16) -> Self {
        self.record.co2 = co2;
        self
    }

    /// Set temperature.
    pub fn temperature(mut self, temp: f32) -> Self {
        self.record.temperature = temp;
        self
    }

    /// Set pressure.
    pub fn pressure(mut self, pressure: f32) -> Self {
        self.record.pressure = pressure;
        self
    }

    /// Set humidity.
    pub fn humidity(mut self, humidity: u8) -> Self {
        self.record.humidity = humidity;
        self
    }

    /// Set radon concentration (`AranetRn+`).
    pub fn radon(mut self, radon: u32) -> Self {
        self.record.radon = Some(radon);
        self
    }

    /// Set radiation dose rate (Aranet Radiation).
    pub fn radiation_rate(mut self, rate: f32) -> Self {
        self.record.radiation_rate = Some(rate);
        self
    }

    /// Set total radiation dose (Aranet Radiation).
    pub fn radiation_total(mut self, total: f64) -> Self {
        self.record.radiation_total = Some(total);
        self
    }

    /// Build the `HistoryRecord`.
    #[must_use]
    pub fn build(self) -> HistoryRecord {
        self.record
    }
}