autocore-std 3.3.34

Standard library for AutoCore control programs - shared memory, IPC, and logging utilities
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
use crate::motion::{
    AxisView,
    cia402::{
        Cia402Control, Cia402Status, Cia402State, ModesOfOperation,
        PpControl, PpStatus,
        HomingControl, HomingStatus,
    },
};
use crate::ethercat::teknic::types::{
    TeknicPpControlWord, TeknicPpStatusWord,
    TeknicPpControl, TeknicPpStatus,
    TeknicHomingControlWord, TeknicHomingStatusWord,
};

// ──────────────────────────────────────────────
// HomingProgress
// ──────────────────────────────────────────────

/// Homing procedure progress, decoded from status word bits 10, 12, 13.
///
/// | Error (13) | Attained (12) | Reached (10) | Progress     |
/// |------------|---------------|--------------|--------------|
/// | 0          | 0             | 1            | `Idle`       |
/// | 0          | 0             | 0            | `InProgress` |
/// | 0          | 1             | 0            | `Attained`   |
/// | 0          | 1             | 1            | `Complete`   |
/// | 1          | x             | x            | `Error`      |
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HomingProgress {
    /// Homing not started or interrupted (motor stationary).
    Idle,
    /// Homing actively in progress (motor searching).
    InProgress,
    /// Reference found; offset move still in progress.
    Attained,
    /// Homing completed successfully — position is now referenced.
    Complete,
    /// A homing error occurred (motor may still be moving).
    Error,
}

impl std::fmt::Display for HomingProgress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Idle       => write!(f, "Idle"),
            Self::InProgress => write!(f, "In Progress"),
            Self::Attained   => write!(f, "Attained"),
            Self::Complete   => write!(f, "Complete"),
            Self::Error      => write!(f, "Error"),
        }
    }
}

// ──────────────────────────────────────────────
// TeknicPpView — borrowed view for one axis
// ──────────────────────────────────────────────

/// A borrowed view into GlobalMemory for one Teknic ClearPath axis.
///
/// Supports both **Profile Position (PP)** moves and the **Homing**
/// phase that typically precedes them. Holds mutable references to
/// RxPDO (output) fields and shared references to TxPDO (input) fields.
/// Reuse the same struct for multiple axes — just point the references
/// at different GlobalMemory fields via [`teknic_pp_view!`].
///
/// # Homing Example
///
/// Homing is performed once at startup. Configure homing parameters
/// (method, speeds, acceleration) via SDO before entering the control
/// loop.
///
/// ```ignore
/// use crate::teknic::view::{TeknicPpView, HomingProgress};
/// use crate::motion::types::{Cia402State, ModesOfOperation};
///
/// #[derive(Debug, Clone, Copy, PartialEq)]
/// enum HomingState {
///     Init,
///     WaitMode,
///     WaitComplete,
///     Done,
///     Failed,
/// }
///
/// fn tick_homing(view: &mut TeknicPpView, state: &mut HomingState) {
///     if view.is_faulted() && *state != HomingState::Failed {
///         log::error!("Drive fault during homing");
///         *state = HomingState::Failed;
///     }
///
///     match state {
///         HomingState::Init => {
///             view.ensure_homing_mode();
///             view.cmd_enable_operation();
///             *state = HomingState::WaitMode;
///         }
///         HomingState::WaitMode => {
///             if view.state() == Cia402State::OperationEnabled
///                 && view.current_mode() == Some(ModesOfOperation::Homing)
///             {
///                 view.trigger_homing();
///                 *state = HomingState::WaitComplete;
///             }
///         }
///         HomingState::WaitComplete => {
///             match view.homing_progress() {
///                 HomingProgress::Complete => {
///                     view.clear_homing_start();
///                     log::info!("Homing complete at pos {}", view.position());
///                     *state = HomingState::Done;
///                 }
///                 HomingProgress::Error => {
///                     log::error!("Homing error!");
///                     *state = HomingState::Failed;
///                 }
///                 _ => {} // still in progress
///             }
///         }
///         HomingState::Done => {
///             // Switch to PP mode for positioning.
///             view.ensure_pp_mode();
///         }
///         HomingState::Failed => {
///             view.cmd_fault_reset();
///             if view.state() == Cia402State::SwitchOnDisabled {
///                 *state = HomingState::Init;
///             }
///         }
///     }
/// }
/// ```
///
/// # Profile Position Example
///
/// After homing, use PP mode to make absolute or relative moves.
///
/// ```ignore
/// use crate::teknic::view::TeknicPpView;
/// use crate::motion::types::Cia402State;
///
/// #[derive(Debug, Clone, Copy, PartialEq)]
/// enum MoveState {
///     Init,
///     WaitReady,
///     WaitEnabled,
///     StartMove,
///     WaitAck,
///     WaitComplete,
///     Done,
///     Faulted,
/// }
///
/// fn tick_move(view: &mut TeknicPpView, state: &mut MoveState) {
///     if view.is_faulted() && *state != MoveState::Faulted {
///         log::error!("Drive fault detected in state {:?}", state);
///         *state = MoveState::Faulted;
///     }
///
///     match state {
///         MoveState::Init => {
///             view.ensure_pp_mode();
///             view.cmd_shutdown();           // → Ready to Switch On
///             *state = MoveState::WaitReady;
///         }
///         MoveState::WaitReady => {
///             if view.state() == Cia402State::ReadyToSwitchOn {
///                 view.cmd_enable_operation(); // → Operation Enabled
///                 *state = MoveState::WaitEnabled;
///             }
///         }
///         MoveState::WaitEnabled => {
///             if view.state() == Cia402State::OperationEnabled {
///                 *state = MoveState::StartMove;
///             }
///         }
///         MoveState::StartMove => {
///             // Absolute move to 100 000 counts at 50 000 cts/s
///             view.set_target(100_000, 50_000, 10_000, 10_000);
///             view.set_relative(false);      // absolute move
///             view.trigger_move();
///             *state = MoveState::WaitAck;
///         }
///         MoveState::WaitAck => {
///             if view.set_point_acknowledged() {
///                 view.ack_set_point();       // complete handshake
///                 *state = MoveState::WaitComplete;
///             }
///         }
///         MoveState::WaitComplete => {
///             if view.following_error() {
///                 log::error!("Following error at pos {}", view.position());
///                 *state = MoveState::Faulted;
///             } else if view.target_reached() && view.in_range() {
///                 *state = MoveState::Done;
///             }
///         }
///         MoveState::Done => {
///             // Move complete — start another or disable the drive.
///         }
///         MoveState::Faulted => {
///             view.cmd_fault_reset();
///             if view.state() == Cia402State::SwitchOnDisabled {
///                 *state = MoveState::Init;   // recovered, restart
///             }
///         }
///     }
/// }
/// ```
pub struct TeknicPpView<'a> {
    // ── RxPDO — master → drive ──
    pub control_word: &'a mut u16,
    pub target_position: &'a mut i32,
    pub profile_velocity: &'a mut u32,
    pub profile_acceleration: &'a mut u32,
    pub profile_deceleration: &'a mut u32,
    pub modes_of_operation: &'a mut i8,

    // ── TxPDO — drive → master ──
    pub status_word: &'a u16,
    pub position_actual: &'a i32,
    pub velocity_actual: &'a i32,
    pub torque_actual: &'a i16,
    pub modes_of_operation_display: &'a i8,
}

/// Teknic-specific convenience methods for `TeknicPpView` (borrowed).
/// The macro parameter `$deref` controls whether field access dereferences
/// a reference (`*`) or reads directly. Includes both standard CiA 402 methods
/// and Teknic vendor-specific extensions (has_homed, in_range, at_velocity).
macro_rules! impl_teknic_pp_methods {
    ($T:ty, deref: $($d:tt)*) => {
        impl $T {
            // ── Typed access ──

            /// Read the control word as a typed Teknic PP control word.
            pub fn pp_control(&self) -> TeknicPpControlWord {
                TeknicPpControlWord($($d)* self.control_word)
            }

            /// Read the status word as a typed Teknic PP status word.
            pub fn pp_status(&self) -> TeknicPpStatusWord {
                TeknicPpStatusWord($($d)* self.status_word)
            }

            /// Write back a modified PP control word.
            pub fn set_pp_control(&mut self, cw: TeknicPpControlWord) {
                $($d)* self.control_word = cw.raw();
            }

            // ── State machine ──

            /// Current CiA 402 state.
            pub fn state(&self) -> Cia402State {
                self.pp_status().state()
            }

            /// Shutdown → Ready to Switch On.
            pub fn cmd_shutdown(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_shutdown();
                self.set_pp_control(cw);
            }

            /// Switch On → Switched On.
            pub fn cmd_switch_on(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_switch_on();
                self.set_pp_control(cw);
            }

            /// Enable Operation → Operation Enabled.
            pub fn cmd_enable_operation(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_enable_operation();
                self.set_pp_control(cw);
            }

            /// Disable Operation → Switched On.
            pub fn cmd_disable_operation(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_disable_operation();
                self.set_pp_control(cw);
            }

            /// Disable Voltage → Switch On Disabled.
            pub fn cmd_disable_voltage(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_disable_voltage();
                self.set_pp_control(cw);
            }

            /// Quick Stop → Quick Stop Active.
            pub fn cmd_quick_stop(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_quick_stop();
                self.set_pp_control(cw);
            }

            /// Fault Reset (rising edge on bit 7).
            pub fn cmd_fault_reset(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_fault_reset();
                self.set_pp_control(cw);
            }

            /// Clear/reset Fault Reset bit (bit 7).
            pub fn cmd_clear_fault_reset(&mut self) {
                let mut cw = self.pp_control();
                cw.cmd_clear_fault_reset();
                self.set_pp_control(cw);
            }

            // ── PP motion ──

            /// Set mode to Profile Position.
            pub fn ensure_pp_mode(&mut self) {
                $($d)* self.modes_of_operation = ModesOfOperation::ProfilePosition.as_i8();
            }

            /// Configure move parameters (does not trigger the move).
            pub fn set_target(&mut self, position: i32, velocity: u32, accel: u32, decel: u32) {
                $($d)* self.target_position = position;
                $($d)* self.profile_velocity = velocity;
                $($d)* self.profile_acceleration = accel;
                $($d)* self.profile_deceleration = decel;
            }

            /// Assert New Set-Point (bit 4). Call after set_target().
            pub fn trigger_move(&mut self) {
                let mut cw = self.pp_control();
                cw.set_new_set_point(true);
                self.set_pp_control(cw);
            }

            /// Clear New Set-Point. Call when set_point_acknowledged() is true.
            pub fn ack_set_point(&mut self) {
                let mut cw = self.pp_control();
                cw.set_new_set_point(false);
                self.set_pp_control(cw);
            }

            /// Bit 8 — Halt: decelerate to stop.
            pub fn set_halt(&mut self, v: bool) {
                let mut cw = self.pp_control();
                cw.set_halt(v);
                self.set_pp_control(cw);
            }

            /// Bit 6 — Relative: when true, target_position is relative to the
            /// current *command* position. When false, target_position is absolute.
            pub fn set_relative(&mut self, v: bool) {
                let mut cw = self.pp_control();
                cw.set_relative(v);
                self.set_pp_control(cw);
            }

            /// Bit 13 (Teknic) — Relative to Actual: when true *and* bit 6 is set,
            /// target_position is relative to the *actual* position rather than the
            /// command position. Only meaningful when `set_relative(true)`.
            pub fn set_relative_to_actual(&mut self, v: bool) {
                let mut cw = self.pp_control();
                cw.set_relative_to_actual(v);
                self.set_pp_control(cw);
            }

            // ── PP status queries ──

            /// Drive has reached the target position.
            pub fn target_reached(&self) -> bool {
                self.pp_status().pp_target_reached()
            }

            /// Set-point was acknowledged by the drive.
            pub fn set_point_acknowledged(&self) -> bool {
                self.pp_status().set_point_acknowledge()
            }

            /// Teknic: position within in-range window.
            pub fn in_range(&self) -> bool {
                self.pp_status().in_range()
            }

            /// Teknic bit 8 — Has Homed: persistent flag that remains set after any
            /// successful homing procedure, even after switching back to PP or PV mode.
            pub fn has_homed(&self) -> bool {
                self.pp_status().has_homed()
            }

            /// Teknic: actual velocity has reached target.
            pub fn at_velocity(&self) -> bool {
                self.pp_status().at_velocity()
            }

            // ── Error / fault status ──

            /// Bit 13 — Following Error: position tracking error exceeded the
            /// configured limit. Typically leads to a fault transition.
            pub fn following_error(&self) -> bool {
                self.pp_status().following_error()
            }

            /// Bit 11 — Internal Limit Active: a hardware or software limit
            /// is currently active (e.g. position or velocity limit).
            pub fn internal_limit(&self) -> bool {
                self.pp_status().internal_limit()
            }

            /// Bit 7 — Warning: a non-fatal warning condition exists.
            pub fn warning(&self) -> bool {
                self.pp_status().warning()
            }

            /// True if the drive is in Fault or Fault Reaction Active state.
            pub fn is_faulted(&self) -> bool {
                matches!(self.state(), Cia402State::Fault | Cia402State::FaultReactionActive)
            }

            // ── Homing ──

            /// Set mode to Homing.
            pub fn ensure_homing_mode(&mut self) {
                $($d)* self.modes_of_operation = ModesOfOperation::Homing.as_i8();
            }

            /// Start the homing procedure (rising edge on bit 4).
            pub fn trigger_homing(&mut self) {
                let mut cw = TeknicHomingControlWord($($d)* self.control_word);
                cw.set_homing_start(true);
                $($d)* self.control_word = cw.raw();
            }

            /// Clear the homing start bit. Call after homing completes.
            pub fn clear_homing_start(&mut self) {
                let mut cw = TeknicHomingControlWord($($d)* self.control_word);
                cw.set_homing_start(false);
                $($d)* self.control_word = cw.raw();
            }

            /// Decode the current homing progress from status word bits 10, 12, 13.
            pub fn homing_progress(&self) -> HomingProgress {
                let sw = TeknicHomingStatusWord($($d)* self.status_word);
                let attained = sw.homing_attained();
                let reached  = sw.homing_target_reached();
                let error    = sw.homing_error();

                if error {
                    HomingProgress::Error
                } else if attained && reached {
                    HomingProgress::Complete
                } else if attained {
                    HomingProgress::Attained
                } else if reached {
                    HomingProgress::Idle
                } else {
                    HomingProgress::InProgress
                }
            }

            // ── Feedback ──

            /// Actual position in encoder counts.
            pub fn position(&self) -> i32 {
                $($d)* self.position_actual
            }

            /// Actual velocity in encoder counts/s.
            pub fn velocity(&self) -> i32 {
                $($d)* self.velocity_actual
            }

            /// Actual torque in per-mille of rated torque.
            pub fn torque(&self) -> i16 {
                $($d)* self.torque_actual
            }

            /// Mode the drive is currently operating in.
            pub fn current_mode(&self) -> Option<ModesOfOperation> {
                ModesOfOperation::from_i8($($d)* self.modes_of_operation_display)
            }
        }
    };
}

// Apply shared methods to TeknicPpView (dereferences references)
impl_teknic_pp_methods!(TeknicPpView<'_>, deref: *);

// ──────────────────────────────────────────────
// AxisView implementation for TeknicPpView
// ──────────────────────────────────────────────

impl AxisView for TeknicPpView<'_> {
    fn control_word(&self) -> u16 { *self.control_word }
    fn set_control_word(&mut self, word: u16) { *self.control_word = word; }
    fn status_word(&self) -> u16 { *self.status_word }
    fn set_target_position(&mut self, pos: i32) { *self.target_position = pos; }
    fn set_profile_velocity(&mut self, vel: u32) { *self.profile_velocity = vel; }
    fn set_profile_acceleration(&mut self, accel: u32) { *self.profile_acceleration = accel; }
    fn set_profile_deceleration(&mut self, decel: u32) { *self.profile_deceleration = decel; }
    fn set_modes_of_operation(&mut self, mode: i8) { *self.modes_of_operation = mode; }
    fn modes_of_operation_display(&self) -> i8 { *self.modes_of_operation_display }
    fn position_actual(&self) -> i32 { *self.position_actual }
    fn velocity_actual(&self) -> i32 { *self.velocity_actual }
    // error_code: uses default (0) — Teknic error code not in standard view fields
}

// ──────────────────────────────────────────────
// View factory macro
// ──────────────────────────────────────────────

/// Create a [`TeknicPpView`] by projecting GlobalMemory fields with a common prefix.
///
/// Fields must follow the naming convention `{prefix}_control_word`,
/// `{prefix}_target_position`, etc.
///
/// # Example
///
/// ```ignore
/// let mut view = teknic_pp_view!(ctx.gm, axis1);
/// view.ensure_pp_mode();
/// view.cmd_enable_operation();
/// view.set_target(10_000, 5_000, 1_000, 1_000);
/// view.trigger_move();
/// ```
#[macro_export]
macro_rules! teknic_pp_view {
    ($gm:expr, $prefix:ident) => {
        paste::paste! {
            $crate::teknic::view::TeknicPpView {
                control_word:              &mut $gm.[<$prefix _control_word>],
                target_position:           &mut $gm.[<$prefix _target_position>],
                profile_velocity:          &mut $gm.[<$prefix _profile_velocity>],
                profile_acceleration:      &mut $gm.[<$prefix _profile_acceleration>],
                profile_deceleration:      &mut $gm.[<$prefix _profile_deceleration>],
                modes_of_operation:        &mut $gm.[<$prefix _modes_of_operation>],
                status_word:               & $gm.[<$prefix _status_word>],
                position_actual:           & $gm.[<$prefix _position_actual>],
                velocity_actual:           & $gm.[<$prefix _velocity_actual>],
                torque_actual:             & $gm.[<$prefix _torque_actual>],
                modes_of_operation_display: & $gm.[<$prefix _modes_of_operation_display>],
            }
        }
    };
}

// ──────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────

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

    /// Local storage for PDO fields used in tests. Avoids depending on
    /// auto-generated GlobalMemory field names.
    #[derive(Default)]
    struct TestPdo {
        control_word: u16,
        target_position: i32,
        profile_velocity: u32,
        profile_acceleration: u32,
        profile_deceleration: u32,
        modes_of_operation: i8,
        status_word: u16,
        position_actual: i32,
        velocity_actual: i32,
        torque_actual: i16,
        modes_of_operation_display: i8,
    }

    impl TestPdo {
        fn view(&mut self) -> TeknicPpView<'_> {
            TeknicPpView {
                control_word:              &mut self.control_word,
                target_position:           &mut self.target_position,
                profile_velocity:          &mut self.profile_velocity,
                profile_acceleration:      &mut self.profile_acceleration,
                profile_deceleration:      &mut self.profile_deceleration,
                modes_of_operation:        &mut self.modes_of_operation,
                status_word:               &self.status_word,
                position_actual:           &self.position_actual,
                velocity_actual:           &self.velocity_actual,
                torque_actual:             &self.torque_actual,
                modes_of_operation_display: &self.modes_of_operation_display,
            }
        }
    }

    // ── State machine ──

    #[test]
    fn test_view_reads_state() {
        let mut pdo = TestPdo { status_word: 0x0040, ..Default::default() };
        let view = pdo.view();
        assert_eq!(view.state(), Cia402State::SwitchOnDisabled);
    }

    #[test]
    fn test_view_cmd_shutdown() {
        let mut pdo = TestPdo { status_word: 0x0040, ..Default::default() };
        let mut view = pdo.view();
        view.cmd_shutdown();
        assert_eq!(*view.control_word & 0x008F, 0x0006);
    }

    #[test]
    fn test_view_cmd_enable_operation() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.cmd_enable_operation();
        assert_eq!(*view.control_word & 0x008F, 0x000F);
    }

    // ── PP motion ──

    #[test]
    fn test_view_set_target_and_trigger() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.cmd_enable_operation();
        view.set_target(50_000, 10_000, 2_000, 2_000);
        view.trigger_move();

        assert_eq!(*view.target_position, 50_000);
        assert_eq!(*view.profile_velocity, 10_000);
        assert_eq!(*view.profile_acceleration, 2_000);
        assert_eq!(*view.profile_deceleration, 2_000);
        assert!(*view.control_word & (1 << 4) != 0);
    }

    #[test]
    fn test_view_ack_set_point() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.cmd_enable_operation();
        view.trigger_move();
        assert!(*view.control_word & (1 << 4) != 0);

        view.ack_set_point();
        assert!(*view.control_word & (1 << 4) == 0);
        assert_eq!(*view.control_word & 0x000F, 0x000F);
    }

    #[test]
    fn test_view_absolute_move() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.cmd_enable_operation();
        view.set_relative(false);
        view.set_target(100_000, 50_000, 10_000, 10_000);
        view.trigger_move();

        assert_eq!(*view.control_word & (1 << 6), 0);
        assert!(*view.control_word & (1 << 4) != 0);
    }

    #[test]
    fn test_view_relative_move() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.cmd_enable_operation();
        view.set_relative(true);
        view.set_target(5_000, 10_000, 2_000, 2_000);
        view.trigger_move();

        assert!(*view.control_word & (1 << 6) != 0);
    }

    #[test]
    fn test_view_relative_to_actual() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.cmd_enable_operation();
        view.set_relative(true);
        view.set_relative_to_actual(true);
        view.set_target(1_000, 5_000, 1_000, 1_000);
        view.trigger_move();

        assert!(*view.control_word & (1 << 6) != 0);
        assert!(*view.control_word & (1 << 13) != 0);
    }

    // ── Feedback ──

    #[test]
    fn test_view_feedback() {
        let mut pdo = TestPdo {
            position_actual: 12345,
            velocity_actual: -500,
            torque_actual: 100,
            modes_of_operation_display: 1,
            ..Default::default()
        };
        let view = pdo.view();

        assert_eq!(view.position(), 12345);
        assert_eq!(view.velocity(), -500);
        assert_eq!(view.torque(), 100);
        assert_eq!(view.current_mode(), Some(ModesOfOperation::ProfilePosition));
    }

    #[test]
    fn test_view_teknic_status_bits() {
        let mut pdo = TestPdo {
            // Operation Enabled (0x27) + has_homed (bit 8) + in_range (bit 15)
            status_word: 0x8127,
            ..Default::default()
        };
        let view = pdo.view();

        assert_eq!(view.state(), Cia402State::OperationEnabled);
        assert!(view.has_homed());
        assert!(view.in_range());
        assert!(!view.at_velocity());
    }

    #[test]
    fn test_view_ensure_pp_mode() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.ensure_pp_mode();
        assert_eq!(*view.modes_of_operation, 1);
    }

    // ── Error / fault ──

    #[test]
    fn test_view_following_error() {
        let mut pdo = TestPdo {
            // Operation Enabled (0x27) + following error (bit 13)
            status_word: 0x2027,
            ..Default::default()
        };
        let view = pdo.view();

        assert_eq!(view.state(), Cia402State::OperationEnabled);
        assert!(view.following_error());
        assert!(!view.is_faulted());
    }

    #[test]
    fn test_view_internal_limit() {
        let mut pdo = TestPdo { status_word: 0x0827, ..Default::default() };
        let view = pdo.view();
        assert!(view.internal_limit());
    }

    #[test]
    fn test_view_warning() {
        let mut pdo = TestPdo { status_word: 0x00A7, ..Default::default() };
        let view = pdo.view();
        assert_eq!(view.state(), Cia402State::OperationEnabled);
        assert!(view.warning());
    }

    #[test]
    fn test_view_is_faulted() {
        let mut pdo = TestPdo::default();

        pdo.status_word = 0x0008; // Fault
        let view = pdo.view();
        assert!(view.is_faulted());
        assert_eq!(view.state(), Cia402State::Fault);

        pdo.status_word = 0x000F; // Fault Reaction Active
        let view = pdo.view();
        assert!(view.is_faulted());

        pdo.status_word = 0x0027; // Operation Enabled — not faulted
        let view = pdo.view();
        assert!(!view.is_faulted());
    }

    // ── Homing ──

    #[test]
    fn test_view_ensure_homing_mode() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.ensure_homing_mode();
        assert_eq!(*view.modes_of_operation, 6);
    }

    #[test]
    fn test_view_trigger_and_clear_homing() {
        let mut pdo = TestPdo::default();
        let mut view = pdo.view();
        view.cmd_enable_operation();

        // Bit 4 should be clear initially
        assert_eq!(*view.control_word & (1 << 4), 0);

        // Trigger homing — bit 4 set
        view.trigger_homing();
        assert!(*view.control_word & (1 << 4) != 0);
        // State machine bits preserved
        assert_eq!(*view.control_word & 0x000F, 0x000F);

        // Clear homing start — bit 4 clear
        view.clear_homing_start();
        assert_eq!(*view.control_word & (1 << 4), 0);
        assert_eq!(*view.control_word & 0x000F, 0x000F);
    }

    #[test]
    fn test_homing_progress_idle() {
        let mut pdo = TestPdo {
            // Bit 10 = 1, bit 12 = 0, bit 13 = 0 → Idle (not started)
            status_word: 0x0427, // OpEnabled + bit10
            ..Default::default()
        };
        let view = pdo.view();
        assert_eq!(view.homing_progress(), HomingProgress::Idle);
    }

    #[test]
    fn test_homing_progress_in_progress() {
        let mut pdo = TestPdo {
            // Bit 10 = 0, bit 12 = 0, bit 13 = 0 → In Progress
            status_word: 0x0027, // OpEnabled, bits 10/12/13 clear
            ..Default::default()
        };
        let view = pdo.view();
        assert_eq!(view.homing_progress(), HomingProgress::InProgress);
    }

    #[test]
    fn test_homing_progress_attained() {
        let mut pdo = TestPdo {
            // Bit 12 = 1, bit 10 = 0, bit 13 = 0 → Attained
            status_word: 0x1027,
            ..Default::default()
        };
        let view = pdo.view();
        assert_eq!(view.homing_progress(), HomingProgress::Attained);
    }

    #[test]
    fn test_homing_progress_complete() {
        let mut pdo = TestPdo {
            // Bit 12 = 1, bit 10 = 1, bit 13 = 0 → Complete
            status_word: 0x1427,
            ..Default::default()
        };
        let view = pdo.view();
        assert_eq!(view.homing_progress(), HomingProgress::Complete);
    }

    #[test]
    fn test_homing_progress_error() {
        let mut pdo = TestPdo {
            // Bit 13 = 1 → Error (regardless of other bits)
            status_word: 0x2027,
            ..Default::default()
        };
        let view = pdo.view();
        assert_eq!(view.homing_progress(), HomingProgress::Error);

        // Error + attained + reached → still Error
        pdo.status_word = 0x3427;
        let view = pdo.view();
        assert_eq!(view.homing_progress(), HomingProgress::Error);
    }

    #[test]
    fn test_homing_has_homed_persists_across_modes() {
        let mut pdo = TestPdo {
            // OpEnabled + bit8 (has_homed)
            status_word: 0x0127,
            modes_of_operation_display: 1, // PP mode
            ..Default::default()
        };
        let view = pdo.view();

        assert!(view.has_homed());
        assert_eq!(view.current_mode(), Some(ModesOfOperation::ProfilePosition));
    }

    // ── AxisView ──

    #[test]
    fn test_axis_view_impl() {
        let mut pdo = TestPdo {
            status_word: 0x0027,
            position_actual: 5000,
            velocity_actual: 1000,
            modes_of_operation_display: 1,
            ..Default::default()
        };
        let mut view = pdo.view();

        // AxisView reads
        assert_eq!(AxisView::status_word(&view), 0x0027);
        assert_eq!(AxisView::position_actual(&view), 5000);
        assert_eq!(AxisView::velocity_actual(&view), 1000);
        assert_eq!(AxisView::modes_of_operation_display(&view), 1);

        // AxisView writes
        AxisView::set_control_word(&mut view, 0x000F);
        assert_eq!(*view.control_word, 0x000F);
        AxisView::set_target_position(&mut view, 10_000);
        assert_eq!(*view.target_position, 10_000);
    }
}