aranet-core 0.2.0

Core BLE library 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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
//! Historical data download.
//!
//! This module provides functionality to download historical sensor
//! readings stored on an Aranet device.
//!
//! # Supported Devices
//!
//! | Device | History Support | Notes |
//! |--------|-----------------|-------|
//! | Aranet4 | Full | COâ‚‚, temperature, pressure, humidity |
//! | Aranet2 | Full | Temperature, humidity |
//! | AranetRn+ (Radon) | Full | Radon, temperature, pressure, humidity |
//! | Aranet Radiation | Not supported | BLE protocol undocumented by manufacturer |
//!
//! **Note:** Aranet Radiation devices do not support history download because
//! the BLE protocol for historical radiation data is not publicly documented
//! by SAF Tehnika. Attempting to download history will return [`Error::Unsupported`].
//! Use [`Device::read_current()`](crate::device::Device::read_current) for
//! current radiation readings.
//!
//! # Index Convention
//!
//! **All history indices are 1-based**, following the Aranet device protocol:
//! - Index 1 = oldest reading
//! - Index N = newest reading (where N = total_readings)
//!
//! This matches the device's internal indexing. When specifying ranges:
//! ```ignore
//! let options = HistoryOptions {
//!     start_index: Some(1),    // First reading
//!     end_index: Some(100),    // 100th reading
//!     ..Default::default()
//! };
//! ```
//!
//! # Protocols
//!
//! Aranet devices support two history protocols:
//! - **V1**: Notification-based (older devices) - uses characteristic notifications
//! - **V2**: Read-based (newer devices, preferred) - direct read/write operations

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use bytes::Buf;
use time::OffsetDateTime;
use tokio::time::sleep;
use tracing::{debug, info, warn};

use crate::commands::{HISTORY_V1_REQUEST, HISTORY_V2_REQUEST};
use crate::device::Device;
use crate::error::{Error, Result};
use crate::uuid::{COMMAND, HISTORY_V2, READ_INTERVAL, SECONDS_SINCE_UPDATE, TOTAL_READINGS};
use aranet_types::HistoryRecord;

/// Progress information for history download.
#[derive(Debug, Clone)]
pub struct HistoryProgress {
    /// Current parameter being downloaded.
    pub current_param: HistoryParam,
    /// Parameter index (1-based, e.g., 1 of 4).
    pub param_index: usize,
    /// Total number of parameters to download.
    pub total_params: usize,
    /// Number of values downloaded for current parameter.
    pub values_downloaded: usize,
    /// Total values to download for current parameter.
    pub total_values: usize,
    /// Overall progress (0.0 to 1.0).
    pub overall_progress: f32,
}

impl HistoryProgress {
    /// Create a new progress struct.
    pub fn new(
        param: HistoryParam,
        param_idx: usize,
        total_params: usize,
        total_values: usize,
    ) -> Self {
        Self {
            current_param: param,
            param_index: param_idx,
            total_params,
            values_downloaded: 0,
            total_values,
            overall_progress: 0.0,
        }
    }

    fn update(&mut self, values_downloaded: usize) {
        self.values_downloaded = values_downloaded;
        let param_progress = if self.total_values > 0 {
            values_downloaded as f32 / self.total_values as f32
        } else {
            1.0
        };
        // Guard against division by zero when total_params is 0
        if self.total_params == 0 {
            self.overall_progress = 1.0;
            return;
        }
        let base_progress = (self.param_index - 1) as f32 / self.total_params as f32;
        let param_contribution = param_progress / self.total_params as f32;
        self.overall_progress = base_progress + param_contribution;
    }
}

/// Type alias for progress callback function.
pub type ProgressCallback = Arc<dyn Fn(HistoryProgress) + Send + Sync>;

/// Type alias for checkpoint callback function.
pub type CheckpointCallback = Arc<dyn Fn(HistoryCheckpoint) + Send + Sync>;

/// Checkpoint data for resuming interrupted history downloads.
///
/// This can be serialized and saved to disk to allow resuming downloads
/// after disconnection or application restart.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HistoryCheckpoint {
    /// Device identifier this checkpoint belongs to.
    pub device_id: String,
    /// The parameter currently being downloaded.
    pub current_param: HistoryParamCheckpoint,
    /// Index where download should resume for current parameter.
    pub resume_index: u16,
    /// Total readings on the device when checkpoint was created.
    pub total_readings: u16,
    /// Which parameters have been fully downloaded.
    pub completed_params: Vec<HistoryParamCheckpoint>,
    /// Timestamp when checkpoint was created.
    pub created_at: time::OffsetDateTime,
    /// Downloaded values for completed parameters (serialized).
    pub downloaded_data: Option<PartialHistoryData>,
}

/// Serializable version of HistoryParam for checkpoints.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum HistoryParamCheckpoint {
    Temperature,
    Humidity,
    Pressure,
    Co2,
    Humidity2,
    Radon,
}

impl From<HistoryParam> for HistoryParamCheckpoint {
    fn from(param: HistoryParam) -> Self {
        match param {
            HistoryParam::Temperature => HistoryParamCheckpoint::Temperature,
            HistoryParam::Humidity => HistoryParamCheckpoint::Humidity,
            HistoryParam::Pressure => HistoryParamCheckpoint::Pressure,
            HistoryParam::Co2 => HistoryParamCheckpoint::Co2,
            HistoryParam::Humidity2 => HistoryParamCheckpoint::Humidity2,
            HistoryParam::Radon => HistoryParamCheckpoint::Radon,
        }
    }
}

impl From<HistoryParamCheckpoint> for HistoryParam {
    fn from(param: HistoryParamCheckpoint) -> Self {
        match param {
            HistoryParamCheckpoint::Temperature => HistoryParam::Temperature,
            HistoryParamCheckpoint::Humidity => HistoryParam::Humidity,
            HistoryParamCheckpoint::Pressure => HistoryParam::Pressure,
            HistoryParamCheckpoint::Co2 => HistoryParam::Co2,
            HistoryParamCheckpoint::Humidity2 => HistoryParam::Humidity2,
            HistoryParamCheckpoint::Radon => HistoryParam::Radon,
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct U16HistoryStep {
    param: HistoryParam,
    step: usize,
    total_steps: usize,
    next_param: Option<HistoryParamCheckpoint>,
}

/// Partially downloaded history data for checkpoint resume.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct PartialHistoryData {
    pub co2_values: Vec<u16>,
    pub temp_values: Vec<u16>,
    pub pressure_values: Vec<u16>,
    pub humidity_values: Vec<u16>,
    pub radon_values: Vec<u32>,
}

impl HistoryCheckpoint {
    /// Create a new checkpoint for starting a fresh download.
    pub fn new(device_id: &str, total_readings: u16, first_param: HistoryParam) -> Self {
        Self {
            device_id: device_id.to_string(),
            current_param: first_param.into(),
            resume_index: 1,
            total_readings,
            completed_params: Vec::new(),
            created_at: time::OffsetDateTime::now_utc(),
            downloaded_data: Some(PartialHistoryData::default()),
        }
    }

    /// Check if this checkpoint is still valid for the given device state.
    pub fn is_valid(&self, current_total_readings: u16) -> bool {
        // Checkpoint is valid if the device hasn't collected more readings
        // (which would shift the indices)
        self.total_readings == current_total_readings
    }

    /// Update the checkpoint after completing a parameter.
    pub fn complete_param(&mut self, param: HistoryParam, values: Vec<u16>) {
        self.completed_params.push(param.into());
        if let Some(ref mut data) = self.downloaded_data {
            match param {
                HistoryParam::Co2 => data.co2_values = values,
                HistoryParam::Temperature => data.temp_values = values,
                HistoryParam::Pressure => data.pressure_values = values,
                HistoryParam::Humidity | HistoryParam::Humidity2 => data.humidity_values = values,
                HistoryParam::Radon => {} // Radon uses u32, handled separately
            }
        }
    }

    /// Update the checkpoint after completing a radon parameter.
    pub fn complete_radon_param(&mut self, values: Vec<u32>) {
        self.completed_params.push(HistoryParamCheckpoint::Radon);
        if let Some(ref mut data) = self.downloaded_data {
            data.radon_values = values;
        }
    }
}

/// Parameter types for history requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum HistoryParam {
    Temperature = 1,
    Humidity = 2,
    Pressure = 3,
    Co2 = 4,
    /// Humidity for Aranet2/Radon (different encoding).
    Humidity2 = 5,
    /// Radon concentration (Bq/m³) for AranetRn+.
    Radon = 10,
}

/// Options for downloading history.
///
/// # Index Convention
///
/// Indices are **1-based** to match the Aranet device protocol:
/// - `start_index: Some(1)` means the first (oldest) reading
/// - `end_index: Some(100)` means the 100th reading
/// - `start_index: None` defaults to 1 (beginning)
/// - `end_index: None` defaults to total_readings (end)
///
/// # Progress Reporting
///
/// Use `with_progress` to receive updates during download:
/// ```ignore
/// let options = HistoryOptions::default()
///     .with_progress(|p| println!("Progress: {:.1}%", p.overall_progress * 100.0));
/// ```
///
/// # Adaptive Read Delay
///
/// Use `adaptive_delay` to automatically adjust delay based on signal quality:
/// ```ignore
/// let options = HistoryOptions::default().adaptive_delay(true);
/// ```
///
/// # Resume Support
///
/// For long downloads, use checkpointing to allow resume on failure:
/// ```ignore
/// let checkpoint = HistoryCheckpoint::load("device_123")?;
/// let options = HistoryOptions::default().resume_from(checkpoint);
/// ```
#[derive(Clone)]
pub struct HistoryOptions {
    /// Starting index (1-based, inclusive). If None, downloads from the beginning (index 1).
    pub start_index: Option<u16>,
    /// Ending index (1-based, inclusive). If None, downloads to the end (index = total_readings).
    pub end_index: Option<u16>,
    /// Delay between read operations to avoid overwhelming the device.
    pub read_delay: Duration,
    /// Progress callback (optional).
    pub progress_callback: Option<ProgressCallback>,
    /// Whether to use adaptive delay based on signal quality.
    pub use_adaptive_delay: bool,
    /// Checkpoint callback for saving progress during download (optional).
    /// Called periodically with the current checkpoint state.
    pub checkpoint_callback: Option<CheckpointCallback>,
    /// How often to call the checkpoint callback (in records).
    pub checkpoint_interval: usize,
}

impl std::fmt::Debug for HistoryOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HistoryOptions")
            .field("start_index", &self.start_index)
            .field("end_index", &self.end_index)
            .field("read_delay", &self.read_delay)
            .field("progress_callback", &self.progress_callback.is_some())
            .field("use_adaptive_delay", &self.use_adaptive_delay)
            .field("checkpoint_callback", &self.checkpoint_callback.is_some())
            .field("checkpoint_interval", &self.checkpoint_interval)
            .finish()
    }
}

impl Default for HistoryOptions {
    fn default() -> Self {
        Self {
            start_index: None,
            end_index: None,
            read_delay: Duration::from_millis(50),
            progress_callback: None,
            use_adaptive_delay: false,
            checkpoint_callback: None,
            checkpoint_interval: 100, // Checkpoint every 100 records
        }
    }
}

impl HistoryOptions {
    /// Create new history options with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the starting index (1-based).
    #[must_use]
    pub fn start_index(mut self, index: u16) -> Self {
        self.start_index = Some(index);
        self
    }

    /// Set the ending index (1-based).
    #[must_use]
    pub fn end_index(mut self, index: u16) -> Self {
        self.end_index = Some(index);
        self
    }

    /// Set the delay between read operations.
    #[must_use]
    pub fn read_delay(mut self, delay: Duration) -> Self {
        self.read_delay = delay;
        self
    }

    /// Set a progress callback.
    #[must_use]
    pub fn with_progress<F>(mut self, callback: F) -> Self
    where
        F: Fn(HistoryProgress) + Send + Sync + 'static,
    {
        self.progress_callback = Some(Arc::new(callback));
        self
    }

    /// Report progress if a callback is set.
    pub fn report_progress(&self, progress: &HistoryProgress) {
        if let Some(cb) = &self.progress_callback {
            cb(progress.clone());
        }
    }

    /// Enable or disable adaptive delay based on signal quality.
    ///
    /// When enabled, the read delay will be automatically adjusted based on
    /// the connection's signal strength:
    /// - Excellent signal: 30ms delay
    /// - Good signal: 50ms delay
    /// - Fair signal: 100ms delay
    /// - Poor signal: 200ms delay
    #[must_use]
    pub fn adaptive_delay(mut self, enable: bool) -> Self {
        self.use_adaptive_delay = enable;
        self
    }

    /// Set a checkpoint callback for saving download progress.
    ///
    /// The callback will be invoked periodically (based on `checkpoint_interval`)
    /// with the current checkpoint state, allowing recovery from interruptions.
    #[must_use]
    pub fn with_checkpoint<F>(mut self, callback: F) -> Self
    where
        F: Fn(HistoryCheckpoint) + Send + Sync + 'static,
    {
        self.checkpoint_callback = Some(Arc::new(callback));
        self
    }

    /// Set how often to call the checkpoint callback (in records).
    ///
    /// Default: 100 records
    #[must_use]
    pub fn checkpoint_interval(mut self, interval: usize) -> Self {
        self.checkpoint_interval = interval;
        self
    }

    /// Resume from a previous checkpoint.
    ///
    /// This sets the start_index based on the checkpoint's resume position.
    #[must_use]
    pub fn resume_from(mut self, checkpoint: &HistoryCheckpoint) -> Self {
        self.start_index = Some(checkpoint.resume_index);
        self
    }

    /// Report a checkpoint if a callback is set.
    pub fn report_checkpoint(&self, checkpoint: &HistoryCheckpoint) {
        if let Some(cb) = &self.checkpoint_callback {
            cb(checkpoint.clone());
        }
    }

    /// Get the effective read delay, optionally adjusted for signal quality.
    pub fn effective_read_delay(
        &self,
        signal_quality: Option<crate::device::SignalQuality>,
    ) -> Duration {
        if self.use_adaptive_delay
            && let Some(quality) = signal_quality
        {
            return quality.recommended_read_delay();
        }
        self.read_delay
    }
}

/// Information about the device's stored history.
#[derive(Debug, Clone)]
pub struct HistoryInfo {
    /// Total number of readings stored.
    pub total_readings: u16,
    /// Measurement interval in seconds.
    pub interval_seconds: u16,
    /// Seconds since the last reading.
    pub seconds_since_update: u16,
}

impl Device {
    /// Get information about the stored history.
    pub async fn get_history_info(&self) -> Result<HistoryInfo> {
        // Read total readings count
        let total_data = self.read_characteristic(TOTAL_READINGS).await?;
        let total_readings = if total_data.len() >= 2 {
            u16::from_le_bytes([total_data[0], total_data[1]])
        } else {
            return Err(Error::InvalidData(
                "Invalid total readings data".to_string(),
            ));
        };

        // Read interval
        let interval_data = self.read_characteristic(READ_INTERVAL).await?;
        let interval_seconds = if interval_data.len() >= 2 {
            u16::from_le_bytes([interval_data[0], interval_data[1]])
        } else {
            return Err(Error::InvalidData("Invalid interval data".to_string()));
        };

        // Read seconds since update
        let age_data = self.read_characteristic(SECONDS_SINCE_UPDATE).await?;
        let seconds_since_update = if age_data.len() >= 2 {
            u16::from_le_bytes([age_data[0], age_data[1]])
        } else {
            0
        };

        Ok(HistoryInfo {
            total_readings,
            interval_seconds,
            seconds_since_update,
        })
    }

    /// Download all historical readings from the device.
    pub async fn download_history(&self) -> Result<Vec<HistoryRecord>> {
        self.download_history_with_options(HistoryOptions::default())
            .await
    }

    /// Download historical readings with custom options.
    ///
    /// # Device Support
    ///
    /// - **Aranet4**: Downloads COâ‚‚, temperature, pressure, humidity
    /// - **Aranet2**: Downloads temperature, humidity
    /// - **AranetRn+ (Radon)**: Downloads radon, temperature, pressure, humidity
    /// - **Aranet Radiation**: **Not supported** - returns an error. The device protocol
    ///   for historical radiation data requires additional documentation. Use
    ///   [`Device::read_current()`](crate::device::Device::read_current) to get
    ///   current radiation readings.
    ///
    /// # Adaptive Delay
    ///
    /// If `options.use_adaptive_delay` is enabled, the read delay will be
    /// automatically adjusted based on the connection's signal quality.
    ///
    /// # Checkpointing
    ///
    /// If a checkpoint callback is set, progress will be saved periodically
    /// to allow resuming interrupted downloads.
    pub async fn download_history_with_options(
        &self,
        options: HistoryOptions,
    ) -> Result<Vec<HistoryRecord>> {
        use aranet_types::DeviceType;

        let info = self.get_history_info().await?;
        info!(
            "Device has {} readings, interval {}s, last update {}s ago",
            info.total_readings, info.interval_seconds, info.seconds_since_update
        );

        if info.total_readings == 0 {
            return Ok(Vec::new());
        }

        let start_idx = options.start_index.unwrap_or(1);
        let end_idx = options.end_index.unwrap_or(info.total_readings);

        if start_idx > end_idx {
            return Err(Error::InvalidConfig(format!(
                "start_index ({start_idx}) must be <= end_index ({end_idx})"
            )));
        }
        if start_idx == 0 {
            return Err(Error::InvalidConfig(
                "start_index must be >= 1 (indices are 1-based)".into(),
            ));
        }

        // Get signal quality for adaptive delay if enabled
        let signal_quality = if options.use_adaptive_delay {
            match self.signal_quality().await {
                Some(quality) => {
                    info!(
                        "Signal quality: {:?} - using {} ms read delay",
                        quality,
                        quality.recommended_read_delay().as_millis()
                    );
                    Some(quality)
                }
                None => {
                    debug!("Could not read signal quality, using default delay");
                    None
                }
            }
        } else {
            None
        };

        // Calculate effective read delay
        let effective_delay = options.effective_read_delay(signal_quality);

        // Dispatch based on device type
        match self.device_type() {
            Some(DeviceType::AranetRadiation) => {
                // Aranet Radiation history download is not supported.
                // The BLE protocol for historical radiation data differs from other
                // Aranet devices and is not publicly documented by SAF Tehnika.
                Err(Error::Unsupported(
                    "History download is not available for Aranet Radiation devices. \
                     The radiation history protocol is not documented. \
                     Use read_current() for current radiation readings."
                        .to_string(),
                ))
            }
            Some(DeviceType::AranetRadon) => {
                // For radon devices, download radon instead of CO2, and use Humidity2
                self.download_radon_history_internal(
                    &info,
                    start_idx,
                    end_idx,
                    &options,
                    effective_delay,
                )
                .await
            }
            Some(DeviceType::Aranet2) => {
                // For Aranet2, download temperature and humidity only
                self.download_aranet2_history_internal(
                    &info,
                    start_idx,
                    end_idx,
                    &options,
                    effective_delay,
                )
                .await
            }
            _ => {
                // For Aranet4 (and unknown devices), download CO2, temp, pressure, humidity
                self.download_aranet4_history_internal(
                    &info,
                    start_idx,
                    end_idx,
                    &options,
                    effective_delay,
                )
                .await
            }
        }
    }

    /// Download a u16 parameter with progress reporting and checkpoint updates.
    ///
    /// This is the common pattern shared by all parameter downloads except radon (u32).
    /// Returns the downloaded values.
    async fn download_u16_param_with_checkpoint(
        &self,
        step_info: U16HistoryStep,
        start_idx: u16,
        end_idx: u16,
        effective_delay: Duration,
        options: &HistoryOptions,
        checkpoint: &mut Option<HistoryCheckpoint>,
    ) -> Result<Vec<u16>> {
        let total_values = (end_idx - start_idx + 1) as usize;
        let mut progress = HistoryProgress::new(
            step_info.param,
            step_info.step,
            step_info.total_steps,
            total_values,
        );
        options.report_progress(&progress);

        let values = self
            .download_param_history_with_progress(
                step_info.param,
                start_idx,
                end_idx,
                effective_delay,
                |downloaded| {
                    progress.update(downloaded);
                    options.report_progress(&progress);
                },
            )
            .await?;

        if let Some(cp) = checkpoint {
            cp.complete_param(step_info.param, values.clone());
            if let Some(next) = step_info.next_param {
                cp.current_param = next;
                cp.resume_index = start_idx;
            }
            options.report_checkpoint(cp);
        }

        Ok(values)
    }

    /// Download history for Aranet4 devices (CO2, temp, pressure, humidity).
    async fn download_aranet4_history_internal(
        &self,
        info: &HistoryInfo,
        start_idx: u16,
        end_idx: u16,
        options: &HistoryOptions,
        effective_delay: Duration,
    ) -> Result<Vec<HistoryRecord>> {
        if start_idx > end_idx {
            return Ok(Vec::new());
        }

        let device_id = self.address().to_string();
        let mut checkpoint = if options.checkpoint_callback.is_some() {
            Some(HistoryCheckpoint::new(
                &device_id,
                info.total_readings,
                HistoryParam::Co2,
            ))
        } else {
            None
        };

        let co2_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Co2,
                    step: 1,
                    total_steps: 4,
                    next_param: Some(HistoryParamCheckpoint::Temperature),
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let temp_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Temperature,
                    step: 2,
                    total_steps: 4,
                    next_param: Some(HistoryParamCheckpoint::Pressure),
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let pressure_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Pressure,
                    step: 3,
                    total_steps: 4,
                    next_param: Some(HistoryParamCheckpoint::Humidity),
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let humidity_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Humidity,
                    step: 4,
                    total_steps: 4,
                    next_param: None,
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let records = build_history_records(
            info,
            &co2_values,
            &temp_values,
            &pressure_values,
            &humidity_values,
            &[],
        );

        info!("Downloaded {} history records", records.len());
        Ok(records)
    }

    /// Download history for Aranet2 devices (temperature, humidity only).
    async fn download_aranet2_history_internal(
        &self,
        info: &HistoryInfo,
        start_idx: u16,
        end_idx: u16,
        options: &HistoryOptions,
        effective_delay: Duration,
    ) -> Result<Vec<HistoryRecord>> {
        if start_idx > end_idx {
            return Ok(Vec::new());
        }

        let device_id = self.address().to_string();
        let mut checkpoint = if options.checkpoint_callback.is_some() {
            Some(HistoryCheckpoint::new(
                &device_id,
                info.total_readings,
                HistoryParam::Temperature,
            ))
        } else {
            None
        };

        let temp_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Temperature,
                    step: 1,
                    total_steps: 2,
                    next_param: Some(HistoryParamCheckpoint::Humidity2),
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let humidity_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Humidity2,
                    step: 2,
                    total_steps: 2,
                    next_param: None,
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        // Build records with no CO2, no pressure, no radon
        let records = build_history_records(info, &[], &temp_values, &[], &humidity_values, &[]);

        info!("Downloaded {} Aranet2 history records", records.len());
        Ok(records)
    }

    /// Download history for AranetRn+ devices (radon, temp, pressure, humidity).
    async fn download_radon_history_internal(
        &self,
        info: &HistoryInfo,
        start_idx: u16,
        end_idx: u16,
        options: &HistoryOptions,
        effective_delay: Duration,
    ) -> Result<Vec<HistoryRecord>> {
        if start_idx > end_idx {
            return Ok(Vec::new());
        }
        let total_values = (end_idx - start_idx + 1) as usize;

        let device_id = self.address().to_string();
        let mut checkpoint = if options.checkpoint_callback.is_some() {
            Some(HistoryCheckpoint::new(
                &device_id,
                info.total_readings,
                HistoryParam::Radon,
            ))
        } else {
            None
        };

        // Download radon values (4 bytes each, uses u32 variant)
        let mut progress = HistoryProgress::new(HistoryParam::Radon, 1, 4, total_values);
        options.report_progress(&progress);

        let radon_values = self
            .download_param_history_u32_with_progress(
                HistoryParam::Radon,
                start_idx,
                end_idx,
                effective_delay,
                |downloaded| {
                    progress.update(downloaded);
                    options.report_progress(&progress);
                },
            )
            .await?;

        if let Some(ref mut cp) = checkpoint {
            cp.complete_radon_param(radon_values.clone());
            cp.current_param = HistoryParamCheckpoint::Temperature;
            cp.resume_index = start_idx;
            options.report_checkpoint(cp);
        }

        let temp_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Temperature,
                    step: 2,
                    total_steps: 4,
                    next_param: Some(HistoryParamCheckpoint::Pressure),
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let pressure_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Pressure,
                    step: 3,
                    total_steps: 4,
                    next_param: Some(HistoryParamCheckpoint::Humidity2),
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let humidity_values = self
            .download_u16_param_with_checkpoint(
                U16HistoryStep {
                    param: HistoryParam::Humidity2,
                    step: 4,
                    total_steps: 4,
                    next_param: None,
                },
                start_idx,
                end_idx,
                effective_delay,
                options,
                &mut checkpoint,
            )
            .await?;

        let records = build_history_records(
            info,
            &[],
            &temp_values,
            &pressure_values,
            &humidity_values,
            &radon_values,
        );

        info!("Downloaded {} radon history records", records.len());
        Ok(records)
    }

    /// Download a single parameter's history using V2 protocol with progress callback.
    ///
    /// This is a generic implementation that handles different value sizes:
    /// - 1 byte: humidity
    /// - 2 bytes: CO2, temperature, pressure, humidity2
    /// - 4 bytes: radon
    #[allow(clippy::too_many_arguments)]
    async fn download_param_history_generic_with_progress<T, F>(
        &self,
        param: HistoryParam,
        start_idx: u16,
        end_idx: u16,
        read_delay: Duration,
        value_parser: impl Fn(&[u8], usize) -> Option<T>,
        value_size: usize,
        mut on_progress: F,
    ) -> Result<Vec<T>>
    where
        T: Default + Clone,
        F: FnMut(usize),
    {
        debug!(
            "Downloading {:?} history from {} to {} (value_size={})",
            param, start_idx, end_idx, value_size
        );

        let mut values: BTreeMap<u16, T> = BTreeMap::new();
        let mut current_idx = start_idx;
        let mut consecutive_wrong_param = 0u32;
        const MAX_WRONG_PARAM_RETRIES: u32 = 5;

        while current_idx <= end_idx {
            // Send V2 history request using command constant
            let cmd = [
                HISTORY_V2_REQUEST,
                param as u8,
                (current_idx & 0xFF) as u8,
                ((current_idx >> 8) & 0xFF) as u8,
            ];

            self.write_characteristic(COMMAND, &cmd).await?;
            sleep(read_delay).await;

            // Read response
            let response = self.read_characteristic(HISTORY_V2).await?;

            // V2 response format (10-byte header):
            // Byte 0: param (1 byte)
            // Bytes 1-2: interval (2 bytes, little-endian)
            // Bytes 3-4: total_readings (2 bytes, little-endian)
            // Bytes 5-6: ago (2 bytes, little-endian)
            // Bytes 7-8: start index (2 bytes, little-endian)
            // Byte 9: count (1 byte)
            // Bytes 10+: data values
            if response.len() < 10 {
                warn!(
                    "Invalid history response: too short ({} bytes)",
                    response.len()
                );
                break;
            }

            let resp_param = response[0];
            if resp_param != param as u8 {
                consecutive_wrong_param += 1;
                warn!(
                    "Unexpected parameter in response: {} (retry {}/{})",
                    resp_param, consecutive_wrong_param, MAX_WRONG_PARAM_RETRIES
                );
                if consecutive_wrong_param >= MAX_WRONG_PARAM_RETRIES {
                    warn!("Too many wrong parameter responses, aborting download");
                    break;
                }
                // Wait and retry - device may not have processed command yet
                sleep(read_delay).await;
                continue;
            }
            consecutive_wrong_param = 0;

            // Parse header
            let resp_start = u16::from_le_bytes([response[7], response[8]]);
            let resp_count = response[9] as usize;

            debug!(
                "History response: param={}, start={}, count={}",
                resp_param, resp_start, resp_count
            );

            // Check if we've reached the end (count == 0)
            if resp_count == 0 {
                debug!("Reached end of history (count=0)");
                break;
            }

            // Parse data values
            let data = &response[10..];
            let num_values = (data.len() / value_size).min(resp_count);

            for i in 0..num_values {
                let idx = resp_start + i as u16;
                if idx > end_idx {
                    break;
                }
                if let Some(value) = value_parser(data, i) {
                    values.insert(idx, value);
                }
            }

            current_idx = resp_start + num_values as u16;
            debug!(
                "Downloaded {} values, next index: {}",
                num_values, current_idx
            );

            // Report progress
            on_progress(values.len());

            // Check if we've downloaded all available data
            if (resp_start as usize + resp_count) >= end_idx as usize {
                debug!("Reached end of requested range");
                break;
            }
        }

        // Convert to ordered vector (BTreeMap already maintains order)
        Ok(values.into_values().collect())
    }

    /// Download a single parameter's history using V2 protocol (u16 values) with progress.
    async fn download_param_history_with_progress<F>(
        &self,
        param: HistoryParam,
        start_idx: u16,
        end_idx: u16,
        read_delay: Duration,
        on_progress: F,
    ) -> Result<Vec<u16>>
    where
        F: FnMut(usize),
    {
        let value_size = if param == HistoryParam::Humidity {
            1
        } else {
            2
        };

        self.download_param_history_generic_with_progress(
            param,
            start_idx,
            end_idx,
            read_delay,
            |data, i| {
                if param == HistoryParam::Humidity {
                    data.get(i).map(|&b| b as u16)
                } else {
                    let offset = i * 2;
                    if offset + 1 < data.len() {
                        Some(u16::from_le_bytes([data[offset], data[offset + 1]]))
                    } else {
                        None
                    }
                }
            },
            value_size,
            on_progress,
        )
        .await
    }

    /// Download a single parameter's history using V2 protocol (u32 values) with progress.
    async fn download_param_history_u32_with_progress<F>(
        &self,
        param: HistoryParam,
        start_idx: u16,
        end_idx: u16,
        read_delay: Duration,
        on_progress: F,
    ) -> Result<Vec<u32>>
    where
        F: FnMut(usize),
    {
        self.download_param_history_generic_with_progress(
            param,
            start_idx,
            end_idx,
            read_delay,
            |data, i| {
                let offset = i * 4;
                if offset + 3 < data.len() {
                    Some(u32::from_le_bytes([
                        data[offset],
                        data[offset + 1],
                        data[offset + 2],
                        data[offset + 3],
                    ]))
                } else {
                    None
                }
            },
            4,
            on_progress,
        )
        .await
    }

    /// Download history using V1 protocol (notification-based).
    ///
    /// This is used for older devices that don't support the V2 read-based protocol.
    /// V1 uses notifications on the HISTORY_V1 characteristic.
    pub async fn download_history_v1(&self) -> Result<Vec<HistoryRecord>> {
        use crate::uuid::HISTORY_V1;
        use tokio::sync::mpsc;

        let info = self.get_history_info().await?;
        info!(
            "V1 download: {} readings, interval {}s",
            info.total_readings, info.interval_seconds
        );

        if info.total_readings == 0 {
            return Ok(Vec::new());
        }

        // Subscribe to notifications
        let (tx, mut rx) = mpsc::channel::<Vec<u8>>(256);

        // Set up notification handler
        self.subscribe_to_notifications(HISTORY_V1, move |data| {
            if let Err(e) = tx.try_send(data.to_vec()) {
                warn!(
                    "V1 history notification channel full or closed, data may be lost: {}",
                    e
                );
            }
        })
        .await?;

        // Request history for each parameter
        let mut co2_values = Vec::new();
        let mut temp_values = Vec::new();
        let mut pressure_values = Vec::new();
        let mut humidity_values = Vec::new();

        for param in [
            HistoryParam::Co2,
            HistoryParam::Temperature,
            HistoryParam::Pressure,
            HistoryParam::Humidity,
        ] {
            // Send V1 history request using command constant
            let cmd = [
                HISTORY_V1_REQUEST,
                param as u8,
                0x01,
                0x00,
                (info.total_readings & 0xFF) as u8,
                ((info.total_readings >> 8) & 0xFF) as u8,
            ];

            self.write_characteristic(COMMAND, &cmd).await?;

            // Collect notifications until we have all values
            let mut values = Vec::new();
            let expected = info.total_readings as usize;

            let mut consecutive_timeouts = 0;
            const MAX_CONSECUTIVE_TIMEOUTS: u32 = 3;

            while values.len() < expected {
                match tokio::time::timeout(Duration::from_secs(5), rx.recv()).await {
                    Ok(Some(data)) => {
                        consecutive_timeouts = 0; // Reset on successful receive
                        // Parse notification data
                        if data.len() >= 3 {
                            let resp_param = data[0];
                            if resp_param == param as u8 {
                                let mut buf = &data[3..];
                                while buf.len() >= 2 && values.len() < expected {
                                    values.push(buf.get_u16_le());
                                }
                            }
                        }
                    }
                    Ok(None) => {
                        warn!(
                            "V1 history channel closed for {:?}: got {}/{} values",
                            param,
                            values.len(),
                            expected
                        );
                        break;
                    }
                    Err(_) => {
                        consecutive_timeouts += 1;
                        warn!(
                            "Timeout waiting for V1 history notification ({}/{}), {:?}: {}/{} values",
                            consecutive_timeouts,
                            MAX_CONSECUTIVE_TIMEOUTS,
                            param,
                            values.len(),
                            expected
                        );
                        if consecutive_timeouts >= MAX_CONSECUTIVE_TIMEOUTS {
                            warn!(
                                "Too many consecutive timeouts for {:?}, proceeding with partial data",
                                param
                            );
                            break;
                        }
                    }
                }
            }

            // Log if we got incomplete data
            if values.len() < expected {
                warn!(
                    "V1 history download incomplete for {:?}: got {}/{} values ({:.1}%)",
                    param,
                    values.len(),
                    expected,
                    (values.len() as f64 / expected as f64) * 100.0
                );
            }

            match param {
                HistoryParam::Co2 => co2_values = values,
                HistoryParam::Temperature => temp_values = values,
                HistoryParam::Pressure => pressure_values = values,
                HistoryParam::Humidity => humidity_values = values,
                // V1 protocol doesn't support radon or humidity2
                HistoryParam::Humidity2 | HistoryParam::Radon => {}
            }
        }

        // Unsubscribe from notifications
        self.unsubscribe_from_notifications(HISTORY_V1).await?;

        // Build history records
        let now = OffsetDateTime::now_utc();
        let latest_reading_time = now - time::Duration::seconds(info.seconds_since_update as i64);

        let mut records = Vec::new();
        let count = co2_values.len();

        // Warn if parameter arrays have mismatched lengths (partial download)
        if temp_values.len() != count
            || pressure_values.len() != count
            || humidity_values.len() != count
        {
            warn!(
                "V1 history arrays have mismatched lengths: co2={}, temp={}, pressure={}, humidity={} — \
                 records with missing values will use defaults",
                count,
                temp_values.len(),
                pressure_values.len(),
                humidity_values.len()
            );
        }

        for i in 0..count {
            let readings_ago = (count - 1 - i) as i64;
            let timestamp = latest_reading_time
                - time::Duration::seconds(readings_ago * info.interval_seconds as i64);

            let record = HistoryRecord {
                timestamp,
                co2: co2_values.get(i).copied().unwrap_or(0),
                temperature: raw_to_temperature(temp_values.get(i).copied().unwrap_or(0)),
                pressure: raw_to_pressure(pressure_values.get(i).copied().unwrap_or(0)),
                humidity: humidity_values.get(i).copied().unwrap_or(0) as u8,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            };
            records.push(record);
        }

        info!("V1 download complete: {} records", records.len());
        Ok(records)
    }
}

/// Build history records from downloaded parameter arrays.
///
/// For Aranet4: pass co2_values and empty radon_values.
/// For AranetRn+: pass empty co2_values and radon_values.
/// Humidity is converted differently based on whether radon_values is populated
/// (radon devices use Humidity2 encoding: tenths of a percent).
fn build_history_records(
    info: &HistoryInfo,
    co2_values: &[u16],
    temp_values: &[u16],
    pressure_values: &[u16],
    humidity_values: &[u16],
    radon_values: &[u32],
) -> Vec<HistoryRecord> {
    let is_radon = !radon_values.is_empty();
    let is_aranet2 = co2_values.is_empty() && radon_values.is_empty();
    let count = if is_radon {
        radon_values.len()
    } else if is_aranet2 {
        temp_values.len()
    } else {
        co2_values.len()
    };

    // Warn if parameter arrays have mismatched lengths (partial download)
    let expected = count;
    if temp_values.len() != expected
        || pressure_values.len() != expected
        || humidity_values.len() != expected
    {
        warn!(
            "History arrays have mismatched lengths: primary={expected}, temp={}, pressure={}, humidity={} — \
             records with missing values will use defaults",
            temp_values.len(),
            pressure_values.len(),
            humidity_values.len()
        );
    }

    let now = OffsetDateTime::now_utc();
    let latest_reading_time = now - time::Duration::seconds(info.seconds_since_update as i64);

    (0..count)
        .map(|i| {
            let readings_ago = (count - 1 - i) as i64;
            let timestamp = latest_reading_time
                - time::Duration::seconds(readings_ago * info.interval_seconds as i64);

            let humidity = if is_radon || is_aranet2 {
                // Humidity2 is stored as tenths of a percent
                let raw = humidity_values.get(i).copied().unwrap_or(0);
                (raw / 10).min(100) as u8
            } else {
                humidity_values.get(i).copied().unwrap_or(0) as u8
            };

            HistoryRecord {
                timestamp,
                co2: if is_radon {
                    0
                } else {
                    co2_values.get(i).copied().unwrap_or(0)
                },
                temperature: raw_to_temperature(temp_values.get(i).copied().unwrap_or(0)),
                pressure: raw_to_pressure(pressure_values.get(i).copied().unwrap_or(0)),
                humidity,
                radon: if is_radon {
                    Some(radon_values.get(i).copied().unwrap_or(0))
                } else {
                    None
                },
                radiation_rate: None,
                radiation_total: None,
            }
        })
        .collect()
}

/// Convert raw temperature value to Celsius.
pub fn raw_to_temperature(raw: u16) -> f32 {
    raw as f32 / 20.0
}

/// Convert raw pressure value to hPa.
pub fn raw_to_pressure(raw: u16) -> f32 {
    raw as f32 / 10.0
}

// NOTE: The HistoryValueConverter trait was removed as it was dead code.
// Use the standalone functions raw_to_temperature, raw_to_pressure, etc. directly.

#[cfg(test)]
mod tests {
    use super::*;

    // --- raw_to_temperature tests ---

    #[test]
    fn test_raw_to_temperature_typical_values() {
        // 22.5°C = 450 raw (450/20 = 22.5)
        assert!((raw_to_temperature(450) - 22.5).abs() < 0.001);

        // 20.0°C = 400 raw
        assert!((raw_to_temperature(400) - 20.0).abs() < 0.001);

        // 25.0°C = 500 raw
        assert!((raw_to_temperature(500) - 25.0).abs() < 0.001);
    }

    #[test]
    fn test_raw_to_temperature_edge_cases() {
        // 0°C = 0 raw
        assert!((raw_to_temperature(0) - 0.0).abs() < 0.001);

        // Very cold: -10°C would be negative, but raw is u16 so minimum is 0
        // Raw values represent actual temperature * 20

        // Very hot: 50°C = 1000 raw
        assert!((raw_to_temperature(1000) - 50.0).abs() < 0.001);

        // Maximum u16 would be 65535/20 = 3276.75°C (unrealistic but tests overflow handling)
        assert!((raw_to_temperature(u16::MAX) - 3276.75).abs() < 0.01);
    }

    #[test]
    fn test_raw_to_temperature_precision() {
        // Test fractional values
        // 22.55°C = 451 raw
        assert!((raw_to_temperature(451) - 22.55).abs() < 0.001);

        // 22.05°C = 441 raw
        assert!((raw_to_temperature(441) - 22.05).abs() < 0.001);
    }

    // --- raw_to_pressure tests ---

    #[test]
    fn test_raw_to_pressure_typical_values() {
        // 1013.2 hPa = 10132 raw
        assert!((raw_to_pressure(10132) - 1013.2).abs() < 0.01);

        // 1000.0 hPa = 10000 raw
        assert!((raw_to_pressure(10000) - 1000.0).abs() < 0.01);

        // 1050.0 hPa = 10500 raw
        assert!((raw_to_pressure(10500) - 1050.0).abs() < 0.01);
    }

    #[test]
    fn test_raw_to_pressure_edge_cases() {
        // 0 hPa = 0 raw
        assert!((raw_to_pressure(0) - 0.0).abs() < 0.01);

        // Low pressure: 950 hPa = 9500 raw
        assert!((raw_to_pressure(9500) - 950.0).abs() < 0.01);

        // High pressure: 1100 hPa = 11000 raw
        assert!((raw_to_pressure(11000) - 1100.0).abs() < 0.01);

        // Maximum u16 would be 65535/10 = 6553.5 hPa (unrealistic but tests bounds)
        assert!((raw_to_pressure(u16::MAX) - 6553.5).abs() < 0.1);
    }

    // --- HistoryParam tests ---

    #[test]
    fn test_history_param_values() {
        assert_eq!(HistoryParam::Temperature as u8, 1);
        assert_eq!(HistoryParam::Humidity as u8, 2);
        assert_eq!(HistoryParam::Pressure as u8, 3);
        assert_eq!(HistoryParam::Co2 as u8, 4);
    }

    #[test]
    fn test_history_param_debug() {
        assert_eq!(format!("{:?}", HistoryParam::Temperature), "Temperature");
        assert_eq!(format!("{:?}", HistoryParam::Co2), "Co2");
    }

    // --- HistoryOptions tests ---

    #[test]
    fn test_history_options_default() {
        let options = HistoryOptions::default();

        assert!(options.start_index.is_none());
        assert!(options.end_index.is_none());
        assert_eq!(options.read_delay, Duration::from_millis(50));
    }

    #[test]
    fn test_history_options_custom() {
        let options = HistoryOptions::new()
            .start_index(10)
            .end_index(100)
            .read_delay(Duration::from_millis(100));

        assert_eq!(options.start_index, Some(10));
        assert_eq!(options.end_index, Some(100));
        assert_eq!(options.read_delay, Duration::from_millis(100));
    }

    #[test]
    fn test_history_options_with_progress() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let call_count = Arc::new(AtomicUsize::new(0));
        let call_count_clone = Arc::clone(&call_count);

        let options = HistoryOptions::new().with_progress(move |_progress| {
            call_count_clone.fetch_add(1, Ordering::SeqCst);
        });

        assert!(options.progress_callback.is_some());

        // Test that the callback can be invoked
        let progress = HistoryProgress::new(HistoryParam::Co2, 1, 4, 100);
        options.report_progress(&progress);
        assert_eq!(call_count.load(Ordering::SeqCst), 1);
    }

    // --- HistoryInfo tests ---

    #[test]
    fn test_history_info_creation() {
        let info = HistoryInfo {
            total_readings: 1000,
            interval_seconds: 300,
            seconds_since_update: 120,
        };

        assert_eq!(info.total_readings, 1000);
        assert_eq!(info.interval_seconds, 300);
        assert_eq!(info.seconds_since_update, 120);
    }

    #[test]
    fn test_history_info_debug() {
        let info = HistoryInfo {
            total_readings: 500,
            interval_seconds: 60,
            seconds_since_update: 30,
        };

        let debug_str = format!("{:?}", info);
        assert!(debug_str.contains("total_readings"));
        assert!(debug_str.contains("500"));
    }
}