moteus 0.5.0

Rust client library for moteus brushless motor 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
// Copyright 2026 mjbots Robotic Systems, LLC.  info@mjbots.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Blocking controller API for moteus devices.
//!
//! This module provides the `BlockingController` which combines frame building
//! with a synchronous transport for direct, blocking communication with moteus
//! controllers. This is the simplest API to use when async is not needed.
//!
//! # Auto-Discovery
//!
//! The controller can automatically discover and use available transports:
//!
//! ```no_run
//! use moteus::BlockingController;
//! use moteus::command::PositionCommand;
//!
//! fn main() -> Result<(), moteus::Error> {
//!     // Auto-discover transport
//!     let mut ctrl = BlockingController::new(1)?;
//!     ctrl.set_stop()?;
//!     Ok(())
//! }
//! ```
//!
//! # Explicit Transport
//!
//! You can also construct a transport yourself and hand it to the
//! controller. The canonical pattern for a single bus is to open one
//! [`Fdcanusb`](crate::Fdcanusb) and pass it to
//! [`with_transport`](BlockingController::with_transport):
//!
//! ```no_run
//! use moteus::{BlockingController, Fdcanusb};
//!
//! fn main() -> Result<(), moteus::Error> {
//!     let transport = Fdcanusb::open("/dev/fdcanusb")?;
//!     let mut ctrl = BlockingController::with_transport(1, transport);
//!     Ok(())
//! }
//! ```

use crate::command_ext::MaybeQuery;
use crate::controller::Controller;
use crate::device_address::DeviceAddress;
use crate::error::{Error, Result};
use crate::transport::factory::TransportOptions;
use crate::transport::singleton::get_singleton_transport;
use crate::transport::transaction::Request;
use crate::transport::{Router, Transport};
use moteus_protocol::command::{
    AuxPwmCommand, CurrentCommand, PositionCommand, StayWithinCommand, VFOCCommand,
    ZeroVelocityCommand,
};
use moteus_protocol::query::{QueryFormat, QueryResult};
use moteus_protocol::Resolution;
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// A blocking controller for a single moteus device.
///
/// This combines the frame-building capabilities of `Controller` with
/// a synchronous transport for blocking communication. This is the simplest
/// API for controlling a moteus when you don't need async.
///
/// # Example
///
/// ```no_run
/// use moteus::{BlockingController, command::PositionCommand};
///
/// fn main() -> Result<(), moteus::Error> {
///     // Create with auto-discovered transport
///     let mut ctrl = BlockingController::new(1)?;
///
///     // Query the controller
///     let result = ctrl.query()?;
///     println!("Position: {}", result.position);
///
///     // Move to a position using builder pattern
///     let result = ctrl.set_position(
///         PositionCommand::new().position(0.5).velocity(1.0)
///     )?;
///
///     // Or with explicit transport options
///     use moteus::TransportOptions;
///     let opts = TransportOptions::new()
///         .socketcan_interfaces(vec!["can0"]);
///     let mut ctrl = BlockingController::with_options(1, &opts)?;
///     Ok(())
/// }
/// ```
pub struct BlockingController<T: Transport = Arc<Mutex<Router>>> {
    /// Frame builder
    pub controller: Controller,
    /// Router for communication
    pub(crate) transport: T,
}

impl<T: Transport> std::fmt::Debug for BlockingController<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BlockingController")
            .field("id", &self.controller.id)
            .field("address", &self.controller.address)
            .finish()
    }
}

// =============================================================================
// Singleton constructors (use global shared transport)
// =============================================================================

impl BlockingController<Arc<Mutex<Router>>> {
    /// Creates a new blocking controller with auto-discovered transport.
    ///
    /// # Arguments
    /// * `address` - Device address (CAN ID or UUID). Integers are automatically
    ///   converted to CAN ID addresses.
    ///
    /// # Errors
    ///
    /// Returns an error if no transport can be discovered.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::{BlockingController, DeviceAddress};
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     // Using integer CAN ID
    ///     let mut ctrl = BlockingController::new(1)?;
    ///
    ///     // Using explicit DeviceAddress
    ///     let mut ctrl = BlockingController::new(DeviceAddress::can_id(1))?;
    ///     Ok(())
    /// }
    /// ```
    pub fn new(address: impl Into<DeviceAddress>) -> Result<Self> {
        Ok(Self {
            controller: Controller::new(address),
            transport: get_singleton_transport(None)?,
        })
    }

    /// Creates a controller with specific transport options.
    ///
    /// # Arguments
    /// * `address` - Device address (CAN ID or UUID). Integers are automatically
    ///   converted to CAN ID addresses.
    /// * `options` - Router options for device selection and configuration
    ///
    /// # Errors
    ///
    /// Returns an error if no transport can be discovered with the given options.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::{BlockingController, TransportOptions};
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let opts = TransportOptions::new()
    ///         .socketcan_interfaces(vec!["can0"])
    ///         .timeout(std::time::Duration::from_millis(200));
    ///     let mut ctrl = BlockingController::with_options(1, &opts)?;
    ///     Ok(())
    /// }
    /// ```
    pub fn with_options(
        address: impl Into<DeviceAddress>,
        options: &TransportOptions,
    ) -> Result<Self> {
        Ok(Self {
            controller: Controller::new(address),
            transport: get_singleton_transport(Some(options))?,
        })
    }

    /// Creates a blocking controller with a pre-configured Controller.
    ///
    /// # Errors
    ///
    /// Returns an error if no transport can be discovered.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::{BlockingController, Controller};
    /// use moteus::query::QueryFormat;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let ctrl = BlockingController::with_controller(
    ///         Controller::new(1)
    ///             .query_format(QueryFormat::comprehensive())
    ///             .source_id(0x10),
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn with_controller(controller: Controller) -> Result<Self> {
        Ok(Self {
            controller,
            transport: get_singleton_transport(None)?,
        })
    }
}

// =============================================================================
// Generic methods (work with any transport)
// =============================================================================

impl<T: Transport> BlockingController<T> {
    /// Creates a blocking controller with an explicit transport.
    ///
    /// This bypasses auto-discovery and uses the provided transport directly.
    ///
    /// # Example
    ///
    /// ```
    /// use moteus::BlockingController;
    /// use moteus::transport::NullTransport;
    ///
    /// let mut ctrl = BlockingController::with_transport(1, NullTransport::new());
    /// ```
    pub fn with_transport(address: impl Into<DeviceAddress>, transport: T) -> Self {
        Self {
            controller: Controller::new(address),
            transport,
        }
    }

    /// Sets the communication timeout.
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.transport.set_timeout(timeout);
    }

    /// Returns the current timeout.
    pub fn timeout(&self) -> Duration {
        self.transport.timeout()
    }

    // === Query Methods ===

    /// Queries the controller for current state.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn query(&mut self) -> Result<QueryResult> {
        let mut requests = [Request::from_command(self.controller.make_query())];
        self.transport.cycle(&mut requests)?;

        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Queries with a custom format.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn query_with_format(&mut self, format: &QueryFormat) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_query_with_format(format),
        )];
        self.transport.cycle(&mut requests)?;

        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    // === Stop/Brake Methods ===

    /// Sends a stop command and returns the query result.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn set_stop(&mut self) -> Result<QueryResult> {
        let mut requests = [Request::from_command(self.controller.make_stop(true))];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Sends a stop command without waiting for response.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_stop_no_query(&mut self) -> Result<()> {
        let mut requests = [Request::from_command(self.controller.make_stop(false))];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    /// Sends a brake command and returns the query result.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn set_brake(&mut self) -> Result<QueryResult> {
        let mut requests = [Request::from_command(self.controller.make_brake(true))];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Sends a brake command without waiting for response.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_brake_no_query(&mut self) -> Result<()> {
        let mut requests = [Request::from_command(self.controller.make_brake(false))];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    // === Position Mode Methods ===

    /// Commands position mode and returns the query result.
    ///
    /// # Arguments
    /// * `cmd` - Position command built with the builder pattern, optionally
    ///   with `.with_query()` to override the query format
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    /// use moteus::command_ext::CommandExt;
    /// use moteus::command::PositionCommand;
    /// use moteus::query::QueryFormat;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///
    ///     // Simple position command
    ///     let result = ctrl.set_position(
    ///         PositionCommand::new().position(0.5)
    ///     )?;
    ///
    ///     // With velocity
    ///     let result = ctrl.set_position(
    ///         PositionCommand::new().position(0.5).velocity(1.0)
    ///     )?;
    ///
    ///     // With full control
    ///     let result = ctrl.set_position(
    ///         PositionCommand::new()
    ///             .position(0.5)
    ///             .velocity(1.0)
    ///             .kp_scale(0.8)
    ///             .maximum_torque(2.0)
    ///     )?;
    ///
    ///     // With query format override
    ///     let result = ctrl.set_position(
    ///         PositionCommand::new()
    ///             .position(0.5)
    ///             .with_query(QueryFormat::comprehensive())
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_position(
        &mut self,
        cmd: impl Into<MaybeQuery<PositionCommand>>,
    ) -> Result<QueryResult> {
        let maybe = cmd.into();
        let (command, query_override) = maybe.into_parts();
        let query_format = query_override
            .as_ref()
            .unwrap_or(&self.controller.query_format);

        let mut cmd = self.controller.prepare_command(true);
        command.serialize(cmd.frame_mut(), &self.controller.position_format);
        cmd.expected_reply_size = query_format.serialize(cmd.frame_mut());

        let mut requests = [Request::from_command(cmd)];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Commands position mode without waiting for response.
    ///
    /// This is a bandwidth optimization for when you don't need feedback.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_position_no_query(&mut self, cmd: &PositionCommand) -> Result<()> {
        let mut requests = [Request::from_command(
            self.controller.make_position_command(cmd, false),
        )];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    /// Waits for a position move to complete.
    ///
    /// Polls the controller until trajectory_complete is true or timeout.
    ///
    /// # Arguments
    /// * `poll_interval` - How often to poll
    /// * `timeout` - Maximum time to wait
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    /// Returns `Error::Timeout` if the operation exceeds the timeout.
    pub fn wait_for_trajectory_complete(
        &mut self,
        poll_interval: Duration,
        timeout: Duration,
    ) -> Result<QueryResult> {
        let start = std::time::Instant::now();

        loop {
            let result = self.query()?;

            if result.trajectory_complete {
                return Ok(result);
            }

            if start.elapsed() > timeout {
                return Err(Error::Timeout);
            }

            std::thread::sleep(poll_interval);
        }
    }

    // === Current Mode Methods ===

    /// Commands current (torque) mode and returns the query result.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    /// use moteus::command::CurrentCommand;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///     let result = ctrl.set_current(
    ///         CurrentCommand::new().q_current(0.5).d_current(0.0)
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_current(
        &mut self,
        cmd: impl Into<MaybeQuery<CurrentCommand>>,
    ) -> Result<QueryResult> {
        let maybe = cmd.into();
        let (command, query_override) = maybe.into_parts();
        let query_format = query_override
            .as_ref()
            .unwrap_or(&self.controller.query_format);

        let mut cmd = self.controller.prepare_command(true);
        command.serialize(cmd.frame_mut(), &self.controller.current_format);
        cmd.expected_reply_size = query_format.serialize(cmd.frame_mut());

        let mut requests = [Request::from_command(cmd)];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Commands current mode without waiting for response.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_current_no_query(&mut self, cmd: &CurrentCommand) -> Result<()> {
        let mut requests = [Request::from_command(
            self.controller.make_current_command(cmd, false),
        )];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    // === VFOC Mode Methods ===

    /// Commands voltage FOC mode and returns the query result.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    /// use moteus::command::VFOCCommand;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///     let result = ctrl.set_vfoc(
    ///         VFOCCommand::new().theta(0.0).voltage(1.0)
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_vfoc(&mut self, cmd: impl Into<MaybeQuery<VFOCCommand>>) -> Result<QueryResult> {
        let maybe = cmd.into();
        let (command, query_override) = maybe.into_parts();
        let query_format = query_override
            .as_ref()
            .unwrap_or(&self.controller.query_format);

        let mut cmd = self.controller.prepare_command(true);
        command.serialize(cmd.frame_mut(), &self.controller.vfoc_format);
        cmd.expected_reply_size = query_format.serialize(cmd.frame_mut());

        let mut requests = [Request::from_command(cmd)];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Commands VFOC mode without waiting for response.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_vfoc_no_query(&mut self, cmd: &VFOCCommand) -> Result<()> {
        let mut requests = [Request::from_command(
            self.controller.make_vfoc_command(cmd, false),
        )];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    // === Stay-Within Mode Methods ===

    /// Commands stay-within mode and returns the query result.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    /// use moteus::command::StayWithinCommand;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///     let result = ctrl.set_stay_within(
    ///         StayWithinCommand::new()
    ///             .lower_bound(-0.5)
    ///             .upper_bound(0.5)
    ///             .maximum_torque(2.0)
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_stay_within(
        &mut self,
        cmd: impl Into<MaybeQuery<StayWithinCommand>>,
    ) -> Result<QueryResult> {
        let maybe = cmd.into();
        let (command, query_override) = maybe.into_parts();
        let query_format = query_override
            .as_ref()
            .unwrap_or(&self.controller.query_format);

        let mut cmd = self.controller.prepare_command(true);
        command.serialize(cmd.frame_mut(), &self.controller.stay_within_format);
        cmd.expected_reply_size = query_format.serialize(cmd.frame_mut());

        let mut requests = [Request::from_command(cmd)];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Commands stay-within mode without waiting for response.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_stay_within_no_query(&mut self, cmd: &StayWithinCommand) -> Result<()> {
        let mut requests = [Request::from_command(
            self.controller.make_stay_within_command(cmd, false),
        )];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    // === Zero-Velocity Mode Methods ===

    /// Commands zero-velocity mode (hold position with damping) and returns the query result.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    /// use moteus::command::ZeroVelocityCommand;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///
    ///     // With default kd_scale
    ///     let result = ctrl.set_zero_velocity(ZeroVelocityCommand::new())?;
    ///
    ///     // With custom kd_scale
    ///     let result = ctrl.set_zero_velocity(
    ///         ZeroVelocityCommand::new().kd_scale(0.5)
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_zero_velocity(
        &mut self,
        cmd: impl Into<MaybeQuery<ZeroVelocityCommand>>,
    ) -> Result<QueryResult> {
        let maybe = cmd.into();
        let (command, query_override) = maybe.into_parts();
        let query_format = query_override
            .as_ref()
            .unwrap_or(&self.controller.query_format);

        let mut cmd = self.controller.prepare_command(true);
        command.serialize(cmd.frame_mut(), &self.controller.zero_velocity_format);
        cmd.expected_reply_size = query_format.serialize(cmd.frame_mut());

        let mut requests = [Request::from_command(cmd)];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Commands zero-velocity mode without waiting for response.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_zero_velocity_no_query(&mut self, cmd: &ZeroVelocityCommand) -> Result<()> {
        let mut requests = [Request::from_command(
            self.controller.make_zero_velocity_command(cmd, false),
        )];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    // === Output Position Methods ===

    /// Sets output position to nearest value.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn set_output_nearest(&mut self, position: f32) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_set_output_nearest(position, true),
        )];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Sets output position to exact value.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn set_output_exact(&mut self, position: f32) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_set_output_exact(position, true),
        )];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Requires re-indexing of the encoder.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn set_require_reindex(&mut self) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_require_reindex(true),
        )];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Recaptures position and velocity.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn set_recapture_position_velocity(&mut self) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_recapture_position_velocity(true),
        )];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    // === GPIO Methods ===

    /// Reads GPIO digital inputs from both AUX ports.
    ///
    /// Returns a tuple of (aux1, aux2) where each byte represents pin states.
    /// Bit N corresponds to pin N's state.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///     let (aux1, aux2) = ctrl.read_gpio()?;
    ///
    ///     // Check individual pins
    ///     if aux1 & 0x01 != 0 {
    ///         println!("AUX1 Pin 0 is HIGH");
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn read_gpio(&mut self) -> Result<(u8, u8)> {
        let mut requests = [Request::from_command(self.controller.make_read_gpio())];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| {
                let gpio = self.controller.parse_gpio(&f);
                (gpio.aux1, gpio.aux2)
            })
            .ok_or(Error::NoResponse)
    }

    /// Writes GPIO digital outputs.
    ///
    /// # Arguments
    /// * `aux1` - Optional value for AUX1 GPIO outputs (bit N = pin N)
    /// * `aux2` - Optional value for AUX2 GPIO outputs (bit N = pin N)
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///
    ///     // Set all GPIO outputs to high
    ///     ctrl.set_write_gpio(Some(0x7f), Some(0x7f))?;
    ///
    ///     // Set only AUX1 outputs
    ///     ctrl.set_write_gpio(Some(0x1f), None)?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_write_gpio(&mut self, aux1: Option<u8>, aux2: Option<u8>) -> Result<()> {
        let mut requests = [Request::from_command(
            self.controller.make_write_gpio(aux1, aux2, false),
        )];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    /// Writes GPIO digital outputs and returns query result.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    pub fn set_write_gpio_query(
        &mut self,
        aux1: Option<u8>,
        aux2: Option<u8>,
    ) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_write_gpio(aux1, aux2, true),
        )];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    // === Custom Query Methods ===

    /// Queries specific registers by address.
    ///
    /// This allows querying arbitrary registers by specifying them as
    /// (register_address, resolution) pairs.
    ///
    /// # Arguments
    /// * `registers` - Slice of (register address, resolution) tuples to query
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::{BlockingController, Register, Resolution};
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///     let result = ctrl.custom_query(&[
    ///         (Register::Position.address(), Resolution::Float),
    ///         (Register::Velocity.address(), Resolution::Float),
    ///     ])?;
    ///     Ok(())
    /// }
    /// ```
    pub fn custom_query(&mut self, registers: &[(u16, Resolution)]) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_custom_query(registers),
        )];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    // === AUX PWM Methods ===

    /// Sets AUX PWM outputs and returns query result.
    ///
    /// # Arguments
    /// * `cmd` - AUX PWM command built with the builder pattern
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::NoResponse` if the device does not reply.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    /// use moteus::command::AuxPwmCommand;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///     let result = ctrl.set_aux_pwm(
    ///         &AuxPwmCommand::new().aux1_pwm1(0.5).aux1_pwm2(0.75)
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_aux_pwm(&mut self, cmd: &AuxPwmCommand) -> Result<QueryResult> {
        let mut requests = [Request::from_command(
            self.controller.make_aux_pwm(cmd, true),
        )];
        self.transport.cycle(&mut requests)?;
        requests[0]
            .responses
            .take()
            .into_iter()
            .next()
            .map(|f| self.controller.parse_query(&f))
            .ok_or(Error::NoResponse)
    }

    /// Sets AUX PWM outputs without waiting for response.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_aux_pwm_no_query(&mut self, cmd: &AuxPwmCommand) -> Result<()> {
        let mut requests = [Request::from_command(
            self.controller.make_aux_pwm(cmd, false),
        )];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    // === Clock Trim Methods ===

    /// Sets the clock trim value.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication fails.
    pub fn set_trim(&mut self, trim: i32) -> Result<()> {
        let mut requests = [Request::from_command(self.controller.make_set_trim(trim))];
        self.transport.cycle(&mut requests)?;
        Ok(())
    }

    // === Position Wait Complete Methods ===

    /// Commands position mode and waits for trajectory completion.
    ///
    /// Unlike `wait_for_trajectory_complete`, this re-sends the position command
    /// each cycle until the trajectory is complete.
    ///
    /// # Arguments
    /// * `cmd` - Position command built with the builder pattern
    /// * `poll_interval` - How often to poll
    /// * `timeout` - Maximum time to wait
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable or communication
    /// fails. Returns `Error::Timeout` if the operation exceeds the
    /// timeout. Returns `Error::Fault` if the device reports a fault or
    /// timeout mode.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use moteus::BlockingController;
    /// use moteus::command::PositionCommand;
    /// use std::time::Duration;
    ///
    /// fn main() -> Result<(), moteus::Error> {
    ///     let mut ctrl = BlockingController::new(1)?;
    ///     let result = ctrl.set_position_wait_complete(
    ///         &PositionCommand::new().position(0.5).stop_position(0.5),
    ///         Duration::from_millis(25),   // poll every 25ms
    ///         Duration::from_secs(5),      // timeout after 5 seconds
    ///     )?;
    ///     Ok(())
    /// }
    /// ```
    pub fn set_position_wait_complete(
        &mut self,
        cmd: &PositionCommand,
        poll_interval: Duration,
        timeout: Duration,
    ) -> Result<QueryResult> {
        let start = std::time::Instant::now();

        // We need trajectory_complete in the response
        let mut query_format = self.controller.query_format.clone();
        query_format.trajectory_complete = moteus_protocol::Resolution::Int8;
        if query_format.mode == moteus_protocol::Resolution::Ignore {
            query_format.mode = moteus_protocol::Resolution::Int8;
        }
        if query_format.fault == moteus_protocol::Resolution::Ignore {
            query_format.fault = moteus_protocol::Resolution::Int8;
        }

        // Need a few successful reads before declaring complete
        let mut success_count: i32 = 2;

        loop {
            // Send position command with query
            let mut command = self.controller.prepare_command(true);
            cmd.serialize(command.frame_mut(), &self.controller.position_format);
            command.expected_reply_size = query_format.serialize(command.frame_mut());

            let mut requests = [Request::from_command(command)];
            self.transport.cycle(&mut requests)?;
            let result = requests[0]
                .responses
                .take()
                .into_iter()
                .next()
                .map(|f| self.controller.parse_query(&f));

            if let Some(ref r) = result {
                success_count = success_count.saturating_sub(1);

                // Check for faults
                if r.mode == moteus_protocol::Mode::Fault
                    || r.mode == moteus_protocol::Mode::Timeout
                {
                    return Err(Error::Fault {
                        mode: r.mode as u8,
                        code: r.fault,
                    });
                }

                // Check if trajectory is complete
                if success_count == 0 && r.trajectory_complete {
                    return result.ok_or(Error::NoResponse);
                }
            }

            if start.elapsed() > timeout {
                return Err(Error::Timeout);
            }

            std::thread::sleep(poll_interval);
        }
    }

    // === Router Methods ===

    /// Flushes any pending data from the transport.
    ///
    /// This is useful when recovering from errors or resynchronizing
    /// with the device.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport is unavailable.
    pub fn flush_transport(&mut self) -> Result<()> {
        // Attempt a read with a short timeout to clear any pending data
        let old_timeout = self.transport.timeout();
        self.transport.set_timeout(Duration::from_millis(20));
        let mut requests: [Request; 0] = [];
        let _ = self.transport.cycle(&mut requests); // Ignore any errors/responses
        self.transport.set_timeout(old_timeout);
        Ok(())
    }
}

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

    #[test]
    fn test_with_transport_is_infallible() {
        // with_transport never fails — no discovery needed
        let _ctrl = BlockingController::with_transport(1, NullTransport::new());
    }

    #[test]
    fn test_with_options_is_infallible() {
        let opts = TransportOptions::new().timeout(Duration::from_millis(200));
        // with_options returns Result, but we just check it compiles
        let _: std::result::Result<BlockingController, _> =
            BlockingController::with_options(1, &opts);
    }

    #[test]
    fn test_explicit_transport() {
        let mut ctrl = BlockingController::with_transport(1, NullTransport::new());
        assert_eq!(ctrl.controller.id, 1);

        // NullTransport returns no responses, so we get NoResponse error
        let result = ctrl.set_stop();
        assert!(result.is_err());
    }

    #[test]
    fn test_timeout() {
        let mut ctrl = BlockingController::with_transport(1, NullTransport::new());

        // Default timeout
        assert_eq!(ctrl.timeout(), Duration::from_millis(100));

        // Set new timeout
        ctrl.set_timeout(Duration::from_millis(500));
        assert_eq!(ctrl.timeout(), Duration::from_millis(500));
    }

    #[test]
    fn test_set_position_no_query() {
        let mut ctrl = BlockingController::with_transport(1, NullTransport::new());

        let result = ctrl.set_position_no_query(&PositionCommand::new().position(0.5));
        assert!(result.is_ok());
    }
}