antaeus 0.3.8

A Versatile Framework for Vexide
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
//! # MotorGroup
//!
//! Missing `MotorGroup` from VEXCode or PROS? This is a lightweight
//! `MotorGroup` implementation bundled with Antaeus (adapted from the
//! original `vexide-motorgroup` crate). No extra dependency is required.
//!
//! ## Usage
//!
//! Normally, you would have to set each motor's target and other values
//! individually even if the motors were physically connected in a drivetrain or
//! similar, but with `MotorGroup`, you can control them as if they were one motor.
//!
//! Just create a `MotorGroup` with a `Vec` of `Motor`s and use the `MotorGroup`
//! methods just like you would with a `Motor`. It's that simple!
//!
//! ```rust,ignore
//! use std::time::Duration;
//!
//! use alloc::vec;
//! use antaeus::peripherals::motorgroup::*;
//!
//! use vexide::prelude::*;
//!
//! #[vexide::main]
//! async fn main(peripherals: Peripherals) {
//!     // Here's where the magic happens
//!     let mut motor_group = MotorGroup::new(vec![
//!         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
//!         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
//!     ]);
//!
//!     // Set the motor group's target to a voltage as if it were a motor
//!     motor_group.set_voltage(5.0).unwrap();
//!     sleep(Duration::from_secs(1)).await;
//!
//!     // Set the motor group's target to a position
//!     motor_group
//!         .set_position_target(Angle::from_degrees(90.0), 200)
//!         .unwrap();
//!     sleep(Duration::from_secs(1)).await;
//!
//!     // Set the motor group's target to a velocity
//!     motor_group.set_velocity(100).unwrap();
//!     sleep(Duration::from_secs(1)).await;
//!
//!     // Brake the motor group
//!     motor_group.brake(BrakeMode::Hold).unwrap();
//! }
//! ```
//!
//! ## Error handling
//!
//! ### Read errors
//!
//! For functions returning values and reading data (i.e., those taking a
//! read-only reference to self), upon encountering an error accessing any
//! motor, the result will be a MotorGroupError that contains all the errors
//! encountered during the operation. Using [`MotorGroupError::result`] will
//! return the average of all the results that were successfully read.
//!
//! ### Write errors
//!
//! This module provides two different strategies for handling write
//! errors. Both of them will return an `Err` when any motor returns an error.
//!
//! 1. [`WriteErrorStrategy::Ignore`] (default): This strategy will ignore
//!    errors and continue writing to the other motors.
//! 2. [`WriteErrorStrategy::Stop`]: This strategy will stop writing to the
//!    other motors and return the error immediately.

extern crate alloc;
use alloc::vec::Vec;

use vexide::{
    math::Angle,
    prelude::{Direction, Gearset},
    smart::{
        PortError,
        motor::{BrakeMode, Motor, MotorControl, SetGearsetError},
    },
};

/// An error that occurs when controlling a motor group.
///
/// This error is returned when an individual motor in the group encounters an
/// error. The error contains a list of all the errors that occurred.
///
/// A MotorGroupError is guaranteed to have at least one error in it.
///
/// `MotorGroupError` implements conversions to [`PortError`] and
/// [`SetGearsetError`], returning the first error encountered. This means
/// you can use the `?` operator to bubble the first error when your
/// function returns one of those error types.
#[derive(Debug)]
#[non_exhaustive]
pub struct MotorGroupError<E = PortError, T = ()> {
    pub errors: Vec<E>,
    pub result: Option<T>,
}

impl<E> MotorGroupError<E, ()> {
    /// Creates a new motor group error from a `Vec` of motor errors.
    ///
    /// # Panics
    ///
    /// Panics if the errors vector is empty.
    pub(crate) fn new(errors: Vec<E>) -> Self {
        assert!(!errors.is_empty(), "Cannot create a MotorGroupError with no errors");
        Self {
            errors,
            result: None,
        }
    }
}

impl<E, T> MotorGroupError<E, T> {
    pub(crate) fn with_result(errors: Vec<E>, result: T) -> Self {
        assert!(!errors.is_empty(), "Cannot create a MotorGroupError with no errors");
        Self {
            errors,
            result: Some(result),
        }
    }

    pub(crate) fn with_empty_result(errors: Vec<E>) -> Self {
        assert!(!errors.is_empty(), "Cannot create a MotorGroupError with no errors");
        Self {
            errors,
            result: None,
        }
    }

    /// Returns the result of the motor group error.
    ///
    /// For getters that return a result, this is the value that would be returned
    /// if there were no errors. It is usually an average of the available data.
    /// If all motors in the group return an error, this will be None.
    pub fn result(&self) -> &Option<T> { &self.result }

    /// The first error that occurred in the motor group.
    pub fn first(&self) -> &E { &self.errors[0] }
}

impl From<MotorGroupError<PortError>> for PortError {
    fn from(error: MotorGroupError<PortError>) -> Self { error.errors.into_iter().next().unwrap() }
}

impl From<MotorGroupError<SetGearsetError>> for SetGearsetError {
    fn from(error: MotorGroupError<SetGearsetError>) -> Self {
        error.errors.into_iter().next().unwrap()
    }
}

impl core::fmt::Display for MotorGroupError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "error(s) in MotorGroup: {:?}", self.errors)
    }
}

impl core::error::Error for MotorGroupError {}

/// The mode for handling errors when writing to a motor group.
///
/// This is used to determine how to handle errors when writing to a motor group.
/// "Writing" means doing things like setting a target, setting a voltage,
/// setting a gearset, etc.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WriteErrorStrategy {
    /// Ignore errors and continue writing.
    ///
    /// This means that if a motor is, for example, unplugged, then writes to
    /// other plugged in motors will still be attempted. You should use this
    /// mode for most places where redundancy is practiced. Note that methods will
    /// still return an `Err` variant when an error occurs even if some writes
    /// succeed.
    ///
    /// This is the default mode.
    #[default]
    Ignore,
    /// Stop writing on the first error and return early.
    ///
    /// This means that if a motor encounters an error, no further writes will
    /// be attempted, and the error will be returned immediately. This is useful
    /// for debugging or when you want to ensure that all motors are in a valid
    /// state at all times (e.g. a subsystem should either 100% work or not work
    /// at all.)
    Stop,
}

/// A group of motors that can be controlled together.
///
/// This is a simple wrapper around a vector of motors, with methods to easily
/// control all motors in the group at once as if they were a single motor.
///
/// A motor group is guaranteed to have at least one motor in it.
#[derive(Debug)]
pub struct MotorGroup<M: AsRef<[Motor]> + AsMut<[Motor]> = Vec<Motor>> {
    pub(crate) motors:    M,
    write_error_strategy: WriteErrorStrategy,
}

type GetterResult<T> = Result<T, MotorGroupError<PortError, T>>;

impl<M: AsRef<[Motor]> + AsMut<[Motor]>> MotorGroup<M> {
    /// Creates a new motor group from a vector of motors.
    ///
    /// You can set the write handling mode afterwards by calling
    /// [`write_error_strategy`].
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     _ = motor_group.set_voltage(5.0);
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if there are no motors in the vector.
    pub fn new(motors: M) -> Self {
        assert!(
            !motors.as_ref().is_empty(),
            "Cannot create a motor group with no motors"
        );
        Self {
            motors,
            write_error_strategy: WriteErrorStrategy::default(),
        }
    }

    /// Sets the write error handling strategy for the motor group.
    ///
    /// This determines how to handle errors when writing to the motor group
    /// using methods like [`set_target`], [`set_voltage`], etc.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    pub fn write_error_strategy(&mut self, mode: WriteErrorStrategy) -> &mut Self {
        self.write_error_strategy = mode;
        self
    }

    /// Sets the target that the motor group should attempt to reach.
    ///
    /// This could be a voltage, velocity, position, or even brake mode.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     let _ = motor_group.set_target(MotorControl::Voltage(5.0));
    ///     sleep(Duration::from_secs(1)).await;
    ///     let _ = motor_group.set_target(MotorControl::Brake(BrakeMode::Hold));
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_target).
    pub fn set_target(&mut self, target: MotorControl) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_target(target) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets the motor group's target to a given [`BrakeMode`].
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     let _ = motor_group.brake(BrakeMode::Hold);
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.brake).
    pub fn brake(&mut self, mode: BrakeMode) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.brake(mode) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Spins the motor group at a target velocity.
    ///
    /// This velocity corresponds to different actual speeds in RPM depending on the gearset used for the motor.
    /// Velocity is held with an internal PID controller to ensure consistent speed, as opposed to setting the
    /// motor's voltage.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// Spin a motor group at 100 RPM:
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     let _ = motor_group.set_velocity(100);
    ///     sleep(Duration::from_secs(1)).await;
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_velocity).
    pub fn set_velocity(&mut self, rpm: i32) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_velocity(rpm) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets the motor group's output voltage.
    ///
    /// This voltage value spans from -12 (fully spinning reverse) to +12 (fully spinning forwards) volts, and
    /// controls the raw output of the motor.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// Give the motor group full power:
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     let _ = motor_group.set_voltage(motor_group.max_voltage());
    /// }
    /// ```
    ///
    /// Drive the motor group based on a controller joystick:
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     let controller = peripherals.primary_controller;
    ///     loop {
    ///         let controller_state = controller.state().unwrap_or_default();
    ///         let voltage = controller_state.left_stick.x() * motor_group.max_voltage();
    ///         motor_group.set_voltage(voltage).unwrap();
    ///     }
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_voltage).
    pub fn set_voltage(&mut self, volts: f64) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_voltage(volts) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets an absolute position target for the motor group to attempt to reach.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    ///
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     let _ = motor_group.set_position_target(Angle::from_degrees(90.0), 200);
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_position_target).
    pub fn set_position_target(
        &mut self,
        position: Angle,
        velocity: i32,
    ) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_position_target(position, velocity) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Changes the output velocity for a profiled movement (motor_move_absolute or motor_move_relative).
    ///
    /// This will have no effect if the motor group is not following a profiled movement.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///     // Set the motor group's target to a Angle so that changing the velocity isn't a noop.
    ///     let _ = motor_group.set_target(MotorControl::Angle(Angle::from_degrees(90.0), 200));
    ///     let _ = motor_group.set_profiled_velocity(100).unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_profiled_velocity).
    pub fn set_profiled_velocity(&mut self, velocity: i32) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_profiled_velocity(velocity) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets the gearset of an 11W motor group.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`SetGearsetError`] values) is returned if any motor encounters an error.
    ///   This includes EXP motors, which do not support swappable gearsets.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     // This must be a V5 motor group
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     // Set the motor group to use the red gearset
    ///     motor_group.set_gearset(Gearset::Red).unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_gearset).
    pub fn set_gearset(
        &mut self,
        gearset: Gearset,
    ) -> Result<(), MotorGroupError<SetGearsetError>> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_gearset(gearset) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Returns `true` if the motor group has a 5.5W (EXP) Smart Motor.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new_exp(peripherals.port_1, Direction::Forward),
    ///         Motor::new_exp(peripherals.port_2, Direction::Forward),
    ///     ]);
    ///     if motor_group.has_exp() {
    ///         println!("Motor group has a 5.5W EXP Smart Motor");
    ///     }
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.is_exp).
    pub fn has_exp(&self) -> bool { self.motors.as_ref().iter().any(|motor| motor.is_exp()) }

    /// Returns `true` if the motor group has an 11W (V5) Smart Motor.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Red, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Red, Direction::Forward),
    ///     ]);
    ///     if motor_group.has_v5() {
    ///         println!("Motor group has an 11W V5 Smart Motor");
    ///     }
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.is_v5).
    pub fn has_v5(&self) -> bool { self.motors.as_ref().iter().any(|motor| motor.is_v5()) }

    /// Returns the maximum voltage for the motor group based off of its [motor type](Motor::motor_type).
    ///
    /// # Examples
    ///
    /// Run a motor group at max speed, agnostic of its type:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// fn run_motor_group_at_max_speed(motor_group: &mut MotorGroup) {
    ///     motor_group.set_voltage(motor_group.max_voltage()).unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.max_voltage).
    pub fn max_voltage(&self) -> f64 {
        self.motors
            .as_ref()
            .iter()
            .map(|motor| motor.max_voltage())
            .reduce(f64::max)
            .unwrap()
    }

    /// Returns the average estimated angular velocity of motors in a motor group in rotations per minute (RPM).
    ///
    /// # Accuracy
    ///
    /// In some cases, this reported value may be noisy or innaccurate, especially for systems where accurate
    /// velocity control at high speeds is required (such as flywheels). If the accuracy of this value proves
    /// inadequate, you may opt to perform your own velocity calculations by differentiating [`Motor::position`]
    /// over the reported internal timestamp of the motor using [`Motor::timestamp`].
    ///
    /// > For more information about Smart motor velocity estimation, see [this article](https://sylvie.fyi/sylib/docs/db/d8e/md_module_writeups__velocity__estimation.html).
    ///
    /// # Note
    ///
    /// To get the current **target** velocity instead of the estimated velocity, use [`Motor::target`].
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Get the current velocity of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.velocity().unwrap());
    /// }
    /// ```
    ///
    /// Calculate acceleration of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     let mut last_velocity = motor_group.velocity().unwrap();
    ///     let mut start_time = Instant::now();
    ///     loop {
    ///         let velocity = motor_group.velocity().unwrap();
    ///         // Make sure we don't divide by zero
    ///         let elapsed = start_time.elapsed().as_secs_f64() + 0.001;
    ///
    ///         // Calculate acceleration
    ///         let acceleration = (velocity - last_velocity) / elapsed;
    ///         println!("Velocity: {:.2} RPM, Acceleration: {:.2} RPM/s", velocity, acceleration);
    ///
    ///         last_velocity = velocity;
    ///         start_time = Instant::now();
    ///    }
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.velocity).
    pub fn velocity(&self) -> GetterResult<f64> {
        let mut errors = Vec::new();
        let mut sum = 0.0;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.velocity() {
                Ok(velocity) => {
                    sum += velocity;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Returns the average power drawn by a motor in this the motor group in Watts.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Print the power drawn by a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.power().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.power).
    pub fn power(&self) -> GetterResult<f64> {
        let mut errors = Vec::new();
        let mut sum = 0.0;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.power() {
                Ok(power) => {
                    sum += power;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Returns the average torque of motors in the motor group in Newton-meters.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Print the torque of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.torque().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.torque).
    pub fn torque(&self) -> GetterResult<f64> {
        let mut errors = Vec::new();
        let mut sum = 0.0;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.torque() {
                Ok(torque) => {
                    sum += torque;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Returns the motor group's output voltage.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Print the voltage of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.voltage().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.voltage).
    pub fn voltage(&self) -> GetterResult<f64> {
        let mut errors = Vec::new();
        let mut sum = 0.0;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.voltage() {
                Ok(voltage) => {
                    sum += voltage;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Returns the motor group's average position in ticks.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Print the position of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.position().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.position).
    pub fn position(&self) -> GetterResult<Angle> {
        let mut errors = Vec::new();
        let mut sum = Angle::ZERO;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.position() {
                Ok(position) => {
                    sum += position;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Returns the motor group's average current in Amperes.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Print the current of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.current().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.current).
    pub fn current(&self) -> GetterResult<f64> {
        let mut errors = Vec::new();
        let mut sum = 0.0;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.current() {
                Ok(current) => {
                    sum += current;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Returns the motor group's average efficiency as a percentage.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Print the efficiency of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.efficiency().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.efficiency).
    pub fn efficiency(&self) -> GetterResult<f64> {
        let mut errors = Vec::new();
        let mut sum = 0.0;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.efficiency() {
                Ok(efficiency) => {
                    sum += efficiency;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Resets every motor in the motor group's position to zero.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// Reset the position of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     motor_group.reset_position().unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.reset_position).
    pub fn reset_position(&mut self) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.reset_position() {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets the motor group's position to a given value.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// Set the position of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     motor_group.set_position(Angle::from_degrees(90.0)).unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_position).
    pub fn set_position(&mut self, position: Angle) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_position(position) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets the motor group's current limit in Amperes.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// Set the current limit of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     motor_group.set_current_limit(2.5).unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_current_limit).
    pub fn set_current_limit(&mut self, limit: f64) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_current_limit(limit) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets the motor group's voltage limit in Volts.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// Set the voltage limit of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     motor_group.set_voltage_limit(10.0).unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_voltage_limit).
    pub fn set_voltage_limit(&mut self, limit: f64) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_voltage_limit(limit) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Returns the motor group's temperature in degrees Celsius.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor in the group encounters an error.
    ///
    /// # Examples
    ///
    /// Print the temperature of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.temperature().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.temperature).
    pub fn temperature(&self) -> GetterResult<f64> {
        let mut errors = Vec::new();
        let mut sum = 0.0;
        let mut count = 0;
        for motor in self.motors.as_ref() {
            match motor.temperature() {
                Ok(temperature) => {
                    sum += temperature;
                    count += 1;
                }
                Err(error) => errors.push(error),
            }
        }
        if errors.is_empty() {
            Ok(sum / count as f64)
        } else if count > 0 {
            Err(MotorGroupError::with_result(errors, sum / count as f64))
        } else {
            Err(MotorGroupError::with_empty_result(errors))
        }
    }

    /// Returns `true` if any motor in the motor group is over temperature.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor encounters an error.
    ///
    /// Note that this method will still return `Ok` if a motor encounters an
    /// error but a motor in a group is still over temperature.
    ///
    /// # Examples
    ///
    /// Check if a motor group is over temperature:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.is_over_temperature().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.is_over_temperature).
    pub fn is_over_temperature(&self) -> Result<bool, MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_ref() {
            match motor.is_over_temperature() {
                Ok(true) => return Ok(true),
                Err(error) => errors.push(error),
                _ => {}
            }
        }
        if errors.is_empty() {
            Ok(false)
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Returns `true` if any motor in the motor group is over current.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor encounters an error.
    ///
    /// Note that this method will still return `Ok` if a motor encounters an
    /// error but a motor in a group is still over current.
    ///
    /// # Examples
    ///
    /// Check if a motor group is over current:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.is_over_current().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.is_over_current).
    pub fn is_over_current(&self) -> Result<bool, MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_ref() {
            match motor.is_over_current() {
                Ok(true) => return Ok(true),
                Err(error) => errors.push(error),
                _ => {}
            }
        }
        if errors.is_empty() {
            Ok(false)
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Returns `true` if any motor in the motor group has a driver fault.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor encounters an error.
    ///
    /// Note that this method will still return `Ok` if a motor encounters an
    /// error but a motor in a group has a driver fault.
    ///
    /// # Examples
    ///
    /// Check if a motor group has a driver fault:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.is_driver_fault().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.is_driver_fault).
    pub fn is_driver_fault(&self) -> Result<bool, MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_ref() {
            match motor.is_driver_fault() {
                Ok(true) => return Ok(true),
                Err(error) => errors.push(error),
                _ => {}
            }
        }
        if errors.is_empty() {
            Ok(false)
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Returns `true` if the any motor in the motor group is over current.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] error is returned if any motor encounters an error.
    ///
    /// Note that this method will still return `Ok` if a motor encounters an
    /// error but a motor in a group is still over current.
    ///
    /// # Examples
    ///
    /// Check if a motor group is over current:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     println!("{:?}", motor_group.is_driver_over_current().unwrap());
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.is_driver_over_current).
    pub fn is_driver_over_current(&self) -> Result<bool, MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_ref() {
            match motor.is_driver_over_current() {
                Ok(true) => return Ok(true),
                Err(error) => errors.push(error),
                _ => {}
            }
        }
        if errors.is_empty() {
            Ok(false)
        } else {
            Err(MotorGroupError::new(errors))
        }
    }

    /// Sets the motor group's direction.
    ///
    /// # Errors
    ///
    /// - A [`MotorGroupError`] (containing one or more [`PortError`] values) is returned if a motor device is not currently connected to the Smart Port.
    ///
    /// # Examples
    ///
    /// Set the direction of a motor group:
    /// ```rust,ignore
    /// use vexide::prelude::*;
    /// use antaeus::peripherals::motorgroup::*;
    ///
    /// #[vexide::main]
    /// async fn main(peripherals: Peripherals) {
    ///     let mut motor_group = MotorGroup::new(vec![
    ///         Motor::new(peripherals.port_1, Gearset::Green, Direction::Forward),
    ///         Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward),
    ///     ]);
    ///
    ///     motor_group.set_direction(Direction::Reverse).unwrap();
    /// }
    /// ```
    ///
    /// See the original method [here](https://docs.rs/vexide/latest/vexide/devices/smart/struct.Motor.html#method.set_direction).
    pub fn set_direction(&mut self, direction: Direction) -> Result<(), MotorGroupError> {
        let mut errors = Vec::new();
        for motor in self.motors.as_mut() {
            if let Err(error) = motor.set_direction(direction) {
                errors.push(error);
                if self.write_error_strategy == WriteErrorStrategy::Stop {
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(MotorGroupError::new(errors))
        }
    }
}

// Unit tests for `lib.rs` covering MotorGroupError helpers and error strategy
// These tests avoid hardware-specific APIs and focus on pure-data helpers

#[cfg(test)]
mod tests {

    use super::{MotorGroupError, WriteErrorStrategy};

    #[derive(Debug, PartialEq, Eq, Clone)]
    struct FakeErr(&'static str);

    #[test]
    fn motor_group_error_new_panics_on_empty() {
        // MotorGroupError::new should panic when given an empty errors vector
        let v: Vec<FakeErr> = vec![];
        let res = std::panic::catch_unwind(|| MotorGroupError::new(v));
        assert!(
            res.is_err(),
            "expected MotorGroupError::new to panic on empty errors vector"
        );
    }

    #[test]
    fn motor_group_error_with_result_and_first() {
        let errors = vec![FakeErr("a"), FakeErr("b")];

        // with_result is crate-private but available to tests in the same crate
        let mg_err = MotorGroupError::with_result(errors.clone(), 42u32);

        // first() returns a reference to the first error
        assert_eq!(mg_err.first(), &errors[0]);

        // result() should return the provided result
        assert_eq!(mg_err.result(), &Some(42u32));

        // errors vector should be preserved
        assert_eq!(mg_err.errors.len(), 2);
    }

    #[test]
    fn motor_group_error_with_empty_result() {
        let errors = vec![FakeErr("x")];

        let mg_err: MotorGroupError<FakeErr, ()> =
            MotorGroupError::with_empty_result(errors.clone());

        // No result available when using with_empty_result
        assert_eq!(mg_err.result(), &None);

        // Error list is present and first() works
        assert_eq!(mg_err.errors.len(), 1);
        assert_eq!(mg_err.first(), &errors[0]);
    }

    #[test]
    fn write_error_strategy_default_is_ignore() {
        // Default strategy should be Ignore
        assert_eq!(WriteErrorStrategy::default(), WriteErrorStrategy::Ignore);
    }
}