emc230x 0.8.0

An async driver for the EMC230x family of fan controllers
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
// Copyright (c) 2024 Jake Swensen
// SPDX-License-Identifier: MPL-2.0
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! The EMC230x device family is a fan controller with up to five independently
//! controlled PWM fan drivers.

#![no_std]

#[cfg(any(test, feature = "std"))]
extern crate std;

#[cfg(any(test, feature = "alloc"))]
extern crate alloc;

use core::fmt::{self, Debug, Formatter};
use embedded_hal_async as hal;
pub use fans::{FanControl, FanDutyCycle, FanRpm, FanSelect};
use hal::i2c::I2c;

use constants::EMC230X_ADDRESSES;
pub use constants::{
    EMC2301_I2C_ADDR, EMC230X_I2C_ADDR_0, EMC230X_I2C_ADDR_1, EMC230X_I2C_ADDR_2,
    EMC230X_I2C_ADDR_3, EMC230X_I2C_ADDR_4, EMC230X_I2C_ADDR_5,
};
pub use error::Error;
pub use probe_result::ProbeResult;
use registers::*;

mod constants;
mod error;
mod probe_result;
mod registers;
mod util;

/// Fetch a read-only register from the device
macro_rules! register_ro {
    ($get:ident, $return_type:ty) => {
        pub async fn $get(&mut self) -> Result<$return_type, Error> {
            self.read_register::<$return_type>(<$return_type>::ADDRESS)
                .await
        }
    };
}

/// Fetch and set a register from the device which applies to all fans
macro_rules! register {
    ($get:ident, $set:ident, $return_type:ty) => {
        pub async fn $get(&mut self) -> Result<$return_type, Error> {
            self.read_register::<$return_type>(<$return_type>::ADDRESS)
                .await
        }

        pub async fn $set(&mut self, value: $return_type) -> Result<(), Error> {
            self.write_register(<$return_type>::ADDRESS, value.into())
                .await?;
            Ok(())
        }
    };
}

/// Fetch and set a register from the device which applies to a specific fan
macro_rules! fan_register {
    ($get:ident, $set:ident, $reg_type:ty) => {
        pub async fn $get(&mut self, sel: FanSelect) -> Result<$reg_type, Error> {
            let sel = self.resolve_fan(sel)?;
            let reg = fan_register_address(sel, <$reg_type>::OFFSET)?;
            let value = self.read_register(reg).await?;
            Ok(value)
        }

        pub async fn $set(&mut self, sel: FanSelect, value: $reg_type) -> Result<(), Error> {
            let sel = self.resolve_fan(sel)?;
            let reg = fan_register_address(sel, <$reg_type>::OFFSET)?;
            self.write_register(reg, value.into()).await?;
            Ok(())
        }
    };
}

pub struct Emc230x<I2C> {
    /// I2C bus
    i2c: I2C,

    /// I2C address of the device
    address: u8,

    /// Device Product Identifier
    ///
    /// The product identification will determine the number of fans the device supports.
    pid: ProductId,

    /// Configurable number of poles in a fan. Typically 2.
    poles: [u8; 5],

    /// Enable or disable reverse fan indexing.
    ///
    /// When enabled, logical fan indices are mirrored around the device's fan count. For example,
    /// on an EMC2305 (5 fans), `FanSelect(1)` will map to hardware fan 5, `FanSelect(2)` to
    /// hardware fan 4, and so on. This is useful when the physical fan wiring order is the reverse
    /// of the hardware channel order.
    reverse_fan_index: bool,
}

impl<I2C> Debug for Emc230x<I2C> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Emc230x")
            .field("address", &self.address)
            .field("pid", &self.pid)
            .field("poles", &self.poles)
            .field("reverse_fan_index", &self.reverse_fan_index)
            .finish()
    }
}

impl<I2C: I2c> Emc230x<I2C> {
    /// Manufacturer ID
    const MANUFACTURER_ID: u8 = 0x5D;

    /// Tachometer measurement frequency (kHz)
    const TACH_FREQUENCY_HZ: f64 = 32_768.0;

    /// Determine if the device at the specified address is an EMC230x device
    async fn is_emc230x(i2c: &mut I2C, address: u8) -> Result<ProductId, Error> {
        let mfg_id: ManufacturerId = Self::raw_read(i2c, address, ManufacturerId::ADDRESS).await?;
        if mfg_id.mfg_id() == Self::MANUFACTURER_ID {
            let pid: ProductId = Self::raw_read(i2c, address, ProductId::ADDRESS).await?;
            Ok(pid)
        } else {
            Err(Error::InvalidManufacturerId)
        }
    }

    /// Probe the I2C bus for any EMC230x devices.
    ///
    /// Checks all six possible EMC230x I2C addresses (0x2C–0x2F, 0x4C–0x4D) and returns a
    /// [`ProbeResult`] containing each address where an EMC230x was identified.
    /// Issues up to 12 I2C transactions (2 per address).
    ///
    /// The I2C bus is borrowed so the caller can pass it to [`Emc230x::new`]
    /// using one of the returned addresses.
    ///
    /// # Example
    /// ```ignore
    /// let found = Emc230x::probe(&mut i2c).await;
    /// if let Some(addr) = found.iter().next() {
    ///     let dev = Emc230x::new(i2c, addr).await?;
    /// }
    /// ```
    pub async fn probe(i2c: &mut I2C) -> ProbeResult {
        let mut result = ProbeResult::default();
        for (slot, &address) in EMC230X_ADDRESSES.iter().enumerate() {
            if Self::is_emc230x(i2c, address).await.is_ok() {
                result.0[slot] = true;
            }
        }
        result
    }

    /// Initialize a new EMC230x device at the specified address
    pub async fn new(i2c: I2C, address: u8) -> Result<Self, Error> {
        let mut i2c = i2c;
        let pid = Self::is_emc230x(&mut i2c, address).await?;

        // Assume 2 poles for all fans by default. This is common for most fans and is a safe default.
        let poles = [2; 5];

        let reverse_fan_index = false;

        // Form the device so that some defaults can be set
        let mut dev = Self {
            i2c,
            address,
            pid,
            poles,
            reverse_fan_index,
        };

        // Set all fan outputs to push-pull to avoid waveform distortion
        let mut output_cfg = pwm_output_config::PwmOutputConfig::default();
        let count = dev.count();
        for fan in 1..=count {
            output_cfg.push_pull(fan);
        }
        dev.set_pwm_output_config(output_cfg).await?;

        // Set RPM range to 500 RPM for all drives to capture slower fans
        for fan in 1..=count {
            let mut cfg = dev.fan_configuration1(FanSelect(fan)).await?;
            cfg.set_rngx(fan_configuration1::Range::Rpm500);
            dev.set_fan_configuration1(FanSelect(fan), cfg).await?;
        }

        // Device is configured
        Ok(dev)
    }

    /// Get the I2C address of the device
    fn address(&self) -> u8 {
        self.address
    }

    /// Get the number of fans the device supports
    pub fn count(&self) -> u16 {
        self.pid.num_fans()
    }

    /// Returns `true` if reverse fan indexing is enabled.
    pub fn reverse_fan_index(&self) -> bool {
        self.reverse_fan_index
    }

    /// Enable or disable reverse fan indexing.
    ///
    /// When enabled, logical fan indices are mirrored around the device's fan count. For example,
    /// on an EMC2305 (5 fans), `FanSelect(1)` will map to hardware fan 5, `FanSelect(2)` to
    /// hardware fan 4, and so on. This is useful when the physical fan wiring order is the reverse
    /// of the hardware channel order.
    pub fn set_reverse_fan_index(&mut self, enabled: bool) {
        self.reverse_fan_index = enabled;
    }

    /// Get the number of poles for the selected fan (used in RPM calculations)
    pub fn fan_poles(&self, sel: FanSelect) -> Result<u8, Error> {
        let sel = self.resolve_fan(sel)?;
        Ok(self.poles[sel.0 as usize - 1])
    }

    /// Set the number of poles for the selected fan (used in RPM calculations)
    ///
    /// It is unlikely that this value will need to change unless a non-standard fan is used.
    /// If it does need to change, there are likely other configuration changes that need to
    /// happen as well.
    pub fn set_fan_poles(&mut self, sel: FanSelect, poles: u8) -> Result<(), Error> {
        let sel = self.resolve_fan(sel)?;
        self.poles[sel.0 as usize - 1] = poles;
        Ok(())
    }

    /// Get the tachometer frequency of the device
    fn tach_freq(&self) -> f64 {
        Self::TACH_FREQUENCY_HZ
    }

    /// Get the mode of the fan
    pub async fn mode(&mut self, sel: FanSelect) -> Result<FanControl, Error> {
        self.valid_fan(sel)?;
        let config = self.fan_configuration1(sel).await?;

        if config.enagx() {
            // RPM mode: read the tach target registers and convert to RPM
            let raw_low = self.tach_target_low_byte(sel).await?;
            let raw_high = self.tach_target_high_byte(sel).await?;

            let raw = u16::from_le_bytes([raw_low.into(), raw_high.into()]) >> 3;
            let rpm = self.calc_raw_rpm(sel, raw).await?;

            Ok(FanControl::Rpm(rpm))
        } else {
            // Duty cycle mode: read the fan drive setting
            let drive = self.fan_setting(sel).await?;
            Ok(FanControl::DutyCycle(drive.duty_cycle()))
        }
    }

    /// Set the mode of the fan
    pub async fn set_mode(&mut self, sel: FanSelect, mode: FanControl) -> Result<(), Error> {
        self.valid_fan(sel)?;
        let mut config = self.fan_configuration1(sel).await?;

        match mode {
            FanControl::DutyCycle(duty) => {
                // Disable RPM mode first if it is enabled.
                //
                // The device appears to set the fan drive with the duty cycle corresponding to the
                // last target RPM set. If the mode bit is set after the duty cycle, the desired
                // duty cycle gets overwritten.
                config.set_enagx(false);
                self.set_fan_configuration1(sel, config).await?;

                self.set_duty_cycle(sel, duty).await?;
            }
            FanControl::Rpm(rpm) => {
                self.set_rpm(sel, rpm).await?;

                config.set_enagx(true);
                self.set_fan_configuration1(sel, config).await?;
            }
        }

        Ok(())
    }

    /// Set the mode of all fans
    ///
    /// This is a convenience method that sets the mode of all fans on the device
    /// to the same setting. It is equivalent to calling [`set_mode`](Self::set_mode) for each fan.
    pub async fn set_mode_all(&mut self, mode: FanControl) -> Result<(), Error> {
        for fan in 1..=self.count() {
            self.set_mode(FanSelect(fan), mode).await?;
        }
        Ok(())
    }

    /// Fetch the current duty cycle of the fan
    pub async fn duty_cycle(&mut self, sel: FanSelect) -> Result<FanDutyCycle, Error> {
        self.valid_fan(sel)?;
        let drive = self.fan_setting(sel).await?;
        let duty = drive.duty_cycle();
        Ok(duty)
    }

    /// Set the duty cycle of the fan
    pub async fn set_duty_cycle(
        &mut self,
        sel: FanSelect,
        duty: FanDutyCycle,
    ) -> Result<(), Error> {
        self.valid_fan(sel)?;
        let drive = FanDriveSetting::from_duty_cycle(duty);
        self.set_fan_setting(sel, drive).await?;
        Ok(())
    }

    /// Fetch the current RPM of the fan
    pub async fn rpm(&mut self, sel: FanSelect) -> Result<FanRpm, Error> {
        self.valid_fan(sel)?;
        let raw_low = self.tach_reading_low_byte(sel).await?;
        let raw_high = self.tach_reading_high_byte(sel).await?;

        let raw = u16::from_le_bytes([raw_low.into(), raw_high.into()]) >> 3;
        let rpm = self.calc_raw_rpm(sel, raw).await?;

        Ok(rpm)
    }

    /// Set the target RPM of the fan
    pub async fn set_rpm(&mut self, sel: FanSelect, rpm: FanRpm) -> Result<(), Error> {
        self.valid_fan(sel)?;

        let raw = self.calc_raw_rpm(sel, rpm).await?;
        let count = (raw << 3).to_le_bytes();

        self.set_tach_target_low_byte(sel, count[0].into()).await?;
        self.set_tach_target_high_byte(sel, count[1].into()).await?;
        Ok(())
    }

    /// Fetch the current duty cycle and RPM of the fan
    pub async fn report(&mut self, sel: FanSelect) -> Result<(FanDutyCycle, FanRpm), Error> {
        self.valid_fan(sel)?;
        let duty = self.duty_cycle(sel).await?;
        let rpm = self.rpm(sel).await?;
        Ok((duty, rpm))
    }

    /// Minimum configured duty cycle the fan will run at.
    pub async fn min_duty(&mut self, sel: FanSelect) -> Result<FanDutyCycle, Error> {
        self.valid_fan(sel)?;
        let drive = self.minimum_drive(sel).await?;
        Ok(drive.duty_cycle())
    }

    /// Set the minimum duty cycle the fan will run at.
    pub async fn set_min_duty(&mut self, sel: FanSelect, duty: FanDutyCycle) -> Result<(), Error> {
        self.valid_fan(sel)?;
        let drive = FanMinimumDrive::from_duty_cycle(duty);
        self.set_minimum_drive(sel, drive).await?;
        Ok(())
    }

    /// Returns `true` if a spinning fan is detected on the selected channel.
    ///
    /// Reads the [`FanStallStatus`] register and checks the per-fan stall bit. A clear bit
    /// means the tachometer is receiving pulses - indicating a connected, spinning fan. A set
    /// bit means the tach count exceeded the [`ValidTachCount`] threshold, which occurs when
    /// no fan is connected **or** when a connected fan is not spinning.
    ///
    /// This is the closest the hardware can indicate fan presence; it cannot distinguish
    /// between an absent fan and a stalled one.
    pub async fn fan_detected(&mut self, sel: FanSelect) -> Result<bool, Error> {
        let sel = self.resolve_fan(sel)?;
        let status = self.stall_status().await?;
        let stalled = (u8::from(status) >> (sel.0 as u8 - 1)) & 1 != 0;
        Ok(!stalled)
    }

    /// Calculate either the RPM or raw value of the RPM based on the input value.
    async fn calc_raw_rpm(&mut self, sel: FanSelect, value: u16) -> Result<u16, Error> {
        let cfg = self.fan_configuration1(sel).await?;

        let poles = self.fan_poles(sel)? as f64;
        let n = cfg.edgx().num_edges() as f64;
        let m = cfg.rngx().tach_count_multiplier() as f64;
        let f_tach = self.tach_freq();

        let value = ((1.0 / poles) * (n - 1.0)) / (value as f64 * (1.0 / m)) * f_tach * 60.0;

        Ok(util::round_to_u16(value))
    }

    /// Write a value to a register on the device
    async fn write_register(&mut self, reg: u8, data: u8) -> Result<(), Error> {
        let addr = self.address();
        let data = [reg, data];
        self.i2c.write(addr, &data).await.map_err(|_| Error::I2c)
    }

    /// Read a value from a register on the device attached to the I2C bus
    async fn raw_read<T: TryFrom<u8>>(i2c: &mut I2C, address: u8, reg: u8) -> Result<T, Error> {
        let mut data = [0];
        i2c.write_read(address, &[reg], data.as_mut_slice())
            .await
            .map_err(|_| Error::I2c)?;

        let data: T = data[0]
            .try_into()
            .map_err(|_| Error::RegisterTypeConversion)?;

        Ok(data)
    }

    /// Read a value from a register on the device
    async fn read_register<T: TryFrom<u8>>(&mut self, reg: u8) -> Result<T, Error> {
        let addr = self.address();
        let data = Self::raw_read(&mut self.i2c, addr, reg).await?;
        Ok(data)
    }

    /// Determine if the fan number is valid by comparing it to the number of fans the device supports.
    fn valid_fan(&self, select: FanSelect) -> Result<(), Error> {
        if select.0 <= self.count() && select.0 != 0 {
            Ok(())
        } else {
            Err(Error::InvalidFan)
        }
    }

    /// Resolve and validate a user-facing [`FanSelect`] to a hardware fan index.
    ///
    /// When [`reverse_fan_index`](Self::reverse_fan_index) is enabled, mirror the fan selection.
    /// When reverse indexing is disabled, the fan select is returned unchanged.
    fn resolve_fan(&self, sel: FanSelect) -> Result<FanSelect, Error> {
        self.valid_fan(sel)?;
        if self.reverse_fan_index {
            Ok(FanSelect(self.count() - sel.0 + 1))
        } else {
            Ok(sel)
        }
    }

    /// Release the I2C bus from the device
    pub fn release(self) -> I2C {
        self.i2c
    }

    // General register access
    register!(config, set_config, Configuration);
    register_ro!(status, FanStatus);
    register_ro!(stall_status, FanStallStatus);
    register_ro!(spin_status, FanSpinStatus);
    register_ro!(drive_fail_status, FanDriveFailStatus);
    register!(interrupt_enable, set_interrupt_enable, FanInterruptEnable);
    register!(pwm_polarity_config, set_pwm_polarity_config, PwmPolarityConfig);
    register!(pwm_output_config, set_pwm_output_config, PwmOutputConfig);
    register!(pwm_base_f45, set_pwm_base_f45, PwmBase45);
    register!(pwm_base_f123, set_pwm_base_f123, PwmBase123);

    // Fan specific register access
    fan_register!(fan_setting, set_fan_setting, FanDriveSetting);
    fan_register!(pwm_divide, set_pwm_divide, PwmDivide);
    fan_register!(fan_configuration1, set_fan_configuration1, FanConfiguration1);
    fan_register!(fan_configuration2, set_fan_configuration2, FanConfiguration2);
    fan_register!(gain, set_gain, PidGain);
    fan_register!(spin_up_configuration, set_spin_up_configuration, FanSpinUpConfig);
    fan_register!(max_step, set_max_step, MaxStepSize);
    fan_register!(minimum_drive, set_minimum_drive, FanMinimumDrive);
    fan_register!(valid_tach_count, set_valid_tach_count, ValidTachCount);
    fan_register!(drive_fail_band_low_byte, set_drive_fail_band_low_byte, DriveFailBandLow);
    fan_register!(drive_fail_band_high_byte, set_drive_fail_band_high_byte, DriveFailBandHigh);
    fan_register!(tach_target_low_byte, set_tach_target_low_byte, TachTargetLow);
    fan_register!(tach_target_high_byte, set_tach_target_high_byte, TachTargetHigh);
    fan_register!(tach_reading_high_byte, set_tach_reading_high_byte, TachReadingHigh);
    fan_register!(tach_reading_low_byte, set_tach_reading_low_byte, TachReadingLow);

    // Chip registers
    register_ro!(software_lock, SoftwareLock);
    register_ro!(product_features, ProductFeatures);
    register_ro!(product_id, ProductId);

    /// Dump all the info and registers from the EMC230x Device
    #[cfg(feature = "defmt")]
    pub async fn dump_info(&mut self) -> Result<(), Error> {
        macro_rules! defmt_info_register {
            ($dev:expr, $reg:tt) => {
                let value = $dev.$reg().await?;
                defmt::info!("{}: {:#04x}", stringify!($reg), u8::from(value));
            };
        }

        macro_rules! defmt_info_fan_register {
            ($dev:expr, $reg:tt, $fan:expr) => {
                let value = $dev.$reg(FanSelect($fan)).await?;
                defmt::info!("{}: {:#04x}", stringify!($reg), u8::from(value));
            };
        }

        let count = self.count();

        defmt::info!("Address: {:#04x}", self.address());
        defmt::info!("Fan Count: {}", count);

        defmt_info_register!(self, software_lock);
        defmt_info_register!(self, product_features);
        defmt_info_register!(self, product_id);

        defmt_info_register!(self, config);
        defmt_info_register!(self, status);
        defmt_info_register!(self, stall_status);
        defmt_info_register!(self, spin_status);
        defmt_info_register!(self, drive_fail_status);
        defmt_info_register!(self, interrupt_enable);
        defmt_info_register!(self, pwm_polarity_config);
        defmt_info_register!(self, pwm_output_config);
        defmt_info_register!(self, pwm_base_f45);
        defmt_info_register!(self, pwm_base_f123);

        for fan in 1..=count {
            defmt::info!("Fan: {} ----------------------", fan);
            defmt_info_fan_register!(self, fan_setting, fan);
            defmt_info_fan_register!(self, pwm_divide, fan);
            defmt_info_fan_register!(self, fan_configuration1, fan);
            defmt_info_fan_register!(self, fan_configuration2, fan);
            defmt_info_fan_register!(self, gain, fan);
            defmt_info_fan_register!(self, spin_up_configuration, fan);
            defmt_info_fan_register!(self, max_step, fan);
            defmt_info_fan_register!(self, minimum_drive, fan);
            defmt_info_fan_register!(self, valid_tach_count, fan);
            defmt_info_fan_register!(self, drive_fail_band_low_byte, fan);
            defmt_info_fan_register!(self, drive_fail_band_high_byte, fan);
            defmt_info_fan_register!(self, tach_target_low_byte, fan);
            defmt_info_fan_register!(self, tach_target_high_byte, fan);
            defmt_info_fan_register!(self, tach_reading_high_byte, fan);
            defmt_info_fan_register!(self, tach_reading_low_byte, fan);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use embedded_hal_mock::eh1::i2c::{Mock as I2cMock, Transaction as I2cTransaction};
    use std::{vec, vec::Vec};

    use crate::constants::_SIMPLIFIED_RPM_FACTOR;
    use crate::registers::tach_reading::TachReading;

    /// Transaction expectation builder for a [`Emc230x`] device.
    #[derive(Clone, Debug)]
    struct Emc230xExpectationBuilder {
        address: u8,
        _product_id: ProductId,
        transactions: Vec<I2cTransaction>,
    }

    impl Emc230xExpectationBuilder {
        /// Create expectations for a mock [`Emc230x`] device that has not been initialized.
        fn new(address: u8, pid: ProductId) -> Self {
            let mut transactions = vec![
                I2cTransaction::write_read(address, vec![ManufacturerId::ADDRESS], vec![0x5D]),
                I2cTransaction::write_read(address, vec![ProductId::ADDRESS], vec![pid.into()]),
            ];

            // Set the output configuration to push-pull for all fans
            let mut output_cfg = 0x00_u8;
            for fan in 1..=pid.num_fans() {
                output_cfg |= 1 << (fan - 1);
            }
            transactions
                .push(I2cTransaction::write(address, vec![PwmOutputConfig::ADDRESS, output_cfg]));

            for fan in 1..=pid.num_fans() {
                transactions.push(I2cTransaction::write_read(
                    address,
                    vec![FanConfiguration1::fan_address(FanSelect(fan))
                        .expect("Could not set fan address")],
                    vec![FanConfiguration1::default().into()],
                ));

                transactions.push(I2cTransaction::write(
                    address,
                    vec![
                        FanConfiguration1::fan_address(FanSelect(fan))
                            .expect("Could not set fan address"),
                        0x0B,
                    ],
                ));
            }

            Self {
                address,
                _product_id: pid,
                transactions,
            }
        }

        /// Set expectations to retrieve the duty cycle of a fan.
        fn duty_cycle(&mut self, select: FanSelect, duty_cycle: u8) {
            let raw = FanDriveSetting::from_duty_cycle(duty_cycle);

            self.transactions.push(I2cTransaction::write_read(
                self.address,
                vec![FanDriveSetting::fan_address(select).expect("Could not set fan address")],
                vec![raw.into()],
            ));
        }

        /// Set expectations to retrieve the RPM of a fan.
        fn rpm(&mut self, select: FanSelect, rpm: u16) {
            let mut default_cfg = FanConfiguration1::default();
            default_cfg.set_rngx(fan_configuration1::Range::Rpm500);

            let raw = (_SIMPLIFIED_RPM_FACTOR * default_cfg.rngx().tach_count_multiplier() as f64
                / rpm as f64) as u16;
            let count: TachReading = TachReading::from(raw);

            self.transactions.push(I2cTransaction::write_read(
                self.address,
                vec![TachReadingLow::fan_address(select).expect("Could not set fan address")],
                vec![count.raw_low()],
            ));

            self.transactions.push(I2cTransaction::write_read(
                self.address,
                vec![TachReadingHigh::fan_address(select).expect("Could not set fan address")],
                vec![count.raw_high()],
            ));

            self.transactions.push(I2cTransaction::write_read(
                self.address,
                vec![FanConfiguration1::fan_address(select).expect("Could not set fan address")],
                vec![default_cfg.into()],
            ));
        }

        fn build(self) -> Vec<I2cTransaction> {
            self.transactions
        }
    }

    #[tokio::test]
    async fn probe_no_devices() {
        use embedded_hal::i2c::{ErrorKind, NoAcknowledgeSource};

        let expectations: Vec<I2cTransaction> = EMC230X_ADDRESSES
            .iter()
            .map(|&addr| {
                I2cTransaction::write_read(addr, vec![ManufacturerId::ADDRESS], vec![0])
                    .with_error(ErrorKind::NoAcknowledge(NoAcknowledgeSource::Address))
            })
            .collect();

        let mut i2c = I2cMock::new(&expectations);
        let result = Emc230x::probe(&mut i2c).await;
        assert!(result.is_empty());
        i2c.done();
    }

    #[tokio::test]
    async fn probe_one_device() {
        use embedded_hal::i2c::{ErrorKind, NoAcknowledgeSource};

        let mut expectations: Vec<I2cTransaction> = Vec::new();
        for &addr in EMC230X_ADDRESSES.iter() {
            if addr == EMC230X_I2C_ADDR_3 {
                expectations.push(I2cTransaction::write_read(
                    addr,
                    vec![ManufacturerId::ADDRESS],
                    vec![0x5D],
                ));
                expectations.push(I2cTransaction::write_read(
                    addr,
                    vec![ProductId::ADDRESS],
                    vec![ProductId::Emc2301.into()],
                ));
            } else {
                expectations.push(
                    I2cTransaction::write_read(addr, vec![ManufacturerId::ADDRESS], vec![0])
                        .with_error(ErrorKind::NoAcknowledge(NoAcknowledgeSource::Address)),
                );
            }
        }

        let mut i2c = I2cMock::new(&expectations);
        let result = Emc230x::probe(&mut i2c).await;
        assert_eq!(result.len(), 1);
        let addrs: Vec<u8> = result.iter().collect();
        assert_eq!(addrs, vec![EMC230X_I2C_ADDR_3]);
        i2c.done();
    }

    #[tokio::test]
    async fn probe_wrong_manufacturer_id() {
        use embedded_hal::i2c::{ErrorKind, NoAcknowledgeSource};

        let mut expectations: Vec<I2cTransaction> = Vec::new();
        for &addr in EMC230X_ADDRESSES.iter() {
            if addr == EMC230X_I2C_ADDR_0 {
                // Responds but returns wrong manufacturer ID
                expectations.push(I2cTransaction::write_read(
                    addr,
                    vec![ManufacturerId::ADDRESS],
                    vec![0x00],
                ));
            } else {
                expectations.push(
                    I2cTransaction::write_read(addr, vec![ManufacturerId::ADDRESS], vec![0])
                        .with_error(ErrorKind::NoAcknowledge(NoAcknowledgeSource::Address)),
                );
            }
        }

        let mut i2c = I2cMock::new(&expectations);
        let result = Emc230x::probe(&mut i2c).await;
        assert!(result.is_empty());
        i2c.done();
    }

    #[tokio::test]
    async fn probe_multiple_devices() {
        use embedded_hal::i2c::{ErrorKind, NoAcknowledgeSource};

        let mut expectations: Vec<I2cTransaction> = Vec::new();
        for &addr in EMC230X_ADDRESSES.iter() {
            if addr == EMC230X_I2C_ADDR_0 {
                expectations.push(I2cTransaction::write_read(
                    addr,
                    vec![ManufacturerId::ADDRESS],
                    vec![0x5D],
                ));
                expectations.push(I2cTransaction::write_read(
                    addr,
                    vec![ProductId::ADDRESS],
                    vec![ProductId::Emc2305.into()],
                ));
            } else if addr == EMC230X_I2C_ADDR_5 {
                expectations.push(I2cTransaction::write_read(
                    addr,
                    vec![ManufacturerId::ADDRESS],
                    vec![0x5D],
                ));
                expectations.push(I2cTransaction::write_read(
                    addr,
                    vec![ProductId::ADDRESS],
                    vec![ProductId::Emc2303.into()],
                ));
            } else {
                expectations.push(
                    I2cTransaction::write_read(addr, vec![ManufacturerId::ADDRESS], vec![0])
                        .with_error(ErrorKind::NoAcknowledge(NoAcknowledgeSource::Address)),
                );
            }
        }

        let mut i2c = I2cMock::new(&expectations);
        let result = Emc230x::probe(&mut i2c).await;
        assert_eq!(result.len(), 2);
        let addrs: Vec<u8> = result.iter().collect();
        assert_eq!(addrs, vec![EMC230X_I2C_ADDR_0, EMC230X_I2C_ADDR_5]);
        i2c.done();
    }

    #[tokio::test]
    async fn new() {
        let expectations =
            Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301).build();

        let i2c = I2cMock::new(&expectations);
        let dev = crate::Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn get_duty_cycle() {
        let expected_duty_cycle = [100, 75, 50, 25, 0];

        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);

        for value in expected_duty_cycle {
            expectations.duty_cycle(FanSelect(1), value);
        }

        let expectations = expectations.build();

        let i2c = I2cMock::new(&expectations);
        let mut dev = crate::Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        for expected in expected_duty_cycle {
            let result = dev
                .duty_cycle(FanSelect(1))
                .await
                .expect("Could not get duty cycle");
            assert_eq!(expected, result);
        }

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn get_rpm() {
        let expected_rpm: [u16; 15_500] = core::array::from_fn(|i| (i + 500) as u16);
        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);

        for value in expected_rpm {
            expectations.rpm(FanSelect(1), value);
        }

        let expectations = expectations.build();

        let i2c = I2cMock::new(&expectations);
        let mut dev = crate::Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        for expected in expected_rpm {
            let result = dev.rpm(FanSelect(1)).await.expect("Could not get RPM");

            // Allow a ±1% margin of error due to count step size varying over different settings
            let range = std::ops::Range {
                start: expected as f64 * 0.99,
                end: expected as f64 * 1.01,
            };
            assert!(
                range.contains(&(result as f64)),
                "RPM was out of expected range; Expected: {} in Range: {:?} Got: {}",
                expected,
                range,
                result
            );
        }

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn emc2305_duty_cycle_fan5() {
        let mut expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_0, ProductId::Emc2305);
        expectations.duty_cycle(FanSelect(5), 75);
        let expectations = expectations.build();

        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_0)
            .await
            .expect("Could not create device");

        let result = dev
            .duty_cycle(FanSelect(5))
            .await
            .expect("Could not get duty cycle for fan 5");
        assert_eq!(75, result);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn emc2305_rpm_fan5() {
        let expected_rpm: u16 = 1000;
        let mut expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_0, ProductId::Emc2305);
        expectations.rpm(FanSelect(5), expected_rpm);
        let expectations = expectations.build();

        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_0)
            .await
            .expect("Could not create device");

        let result = dev
            .rpm(FanSelect(5))
            .await
            .expect("Could not get RPM for fan 5");

        let range = std::ops::Range {
            start: expected_rpm as f64 * 0.99,
            end: expected_rpm as f64 * 1.01,
        };
        assert!(
            range.contains(&(result as f64)),
            "RPM was out of expected range; Expected: {} in Range: {:?} Got: {}",
            expected_rpm,
            range,
            result
        );

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn fan_detected_spinning() {
        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);
        // stall status = 0x00 -> fan 1 not stalled
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanStallStatus::ADDRESS],
            vec![0x00],
        ));
        let expectations = expectations.build();

        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        let result = dev
            .fan_detected(FanSelect(1))
            .await
            .expect("fan_detected failed");
        assert!(result);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn fan_detected_stalled() {
        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);
        // stall status = 0x01 -> bit 0 set -> fan 1 stalled
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanStallStatus::ADDRESS],
            vec![0x01],
        ));
        let expectations = expectations.build();

        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        let result = dev
            .fan_detected(FanSelect(1))
            .await
            .expect("fan_detected failed");
        assert!(!result);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn fan_detected_emc2305_fan5_stalled() {
        let mut expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_0, ProductId::Emc2305);
        // stall status = 0x10 -> bit 4 set -> fan 5 stalled
        expectations.transactions.push(I2cTransaction::write_read(
            EMC230X_I2C_ADDR_0,
            vec![FanStallStatus::ADDRESS],
            vec![0x10],
        ));
        let expectations = expectations.build();

        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_0)
            .await
            .expect("Could not create device");

        let result = dev
            .fan_detected(FanSelect(5))
            .await
            .expect("fan_detected failed");
        assert!(!result);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn valid_fan() {
        let expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);
        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let dev = Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        let result = dev.valid_fan(FanSelect(1));
        assert!(result.is_ok());

        let result = dev.valid_fan(FanSelect(0));
        assert!(result.is_err());

        let result = dev.valid_fan(FanSelect(6));
        assert!(result.is_err());

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn get_rpm_zero_tach_saturates_to_u16_max() {
        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);

        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![TachReadingLow::fan_address(FanSelect(1)).expect("fan address")],
            vec![0x00],
        ));
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![TachReadingHigh::fan_address(FanSelect(1)).expect("fan address")],
            vec![0x00],
        ));

        let mut cfg = FanConfiguration1::default();
        cfg.set_rngx(fan_configuration1::Range::Rpm500);
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanConfiguration1::fan_address(FanSelect(1)).expect("fan address")],
            vec![cfg.into()],
        ));

        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        let result = dev.rpm(FanSelect(1)).await.expect("Could not get RPM");
        assert_eq!(result, u16::MAX);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn set_rpm_zero_saturates_to_u16_max() {
        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);

        let mut cfg = FanConfiguration1::default();
        cfg.set_rngx(fan_configuration1::Range::Rpm500);
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanConfiguration1::fan_address(FanSelect(1)).expect("fan address")],
            vec![cfg.into()],
        ));

        let count = TachReading::from(u16::MAX);
        expectations.transactions.push(I2cTransaction::write(
            EMC2301_I2C_ADDR,
            vec![
                TachTargetLow::fan_address(FanSelect(1)).expect("fan address"),
                count.raw_low(),
            ],
        ));
        expectations.transactions.push(I2cTransaction::write(
            EMC2301_I2C_ADDR,
            vec![
                TachTargetHigh::fan_address(FanSelect(1)).expect("fan address"),
                count.raw_high(),
            ],
        ));

        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        dev.set_rpm(FanSelect(1), 0)
            .await
            .expect("Could not set RPM");

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn mode_duty_cycle() {
        let duty = 75_u8;
        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);

        let mut cfg = FanConfiguration1::default();
        cfg.set_rngx(fan_configuration1::Range::Rpm500);
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanConfiguration1::fan_address(FanSelect(1)).expect("fan address")],
            vec![cfg.into()],
        ));

        let raw = FanDriveSetting::from_duty_cycle(duty);
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanDriveSetting::fan_address(FanSelect(1)).expect("fan address")],
            vec![raw.into()],
        ));

        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        let result = dev.mode(FanSelect(1)).await.expect("Could not get mode");
        assert_eq!(result, FanControl::DutyCycle(duty));

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn mode_rpm() {
        let target_rpm: u16 = 1000;
        let mut expectations = Emc230xExpectationBuilder::new(EMC2301_I2C_ADDR, ProductId::Emc2301);

        let mut cfg = FanConfiguration1::default();
        cfg.set_rngx(fan_configuration1::Range::Rpm500);
        cfg.set_enagx(true);
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanConfiguration1::fan_address(FanSelect(1)).expect("fan address")],
            vec![cfg.into()],
        ));

        let raw_count = (_SIMPLIFIED_RPM_FACTOR * cfg.rngx().tach_count_multiplier() as f64
            / target_rpm as f64) as u16;
        let count = TachReading::from(raw_count);

        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![TachTargetLow::fan_address(FanSelect(1)).expect("fan address")],
            vec![count.raw_low()],
        ));
        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![TachTargetHigh::fan_address(FanSelect(1)).expect("fan address")],
            vec![count.raw_high()],
        ));

        expectations.transactions.push(I2cTransaction::write_read(
            EMC2301_I2C_ADDR,
            vec![FanConfiguration1::fan_address(FanSelect(1)).expect("fan address")],
            vec![cfg.into()],
        ));

        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC2301_I2C_ADDR)
            .await
            .expect("Could not create device");

        let result = dev.mode(FanSelect(1)).await.expect("Could not get mode");

        match result {
            FanControl::Rpm(rpm) => {
                let range = std::ops::Range {
                    start: target_rpm as f64 * 0.99,
                    end: target_rpm as f64 * 1.01,
                };
                assert!(
                    range.contains(&(rpm as f64)),
                    "RPM was out of expected range; Expected: {} in Range: {:?} Got: {}",
                    target_rpm,
                    range,
                    rpm
                );
            }
            other => panic!("Expected FanControl::Rpm, got {:?}", other),
        }

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn resolve_fan_no_reverse() {
        let expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_5, ProductId::Emc2305).build();
        let i2c = I2cMock::new(&expectations);
        let dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_5)
            .await
            .expect("Could not create device");

        // Without reverse, fan indices should pass through unchanged
        for fan in 1..=5_u16 {
            let resolved = dev.resolve_fan(FanSelect(fan)).expect("resolve_fan failed");
            assert_eq!(resolved.0, fan);
        }

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn resolve_fan_reversed_emc2305() {
        let expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_5, ProductId::Emc2305).build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_5)
            .await
            .expect("Could not create device");

        dev.set_reverse_fan_index(true);
        assert!(dev.reverse_fan_index());

        // On EMC2305 (5 fans): 1->5, 2->4, 3->3, 4->2, 5->1
        assert_eq!(dev.resolve_fan(FanSelect(1)).unwrap().0, 5);
        assert_eq!(dev.resolve_fan(FanSelect(2)).unwrap().0, 4);
        assert_eq!(dev.resolve_fan(FanSelect(3)).unwrap().0, 3);
        assert_eq!(dev.resolve_fan(FanSelect(4)).unwrap().0, 2);
        assert_eq!(dev.resolve_fan(FanSelect(5)).unwrap().0, 1);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn resolve_fan_reversed_emc2302() {
        let expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_1, ProductId::Emc2302).build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_1)
            .await
            .expect("Could not create device");

        dev.set_reverse_fan_index(true);

        // On EMC2302 (2 fans): 1->2, 2->1
        assert_eq!(dev.resolve_fan(FanSelect(1)).unwrap().0, 2);
        assert_eq!(dev.resolve_fan(FanSelect(2)).unwrap().0, 1);

        // Fan 3 should be invalid on a 2-fan device
        assert!(dev.resolve_fan(FanSelect(3)).is_err());

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn reversed_duty_cycle_emc2305() {
        // With reverse enabled, reading duty_cycle(FanSelect(1)) should hit hardware fan 5
        // (register at FAN5_BASE + offset = 0x70)
        let mut expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_4, ProductId::Emc2305);

        // The mock expects I2C reads at the *hardware* fan 5 address
        expectations.duty_cycle(FanSelect(5), 80);

        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_4)
            .await
            .expect("Could not create device");

        dev.set_reverse_fan_index(true);

        // User asks for fan 1, but it resolves to hardware fan 5
        let result = dev
            .duty_cycle(FanSelect(1))
            .await
            .expect("Could not get duty cycle");
        assert_eq!(80, result);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn reversed_fan_detected_emc2305() {
        // With reverse enabled, fan_detected(FanSelect(1)) on EMC2305 should check
        // hardware fan 5 (bit 4 of stall status register)
        let mut expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_4, ProductId::Emc2305);

        // Stall status = 0x10 -> bit 4 set -> hardware fan 5 stalled
        expectations.transactions.push(I2cTransaction::write_read(
            EMC230X_I2C_ADDR_4,
            vec![FanStallStatus::ADDRESS],
            vec![0x10],
        ));

        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_4)
            .await
            .expect("Could not create device");

        dev.set_reverse_fan_index(true);

        // User asks about fan 1 -> resolves to hardware fan 5 -> bit 4 is set -> stalled
        let result = dev
            .fan_detected(FanSelect(1))
            .await
            .expect("fan_detected failed");
        assert!(!result);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn reversed_fan_poles_emc2305() {
        let expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_4, ProductId::Emc2305).build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_4)
            .await
            .expect("Could not create device");

        dev.set_reverse_fan_index(true);

        // Set poles for logical fan 1 (resolves to hardware fan 5)
        dev.set_fan_poles(FanSelect(1), 4)
            .expect("set_fan_poles failed");

        // Reading logical fan 1 should return what we set
        assert_eq!(dev.fan_poles(FanSelect(1)).unwrap(), 4);

        // Logical fan 5 (resolves to hardware fan 1) should still have the default
        assert_eq!(dev.fan_poles(FanSelect(5)).unwrap(), 2);

        // Disable reverse and verify the value is at the correct hardware position
        dev.set_reverse_fan_index(false);

        // Hardware fan 5 should have poles=4 (what we set via logical fan 1)
        assert_eq!(dev.fan_poles(FanSelect(5)).unwrap(), 4);
        // Hardware fan 1 should have the default poles=2
        assert_eq!(dev.fan_poles(FanSelect(1)).unwrap(), 2);

        let mut i2c = dev.release();
        i2c.done();
    }

    #[tokio::test]
    async fn set_mode_all_duty_cycle() {
        let duty = 50_u8;
        let mut expectations =
            Emc230xExpectationBuilder::new(EMC230X_I2C_ADDR_4, ProductId::Emc2305);

        // After init, each fan has FanConfiguration1 = 0x0B (default 0x2B with rngx set to Rpm500).
        // For each fan, set_mode(DutyCycle) performs:
        //   1. Read FanConfiguration1 (returns 0x0B)
        //   2. Write FanConfiguration1 with enagx cleared (still 0x0B since bit 7 is already 0)
        //   3. Write FanDriveSetting with the duty cycle value
        let mut cfg = FanConfiguration1::default();
        cfg.set_rngx(fan_configuration1::Range::Rpm500);
        let raw_duty: u8 = FanDriveSetting::from_duty_cycle(duty).into();

        for fan in 1..=5_u16 {
            // Read FanConfiguration1
            expectations.transactions.push(I2cTransaction::write_read(
                EMC230X_I2C_ADDR_4,
                vec![FanConfiguration1::fan_address(FanSelect(fan)).expect("fan address")],
                vec![cfg.into()],
            ));

            // Write FanConfiguration1 (enagx cleared)
            expectations.transactions.push(I2cTransaction::write(
                EMC230X_I2C_ADDR_4,
                vec![
                    FanConfiguration1::fan_address(FanSelect(fan)).expect("fan address"),
                    cfg.into(),
                ],
            ));

            // Write FanDriveSetting
            expectations.transactions.push(I2cTransaction::write(
                EMC230X_I2C_ADDR_4,
                vec![
                    FanDriveSetting::fan_address(FanSelect(fan)).expect("fan address"),
                    raw_duty,
                ],
            ));
        }

        // Read back mode for each fan to verify
        for fan in 1..=5_u16 {
            // mode() reads FanConfiguration1 (enagx is false -> duty cycle mode)
            expectations.transactions.push(I2cTransaction::write_read(
                EMC230X_I2C_ADDR_4,
                vec![FanConfiguration1::fan_address(FanSelect(fan)).expect("fan address")],
                vec![cfg.into()],
            ));

            // mode() reads FanDriveSetting
            expectations.transactions.push(I2cTransaction::write_read(
                EMC230X_I2C_ADDR_4,
                vec![FanDriveSetting::fan_address(FanSelect(fan)).expect("fan address")],
                vec![raw_duty],
            ));
        }

        let expectations = expectations.build();
        let i2c = I2cMock::new(&expectations);
        let mut dev = Emc230x::new(i2c, EMC230X_I2C_ADDR_4)
            .await
            .expect("Could not create device");

        dev.set_mode_all(FanControl::DutyCycle(duty))
            .await
            .expect("set_mode_all failed");

        // Verify all fans are in the expected mode
        for fan in 1..=5_u16 {
            let result = dev.mode(FanSelect(fan)).await.expect("Could not get mode");
            assert_eq!(result, FanControl::DutyCycle(duty));
        }

        let mut i2c = dev.release();
        i2c.done();
    }
}