Skip to main content

autocore_std/motion/
axis.rs

1//! Stateful motion controller for CiA 402 servo drives.
2//!
3//! [`Axis`] manages the CiA 402 protocol state machine internally,
4//! providing a clean high-level motion API. It owns an [`SdoClient`]
5//! for SDO operations during homing.
6//!
7//! # Usage
8//!
9//! ```ignore
10//! use autocore_std::motion::{Axis, AxisConfig};
11//!
12//! let config = AxisConfig::new(12_800).with_user_scale(360.0);
13//! let mut axis = Axis::new(config, "ClearPath_0");
14//!
15//! // In your control loop:
16//! axis.tick(&mut view, ctx.client);
17//!
18//! // Command the axis:
19//! axis.enable(&mut view);              // start enable sequence
20//! axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
21//! axis.home(&mut view, HomingMethod::CurrentPosition);
22//! ```
23
24use std::time::{Duration, Instant};
25
26use serde_json::json;
27use strum_macros::FromRepr;
28
29use crate::command_client::CommandClient;
30use crate::ethercat::{SdoClient, SdoResult};
31use crate::fb::Ton;
32use crate::motion::FbSetModeOfOperation;
33use super::axis_config::AxisConfig;
34use super::axis_view::AxisView;
35use super::homing::HomingMethod;
36use super::cia402::{
37    Cia402Control, Cia402Status, Cia402State,
38    ModesOfOperation, RawControlWord, RawStatusWord,
39};
40
41// ──────────────────────────────────────────────
42// Internal state machine
43// ──────────────────────────────────────────────
44
45#[derive(Debug, Clone, PartialEq)]
46enum AxisOp {
47    Idle,
48    Enabling(u8),
49    Disabling(u8),
50    Moving(MoveKind, u8, bool, bool),
51    Homing(u8),
52    SoftHoming(u8),
53    Halting(u8),
54    FaultRecovery(u8),
55}
56
57/// Sub-steps of `AxisOp::Halting`. Mirrors the multi-stage close-out used
58/// by soft-homing: wait for motion to stop, issue cancel_move, wait for
59/// setpoint_ack, clear new_setpoint, wait for setpoint_ack to drop.
60/// Without this sequence the PP handshake is left half-finished and the
61/// next `move_absolute` gets rejected with "set-point not acknowledged."
62#[repr(u8)]
63#[derive(Debug, Clone, PartialEq, FromRepr)]
64enum HaltState {
65    /// Halt bit set + new_setpoint cleared. Polling position for
66    /// stability before issuing cancel_move.
67    WaitStopped        = 0,
68    /// cancel_move issued. Waiting for SW bit 12 (setpoint_ack) AND
69    /// bit 10 (target_reached) — drive has accepted the cancel.
70    WaitCancelAck      = 10,
71    /// Ack received, new_setpoint cleared, single-setpoint flush bit
72    /// asserted. Waiting for SW bit 12 to drop so the next move's
73    /// rising edge is clean.
74    WaitCancelAckClear = 20,
75}
76
77/// How long each halt sub-stage may take before we error out.
78const HALT_STAGE_TIMEOUT: Duration = Duration::from_secs(3);
79
80/// Raw-encoder-count window within which the axis is considered "stopped."
81/// Sized to tolerate servo micro-oscillation during closed-loop hold.
82/// On a 10 000 cnt/mm drive this is 0.005 mm — below any meaningful
83/// motion but well above typical ±5 count hold jitter.
84const HALT_STABLE_WINDOW: i32 = 50;
85
86/// Velocity magnitude (in raw drive units, typically counts/s) at or
87/// below which the axis is considered "not moving" for the purposes of
88/// completing a halt. Used alongside position stability so we don't
89/// require *both* perfect position and zero velocity — either reliable
90/// indicator counts.
91const HALT_STOPPED_VELOCITY: i32 = 100;
92
93/// Consecutive ticks of stability required before issuing cancel_move.
94/// At a 10 ms scan period, 5 ticks = ~50 ms dwell — long enough for the
95/// drive to have actually settled, short enough not to stall the cycle.
96const HALT_STABLE_TICKS_REQUIRED: u8 = 5;
97
98#[repr(u8)]
99#[derive(Debug, Clone, PartialEq, FromRepr)]
100enum HomeState {
101    EnsurePpMode = 0,
102    WaitPpMode = 1,
103    Search = 5,
104    WaitSearching = 10,
105    WaitFoundSensor = 20,
106    WaitStoppedFoundSensor = 30,
107    WaitFoundSensorAck = 40,
108    WaitFoundSensorAckClear = 45,
109    DebounceFoundSensor = 50,
110    BackOff = 60,
111    WaitBackingOff = 70,
112    WaitLostSensor = 80,
113    WaitStoppedLostSensor = 90,
114    WaitLostSensorAck = 100,
115    WaitLostSensorAckClear = 120,
116    WaitHomeOffsetDone = 125,
117
118    WriteHomingModeOp = 160,
119    WaitWriteHomingModeOp = 165,
120    
121    WriteHomingMethod = 205,
122    WaitWriteHomingMethodDone = 210,
123    ClearHomingTrigger = 215,
124    TriggerHoming = 217,
125    WaitHomingStarted = 218,
126    WaitHomingDone = 220,
127    ResetHomingTrigger = 222,
128    WaitHomingTriggerCleared = 223,
129    WriteMotionModeOfOperation = 230,
130    WaitWriteMotionModeOfOperation = 235,
131    SendCurrentPositionTarget = 240,
132    WaitCurrentPositionTargetSent = 245
133
134}
135
136#[derive(Debug, Clone, PartialEq)]
137enum MoveKind {
138    Absolute,
139    Relative,
140}
141
142#[derive(Debug, Clone, Copy, PartialEq)]
143enum SoftHomeSensor {
144    PositiveLimit,
145    NegativeLimit,
146    HomeSensor,
147}
148
149#[derive(Debug, Clone, Copy, PartialEq)]
150enum SoftHomeSensorType {
151    /// PNP: sensor reads true when object detected (normally open)
152    Pnp,
153    /// NPN: sensor reads false when object detected (normally closed)
154    Npn,
155}
156
157// ──────────────────────────────────────────────
158// Axis
159// ──────────────────────────────────────────────
160
161/// Stateful motion controller for a CiA 402 servo drive.
162///
163/// Manages the CiA 402 protocol (state machine, PP handshake, homing)
164/// internally. Call [`tick()`](Self::tick) every control cycle to progress
165/// operations and update output fields.
166pub struct Axis {
167    config: AxisConfig,
168    sdo: SdoClient,
169
170    // ── Internal state ──
171    op: AxisOp,
172    home_offset: i32,
173    last_raw_position: i32,
174    op_started: Option<Instant>,
175    op_timeout: Duration,
176    homing_timeout: Duration,
177    move_start_timeout: Duration,
178    pending_move_target: i32,
179    pending_move_vel: u32,
180    pending_move_accel: u32,
181    pending_move_decel: u32,
182    homing_method: i8,
183    homing_sdo_tid: u32,
184    soft_home_sensor: SoftHomeSensor,
185    soft_home_sensor_type: SoftHomeSensorType,
186    soft_home_direction: f64,
187    halt_stable_count: u8,
188    prev_positive_limit: bool,
189    prev_negative_limit: bool,
190    prev_home_sensor: bool,
191
192
193
194    fb_mode_of_operation : FbSetModeOfOperation,
195
196    // ── Outputs (updated every tick) ──
197
198    /// True if a drive fault or operation timeout has occurred.
199    pub is_error: bool,
200    /// Drive error code (from status word or view error_code).
201    pub error_code: u32,
202    /// Human-readable error description.
203    pub error_message: String,
204    /// True when the drive is in Operation Enabled state.
205    pub motor_on: bool,
206    /// True when any operation is in progress (enable, move, home, fault recovery, etc.).
207    ///
208    /// Derived from the internal state machine — immediately true when a command
209    /// is issued, false when the operation completes or a fault cancels it.
210    /// Use this (not [`in_motion`](Self::in_motion)) to wait for operations to finish.
211    pub is_busy: bool,
212    /// True while a move operation specifically is active (subset of [`is_busy`](Self::is_busy)).
213    pub in_motion: bool,
214    /// True when velocity is positive.
215    pub moving_positive: bool,
216    /// True when velocity is negative.
217    pub moving_negative: bool,
218    /// Current position in user units (relative to home).
219    pub position: f64,
220    /// Current position in raw encoder counts (widened from i32).
221    pub raw_position: i64,
222    /// Current speed in user units/s (absolute value).
223    pub speed: f64,
224    /// True when position is at or beyond the maximum software limit.
225    pub at_max_limit: bool,
226    /// True when position is at or beyond the minimum software limit.
227    pub at_min_limit: bool,
228    /// True when the positive-direction hardware limit switch is active.
229    pub at_positive_limit_switch: bool,
230    /// True when the negative-direction hardware limit switch is active.
231    pub at_negative_limit_switch: bool,
232    /// True when the home reference sensor is active.
233    pub home_sensor: bool,
234
235
236    /// Timer used for delays between states.
237    ton : Ton
238}
239
240impl Axis {
241    /// Create a new Axis with the given configuration.
242    ///
243    /// `device_name` must match the device name in `project.json`
244    /// (used for SDO operations during homing).
245    pub fn new(config: AxisConfig, device_name: &str) -> Self {
246        let op_timeout = Duration::from_secs_f64(config.operation_timeout_secs);
247        let homing_timeout = Duration::from_secs_f64(config.homing_timeout_secs);
248        let move_start_timeout = op_timeout; // reuse operation timeout for move handshake
249        Self {
250            config,
251            sdo: SdoClient::new(device_name),
252            op: AxisOp::Idle,
253            home_offset: 0,
254            last_raw_position: 0,
255            op_started: None,
256            op_timeout,
257            homing_timeout,
258            move_start_timeout,
259            pending_move_target: 0,
260            pending_move_vel: 0,
261            pending_move_accel: 0,
262            pending_move_decel: 0,
263            homing_method: 37,
264            homing_sdo_tid: 0,
265            soft_home_sensor: SoftHomeSensor::HomeSensor,
266            soft_home_sensor_type: SoftHomeSensorType::Pnp,
267            soft_home_direction: 1.0,
268            halt_stable_count: 0,
269            prev_positive_limit: false,
270            prev_negative_limit: false,
271            prev_home_sensor: false,
272            is_error: false,
273            error_code: 0,
274            error_message: String::new(),
275            motor_on: false,
276            is_busy: false,
277            in_motion: false,
278            moving_positive: false,
279            moving_negative: false,
280            position: 0.0,
281            raw_position: 0,
282            speed: 0.0,
283            at_max_limit: false,
284            at_min_limit: false,
285            at_positive_limit_switch: false,
286            at_negative_limit_switch: false,
287            home_sensor: false,
288            ton: Ton::new(),
289            fb_mode_of_operation : FbSetModeOfOperation::new()
290        }
291    }
292
293    /// Get a reference to the axis configuration.
294    pub fn config(&self) -> &AxisConfig {
295        &self.config
296    }
297
298    // ═══════════════════════════════════════════
299    // Motion commands
300    // ═══════════════════════════════════════════
301
302    /// Start an absolute move to `target` in user units.
303    ///
304    /// The axis must be enabled (Operation Enabled) before calling this.
305    /// If the target exceeds a software position limit, the move is rejected
306    /// and [`is_error`](Self::is_error) is set.
307    pub fn move_absolute(
308        &mut self,
309        view: &mut impl AxisView,
310        target: f64,
311        vel: f64,
312        accel: f64,
313        decel: f64,
314    ) {
315        if let Some(msg) = self.check_target_limit(target, view) {
316            self.set_op_error(&msg);
317            return;
318        }
319
320        let cpu = self.config.counts_per_user();
321        let raw_target = self.config.to_counts(target).round() as i32 + self.home_offset;
322        let raw_vel = (vel * cpu).round() as u32;
323        let raw_accel = (accel * cpu).round() as u32;
324        let raw_decel = (decel * cpu).round() as u32;
325
326        // User-frame direction (consistent with sw_max/sw_min and hw_pos/hw_neg).
327        let user_pos = target > self.position;
328        let user_neg = target < self.position;
329
330        self.start_move(view, raw_target, raw_vel, raw_accel, raw_decel, MoveKind::Absolute, user_pos, user_neg);
331    }
332
333    /// Start a relative move by `distance` user units from the current position.
334    ///
335    /// The axis must be enabled (Operation Enabled) before calling this.
336    /// If the resulting position would exceed a software position limit,
337    /// the move is rejected and [`is_error`](Self::is_error) is set.
338    pub fn move_relative(
339        &mut self,
340        view: &mut impl AxisView,
341        distance: f64,
342        vel: f64,
343        accel: f64,
344        decel: f64,
345    ) {
346        log::info!("Axis: request to move relative dist {} vel {} accel {} decel {}",
347            distance, vel, accel, decel
348        );
349
350        if let Some(msg) = self.check_target_limit(self.position + distance, view) {
351            self.set_op_error(&msg);
352            return;
353        }
354
355        let cpu = self.config.counts_per_user();
356        let raw_distance = self.config.to_counts(distance).round() as i32;
357        let raw_vel = (vel * cpu).round() as u32;
358        let raw_accel = (accel * cpu).round() as u32;
359        let raw_decel = (decel * cpu).round() as u32;
360
361        log::info!("Axis starting relative move: request to move relative raw dist {} raw vel {} raw accel {} raw decel {}",
362            raw_distance, raw_vel, raw_accel, raw_decel
363        );
364
365        // Make sure bit 4 is off so that a new move can be commanded.
366        let mut cw = RawControlWord(view.control_word());
367        cw.set_bit(4, false); // new set-point
368        view.set_control_word(cw.raw());
369
370        // User-frame direction is the sign of `distance` (which is in user units).
371        let user_pos = distance > 0.0;
372        let user_neg = distance < 0.0;
373
374        self.start_move(view, raw_distance, raw_vel, raw_accel, raw_decel, MoveKind::Relative, user_pos, user_neg);
375    }
376
377    fn start_move(
378        &mut self,
379        view: &mut impl AxisView,
380        raw_target: i32,
381        raw_vel: u32,
382        raw_accel: u32,
383        raw_decel: u32,
384        kind: MoveKind,
385        user_pos: bool,
386        user_neg: bool,
387    ) {
388        self.pending_move_target = raw_target;
389        self.pending_move_vel = raw_vel;
390        self.pending_move_accel = raw_accel;
391        self.pending_move_decel = raw_decel;
392
393        // Set parameters on view
394        view.set_target_position(raw_target);
395        view.set_profile_velocity(raw_vel);
396        view.set_profile_acceleration(raw_accel);
397        view.set_profile_deceleration(raw_decel);
398
399        // Set control word: relative bit + trigger (new set-point).
400        // We also clear halt as belt-and-suspenders — limit-switch halts and
401        // explicit halt() both flow through the Halting state machine, which
402        // ends with halt already cleared, so this is normally a no-op.
403        let mut cw = RawControlWord(view.control_word());
404        cw.set_bit(6, kind == MoveKind::Relative);
405        cw.set_bit(8, false); // clear halt
406        cw.set_bit(4, true);  // new set-point
407        view.set_control_word(cw.raw());
408
409        // pos/neg stored in AxisOp::Moving are USER-frame so that check_limits
410        // can compare them directly against user-frame software limits and
411        // the integrator's user-frame limit-switch wiring without an
412        // axis-inversion swap.
413        self.op = AxisOp::Moving(kind, 1, user_pos, user_neg);
414        self.op_started = Some(Instant::now());
415    }
416
417    /// Halt the current move (decelerate to stop).
418    ///
419    /// This is a **multi-tick** operation. `halt()` starts the sequence:
420    ///
421    /// 1. Halt bit (CW 8) set, new_setpoint (CW 4) cleared.
422    /// 2. Wait for motor position to stabilize for ~100 ms.
423    /// 3. Issue cancel_move with current_position as target.
424    /// 4. Wait for setpoint_ack (SW 12) + target_reached (SW 10).
425    /// 5. Clear new_setpoint, set single_setpoint (CW 5).
426    /// 6. Wait for setpoint_ack to drop.
427    /// 7. Return to Idle.
428    ///
429    /// [`is_busy`](Self::is_busy) stays `true` for the whole sequence.
430    /// Callers that wait on `!is_busy()` after `halt()` (e.g.
431    /// [`super::move_to_load::MoveToLoad`]) will correctly block until
432    /// the drive's PP handshake is fully cleaned up, preventing a
433    /// "set-point not acknowledged" timeout on the *next* move.
434    pub fn halt(&mut self, view: &mut impl AxisView) {
435        self.command_halt(view);
436        self.halt_stable_count = 0;
437        self.last_raw_position = view.position_actual();
438        self.op_started = Some(Instant::now());
439        self.op = AxisOp::Halting(HaltState::WaitStopped as u8);
440    }
441
442    // ═══════════════════════════════════════════
443    // Drive control
444    // ═══════════════════════════════════════════
445
446    /// Start the enable sequence (Shutdown → ReadyToSwitchOn → OperationEnabled).
447    ///
448    /// The sequence is multi-tick. Check [`motor_on`](Self::motor_on) for completion.
449    pub fn enable(&mut self, view: &mut impl AxisView) {
450        // Step 0: set PP mode + cmd_shutdown
451        view.set_modes_of_operation(ModesOfOperation::ProfilePosition.as_i8());
452        let mut cw = RawControlWord(view.control_word());
453        cw.cmd_shutdown();
454        view.set_control_word(cw.raw());
455
456        self.op = AxisOp::Enabling(1);
457        self.op_started = Some(Instant::now());
458    }
459
460    /// Start the disable sequence (OperationEnabled → SwitchedOn).
461    pub fn disable(&mut self, view: &mut impl AxisView) {
462        let mut cw = RawControlWord(view.control_word());
463        cw.cmd_disable_operation();
464        cw.set_bit(4, false);
465        cw.set_bit(8, false);
466        cw.set_bit(7, false);
467        cw.set_bit(2, true);
468        view.set_control_word(cw.raw());
469
470        self.op = AxisOp::Disabling(1);
471        self.op_started = Some(Instant::now());
472    }
473
474    /// Clear the axis error state.
475    ///
476    /// Two paths depending on whether the drive itself is faulted:
477    ///
478    /// - **Drive in CiA 402 Fault / FaultReactionActive**: runs the full
479    ///   reset sequence — clear bit 7, then assert it next tick (rising
480    ///   edge on the drive's fault-reset bit), then wait for the drive to
481    ///   leave the Fault state. `is_busy` stays true through this sequence.
482    ///
483    /// - **Drive healthy** (e.g. the `is_error` was set by a software
484    ///   software-limit overshoot, an operation timeout, or a limit-switch
485    ///   close-out timeout — the drive itself is still in OperationEnabled):
486    ///   no CiA 402 handshake is needed. Just clears the software error
487    ///   flags and returns the axis to Idle synchronously. `is_busy` goes
488    ///   to false on the same call.
489    pub fn reset_faults(&mut self, view: &mut impl AxisView) {
490        let sw = RawStatusWord(view.status_word());
491        let drive_in_fault = matches!(
492            sw.state(),
493            Cia402State::Fault | Cia402State::FaultReactionActive
494        );
495
496        self.is_error = false;
497        self.error_code = 0;
498        self.error_message.clear();
499
500        if drive_in_fault {
501            // Step 0: clear bit 7 first (so next step produces a rising edge).
502            let mut cw = RawControlWord(view.control_word());
503            cw.cmd_clear_fault_reset();
504            view.set_control_word(cw.raw());
505            self.op = AxisOp::FaultRecovery(1);
506            self.op_started = Some(Instant::now());
507        } else {
508            // Software-only error — no drive handshake needed.
509            self.op = AxisOp::Idle;
510            self.op_started = None;
511            self.is_busy = false;
512            self.in_motion = false;
513        }
514    }
515
516    /// Start a homing sequence with the given homing method.
517    ///
518    /// **Integrated** methods delegate to the drive's built-in CiA 402
519    /// homing mode (SDO writes + homing trigger).
520    ///
521    /// **Software** methods are implemented by the Axis, which monitors
522    /// [`AxisView`] sensor signals for edge triggers and captures home.
523    pub fn home(&mut self, view: &mut impl AxisView, method: HomingMethod) {
524        if method.is_integrated() {
525            self.homing_method = match method {
526                HomingMethod::CurrentPosition => self.config.soft_home_method,
527                _ => method.cia402_code(),
528            };
529            self.op = AxisOp::Homing(0);
530            self.op_started = Some(Instant::now());
531            let _ = view;
532        } else {
533            self.configure_soft_homing(method);
534            self.start_soft_homing(view);
535        }
536    }
537
538    // ═══════════════════════════════════════════
539    // Position management
540    // ═══════════════════════════════════════════
541
542    /// Set the current position to the given user-unit value.
543    ///
544    /// Adjusts the internal home offset so that the current raw position
545    /// maps to `user_units`. Does not move the motor.
546    pub fn set_position(&mut self, view: &impl AxisView, user_units: f64) {
547        self.home_offset = view.position_actual() - self.config.to_counts(user_units).round() as i32;
548    }
549
550    /// Set the current position to `user_units` and persist it to the drive.
551    ///
552    /// Writes `0x607C` (home offset) to the drive in encoder counts, then runs
553    /// a CiA 402 homing cycle with method [`AxisConfig::soft_home_method`] so
554    /// the drive's reported position (`0x6064`) reads `user_units` afterward.
555    /// No motor motion occurs.
556    ///
557    /// For drives with absolute encoders configured in linear mode (e.g.
558    /// Inovance SV660N with `0x2002:02 = 1`), the resulting encoder offset
559    /// (`0x2005:2F`/`0x2005:31`) is auto-saved to EEPROM, so the new reference
560    /// survives a power cycle.
561    ///
562    /// **Preconditions:** drive must be enabled (OperationEnabled) and at rest
563    /// (no move in progress). The operation switches to HM mode internally and
564    /// back to PP on completion. Poll [`is_busy`](Self::is_busy) to know when
565    /// it finishes.
566    pub fn set_position_persistent(
567        &mut self,
568        client: &mut CommandClient,
569        user_units: f64,
570    ) {
571        // Reuse the SoftHoming state machine starting from the post-607C-write
572        // step (WaitHomeOffsetDone). We issue the 607C SDO write here; the
573        // state machine handles the rest: wait for ack, switch to HM, write
574        // 6098 = soft_home_method, trigger homing, wait for completion, switch
575        // back to PP, and zero the software home_offset since the drive owns
576        // it now.
577        self.config.home_position = user_units;
578        let desired_counts = self.config.to_counts(user_units).round() as i32;
579        self.homing_sdo_tid = self.sdo.write(client, 0x607C, 0, json!(desired_counts));
580        self.op = AxisOp::SoftHoming(HomeState::WaitHomeOffsetDone as u8);
581        self.op_started = Some(Instant::now());
582        log::info!(
583            "set_position_persistent: writing 0x607C = {} counts ({} user units)",
584            desired_counts, user_units
585        );
586    }
587
588    /// Set the home position in user units. This value is used by the next
589    /// `home()` call to set the axis position at the reference point.
590    /// Can be called at any time before homing.
591    pub fn set_home_position(&mut self, user_units: f64) {
592        self.config.home_position = user_units;
593    }
594
595    /// Set the maximum (positive) software position limit.
596    pub fn set_software_max_limit(&mut self, user_units: f64) {
597        self.config.max_position_limit = user_units;
598        self.config.enable_max_position_limit = true;
599    }
600
601    /// Set the minimum (negative) software position limit.
602    pub fn set_software_min_limit(&mut self, user_units: f64) {
603        self.config.min_position_limit = user_units;
604        self.config.enable_min_position_limit = true;
605    }
606
607    // ═══════════════════════════════════════════
608    // SDO pass-through
609    // ═══════════════════════════════════════════
610
611    /// Write an SDO value to the drive.
612    pub fn sdo_write(
613        &mut self,
614        client: &mut CommandClient,
615        index: u16,
616        sub_index: u8,
617        value: serde_json::Value,
618    ) {
619        self.sdo.write(client, index, sub_index, value);
620    }
621
622    /// Start an SDO read from the drive. Returns a transaction ID.
623    pub fn sdo_read(
624        &mut self,
625        client: &mut CommandClient,
626        index: u16,
627        sub_index: u8,
628    ) -> u32 {
629        self.sdo.read(client, index, sub_index)
630    }
631
632    /// Check the result of a previous SDO read.
633    pub fn sdo_result(
634        &mut self,
635        client: &mut CommandClient,
636        tid: u32,
637    ) -> SdoResult {
638        self.sdo.result(client, tid, Duration::from_secs(5))
639    }
640
641    // ═══════════════════════════════════════════
642    // Tick — call every control cycle
643    // ═══════════════════════════════════════════
644
645    /// Update outputs and progress the current operation.
646    ///
647    /// Must be called every control cycle. Does three things:
648    /// 1. Checks for drive faults
649    /// 2. Progresses the current multi-tick operation
650    /// 3. Updates output fields (position, velocity, status)
651    ///
652    /// Outputs are updated last so they reflect the final state after
653    /// all processing for this tick.
654    pub fn tick(&mut self, view: &mut impl AxisView, client: &mut CommandClient) {
655        self.check_faults(view);
656        self.progress_op(view, client);
657        self.update_outputs(view);
658        self.check_limits(view);
659    }
660
661    // ═══════════════════════════════════════════
662    // Internal: output update
663    // ═══════════════════════════════════════════
664
665    fn update_outputs(&mut self, view: &impl AxisView) {
666        let raw = view.position_actual();
667        self.raw_position = raw as i64;
668        self.position = self.config.to_user((raw - self.home_offset) as f64);
669
670        let vel = view.velocity_actual();
671        let user_vel = self.config.to_user(vel as f64);
672        self.speed = user_vel.abs();
673        self.moving_positive = user_vel > 0.0;
674        self.moving_negative = user_vel < 0.0;
675        self.is_busy = self.op != AxisOp::Idle;
676        self.in_motion = matches!(self.op, AxisOp::Moving(_, _, _, _) | AxisOp::SoftHoming(_));
677
678        let sw = RawStatusWord(view.status_word());
679        self.motor_on = sw.state() == Cia402State::OperationEnabled;
680
681        self.last_raw_position = raw;
682    }
683
684    // ═══════════════════════════════════════════
685    // Internal: fault check
686    // ═══════════════════════════════════════════
687
688    fn check_faults(&mut self, view: &impl AxisView) {
689        let sw = RawStatusWord(view.status_word());
690        let state = sw.state();
691
692        if matches!(state, Cia402State::Fault | Cia402State::FaultReactionActive) {
693            if !matches!(self.op, AxisOp::FaultRecovery(_)) {
694                self.is_error = true;
695                let ec = view.error_code();
696                if ec != 0 {
697                    self.error_code = ec as u32;
698                }
699                self.error_message = format!("Drive fault (state: {})", state);
700                // Cancel the current operation so is_busy goes false
701                self.op = AxisOp::Idle;
702                self.op_started = None;
703            }
704        }
705    }
706
707    // ═══════════════════════════════════════════
708    // Internal: operation timeout helper
709    // ═══════════════════════════════════════════
710
711    fn op_timed_out(&self) -> bool {
712        self.op_started
713            .map_or(false, |t| t.elapsed() > self.op_timeout)
714    }
715
716    fn homing_timed_out(&self) -> bool {
717        self.op_started
718            .map_or(false, |t| t.elapsed() > self.homing_timeout)
719    }
720
721    fn move_start_timed_out(&self) -> bool {
722        self.op_started
723            .map_or(false, |t| t.elapsed() > self.move_start_timeout)
724    }
725
726    /// Has the current operation exceeded the supplied stage timeout?
727    /// Used by the halt state machine so each sub-stage gets its own
728    /// budget rather than sharing the general `op_timeout`.
729    fn op_stage_timed_out(&self, limit: Duration) -> bool {
730        self.op_started
731            .map_or(false, |t| t.elapsed() > limit)
732    }
733
734    fn set_op_error(&mut self, msg: &str) {
735        self.is_error = true;
736        self.error_message = msg.to_string();
737        self.op = AxisOp::Idle;
738        self.op_started = None;
739        self.is_busy = false;
740        self.in_motion = false;
741        log::error!("Axis error: {}", msg);
742    }
743
744    fn restore_pp_after_error(&mut self, msg: &str) {
745        self.is_error = true;
746        self.error_message = msg.to_string();
747        self.op = AxisOp::SoftHoming(HomeState::WriteMotionModeOfOperation as u8);;
748        log::error!("Axis error: {}", msg);
749    }
750
751    fn finish_op_error(&mut self) {
752        self.op = AxisOp::Idle;
753        self.op_started = None;
754        self.is_busy = false;
755        self.in_motion = false;
756    }
757
758    fn complete_op(&mut self) {
759        self.op = AxisOp::Idle;
760        self.op_started = None;
761        // Clear busy/motion flags directly so callers that observe state on
762        // the same tick (e.g. check_limits, which runs after update_outputs)
763        // see Idle immediately. For complete_op calls inside progress_op,
764        // update_outputs would recompute these to the same values anyway.
765        self.is_busy = false;
766        self.in_motion = false;
767    }
768
769    // ═══════════════════════════════════════════
770    // Internal: position limits and limit switches
771    // ═══════════════════════════════════════════
772
773    /// Resolve the effective maximum software limit for this tick, combining
774    /// the static [`AxisConfig`] value (if enabled) with any dynamic limit
775    /// supplied by the [`AxisView`] (e.g. a GM-linked variable). The most
776    /// restrictive (smallest) value wins.
777    fn effective_max_limit(&self, view: &impl AxisView) -> Option<f64> {
778        let static_limit = if self.config.enable_max_position_limit {
779            Some(self.config.max_position_limit)
780        } else {
781            None
782        };
783        match (static_limit, view.dynamic_max_position_limit()) {
784            (Some(s), Some(d)) => Some(s.min(d)),
785            (Some(v), None) | (None, Some(v)) => Some(v),
786            (None, None) => None,
787        }
788    }
789
790    /// Resolve the effective minimum software limit for this tick. See
791    /// [`effective_max_limit`](Self::effective_max_limit) — the most
792    /// restrictive (largest) value wins.
793    fn effective_min_limit(&self, view: &impl AxisView) -> Option<f64> {
794        let static_limit = if self.config.enable_min_position_limit {
795            Some(self.config.min_position_limit)
796        } else {
797            None
798        };
799        match (static_limit, view.dynamic_min_position_limit()) {
800            (Some(s), Some(d)) => Some(s.max(d)),
801            (Some(v), None) | (None, Some(v)) => Some(v),
802            (None, None) => None,
803        }
804    }
805
806    /// Check whether a target position (in user units) exceeds a software limit.
807    /// Returns `Some(error_message)` if the target is out of range, `None` if OK.
808    /// Consults both the static [`AxisConfig`] limits and any dynamic limits
809    /// exposed by the view, taking whichever is most restrictive.
810    fn check_target_limit(&self, target: f64, view: &impl AxisView) -> Option<String> {
811        if let Some(max) = self.effective_max_limit(view) {
812            if target > max {
813                return Some(format!(
814                    "Target {:.3} exceeds max software limit {:.3}",
815                    target, max
816                ));
817            }
818        }
819        if let Some(min) = self.effective_min_limit(view) {
820            if target < min {
821                return Some(format!(
822                    "Target {:.3} exceeds min software limit {:.3}",
823                    target, min
824                ));
825            }
826        }
827        None
828    }
829
830    /// Check software position limits, hardware limit switches, and home sensor.
831    /// If a limit is violated and a move is in progress in that direction,
832    /// halt the drive and set an error. Moving in the opposite direction is
833    /// always allowed so the axis can be recovered.
834    ///
835    /// During software homing on a limit switch (`SoftHoming` + `SoftHomeSensor::PositiveLimit`
836    /// or `NegativeLimit`), the homed-on switch is suppressed so it triggers a home
837    /// event rather than an error halt. The opposite switch still protects.
838    fn check_limits(&mut self, view: &mut impl AxisView) {
839        // ── Software position limits (static config + dynamic GM-linked) ──
840        let eff_max = self.effective_max_limit(view);
841        let eff_min = self.effective_min_limit(view);
842        let sw_max = eff_max.map_or(false, |m| self.position >= m);
843        let sw_min = eff_min.map_or(false, |m| self.position <= m);
844
845        self.at_max_limit = sw_max;
846        self.at_min_limit = sw_min;
847
848        // ── Hardware limit switches ──
849        let hw_pos = view.positive_limit_active();
850        let hw_neg = view.negative_limit_active();
851
852        self.at_positive_limit_switch = hw_pos;
853        self.at_negative_limit_switch = hw_neg;
854
855        // ── Home sensor ──
856        self.home_sensor = view.home_sensor_active();
857
858        // ── Save previous sensor state for next tick's edge detection ──
859        self.prev_positive_limit = hw_pos;
860        self.prev_negative_limit = hw_neg;
861        self.prev_home_sensor = view.home_sensor_active();
862
863        // ── Halt logic (only while moving or soft-homing) ──
864        let mut commanded_positive = false;
865        let mut commanded_negative = false;
866
867        let is_moving = matches!(self.op, AxisOp::Moving(_, _, _, _));
868        let is_soft_homing = matches!(self.op, AxisOp::SoftHoming(_));
869
870        if !is_moving && !is_soft_homing {
871            return; // Only halt actively if we are currently driving into the limit
872        }
873
874        match &self.op {
875            AxisOp::Moving(_, _, pos, neg) => {
876                // Already user-frame (set by move_absolute / move_relative).
877                commanded_positive = *pos;
878                commanded_negative = *neg;
879            }
880            AxisOp::SoftHoming(_) => {
881                match self.soft_home_sensor {
882                    SoftHomeSensor::PositiveLimit => commanded_positive = true,
883                    SoftHomeSensor::NegativeLimit => commanded_negative = true,
884                    SoftHomeSensor::HomeSensor => {
885                        commanded_positive = self.moving_positive;
886                        commanded_negative = self.moving_negative;
887                    }
888                }
889            }
890            _ => {}
891        }
892
893        // During software homing, suppress the limit switch being homed on
894        let suppress_pos = is_soft_homing && self.soft_home_sensor == SoftHomeSensor::PositiveLimit;
895        let suppress_neg = is_soft_homing && self.soft_home_sensor == SoftHomeSensor::NegativeLimit;
896
897        let effective_hw_pos = hw_pos && !suppress_pos;
898        let effective_hw_neg = hw_neg && !suppress_neg;
899
900        // During soft homing, suppress software limits too (we need to move freely)
901        let effective_sw_max = sw_max && !is_soft_homing;
902        let effective_sw_min = sw_min && !is_soft_homing;
903
904        let positive_blocked = (effective_sw_max || effective_hw_pos) && commanded_positive;
905        let negative_blocked = (effective_sw_min || effective_hw_neg) && commanded_negative;
906
907
908        if positive_blocked || negative_blocked {
909            let mut cw = RawControlWord(view.control_word());
910            cw.set_bit(8, true); // halt
911            view.set_control_word(cw.raw());
912
913            let msg = if effective_hw_pos && commanded_positive {
914                "Positive limit switch active".to_string()
915            } else if effective_hw_neg && commanded_negative {
916                "Negative limit switch active".to_string()
917            } else if effective_sw_max && commanded_positive {
918                format!(
919                    "Software position limit: position {:.3} >= max {:.3}",
920                    self.position, eff_max.unwrap_or(self.position)
921                )
922            } else {
923                format!(
924                    "Software position limit: position {:.3} <= min {:.3}",
925                    self.position, eff_min.unwrap_or(self.position)
926                )
927            };
928
929            if is_soft_homing {
930                // Hitting the *opposite* limit during soft homing is a real
931                // fault — the axis went the wrong way and must be reset.
932                self.set_op_error(&msg);
933            } else {
934                // Regular move into a limit: enter the multi-stage Halting
935                // close-out (wait for motor stop → cancel queued setpoint →
936                // clear halt) so the drive ends in a clean state. Just
937                // clearing halt isn't enough — the previous move's target is
938                // still queued in the drive's PP buffer, and on the next
939                // start_move some drives ignore the new setpoint until that
940                // queued one is canceled.
941                //
942                // is_busy stays true through the close-out. Callers detect
943                // why the move ended by inspecting
944                // `at_positive_limit_switch` / `at_negative_limit_switch` /
945                // `at_max_limit` / `at_min_limit` once `!is_busy()`.
946                log::info!("Axis move halted by limit: {}", msg);
947                self.command_halt(view);
948                self.halt_stable_count = 0;
949                self.last_raw_position = view.position_actual();
950                self.op_started = Some(Instant::now());
951                self.op = AxisOp::Halting(HaltState::WaitStopped as u8);
952            }
953        }
954    }
955
956    // ═══════════════════════════════════════════
957    // Internal: operation progress
958    // ═══════════════════════════════════════════
959
960    fn progress_op(&mut self, view: &mut impl AxisView, client: &mut CommandClient) {
961        match self.op.clone() {
962            AxisOp::Idle => {}
963            AxisOp::Enabling(step) => self.tick_enabling(view, step),
964            AxisOp::Disabling(step) => self.tick_disabling(view, step),
965            AxisOp::Moving(kind, step, pos, neg) => self.tick_moving(view, kind, step, pos, neg),
966            AxisOp::Homing(step) => self.tick_homing(view, client, step),
967            AxisOp::SoftHoming(step) => self.tick_soft_homing(view, client, step),
968            AxisOp::Halting(step) => self.tick_halting(view, step),
969            AxisOp::FaultRecovery(step) => self.tick_fault_recovery(view, step),
970        }
971    }
972
973    // ── Enabling ──
974    // Step 0: (done in enable()) ensure PP + cmd_shutdown
975    // Step 1: wait ReadyToSwitchOn → cmd_enable_operation
976    // Step 2: wait OperationEnabled → capture home → Idle
977    fn tick_enabling(&mut self, view: &mut impl AxisView, step: u8) {
978        match step {
979            1 => {
980                let sw = RawStatusWord(view.status_word());
981                if sw.state() == Cia402State::ReadyToSwitchOn {
982                    let mut cw = RawControlWord(view.control_word());
983                    cw.cmd_enable_operation();
984                    view.set_control_word(cw.raw());
985                    self.op = AxisOp::Enabling(2);
986                } else if self.op_timed_out() {
987                    self.set_op_error("Enable timeout: waiting for ReadyToSwitchOn");
988                }
989            }
990            2 => {
991                let sw = RawStatusWord(view.status_word());
992                if sw.state() == Cia402State::OperationEnabled {
993                    // NO - We do not do software-based encoder. That would break absolute encoders.
994                    // self.home_offset = view.position_actual();
995                    // log::info!("Axis enabled — home captured at {}", self.home_offset);
996
997                    // Possible TODO: Read the home_offset in the drive? 
998
999                    self.complete_op();
1000                } else if self.op_timed_out() {
1001                    self.set_op_error("Enable timeout: waiting for OperationEnabled");
1002                }
1003            }
1004            _ => self.complete_op(),
1005        }
1006    }
1007
1008    // ── Disabling ──
1009    // Step 0: (done in disable()) cmd_disable_operation
1010    // Step 1: wait not OperationEnabled → Idle
1011    fn tick_disabling(&mut self, view: &mut impl AxisView, step: u8) {
1012        match step {
1013            1 => {
1014                let sw = RawStatusWord(view.status_word());
1015                if sw.state() != Cia402State::OperationEnabled {
1016                    self.complete_op();
1017                } else if self.op_timed_out() {
1018                    self.set_op_error("Disable timeout: drive still in OperationEnabled");
1019                }
1020            }
1021            _ => self.complete_op(),
1022        }
1023    }
1024
1025    // ── Moving ──
1026    // Step 0: (done in move_absolute/relative()) set params + trigger
1027    // Step 1: wait set_point_acknowledge → ack
1028    // Step 2: wait ack cleared (one tick)
1029    // Step 3: wait target_reached → Idle
1030    fn tick_moving(&mut self, view: &mut impl AxisView, kind: MoveKind, step: u8, pos: bool, neg: bool) {
1031        match step {
1032            1 => {
1033                // Wait for set-point acknowledge (bit 12)
1034                let sw = RawStatusWord(view.status_word());
1035                if sw.raw() & (1 << 12) != 0 {
1036                    // Ack: clear new set-point (bit 4)
1037                    let mut cw = RawControlWord(view.control_word());
1038                    cw.set_bit(4, false);
1039                    view.set_control_word(cw.raw());
1040                    self.op = AxisOp::Moving(kind, 2, pos, neg);
1041                } else if self.move_start_timed_out() {
1042                    self.set_op_error("Move timeout: set-point not acknowledged");
1043                }
1044            },
1045            2 => {
1046                // Wait for the drive to confirm it saw Bit 4 go low
1047                let sw = RawStatusWord(view.status_word());
1048                if sw.raw() & (1 << 12) == 0 {
1049                    // Handshake is officially reset. Now wait for physics.
1050                    self.op = AxisOp::Moving(kind, 3, pos, neg);
1051                }
1052            },
1053            3 => {
1054                // Wait for target reached (bit 10) — no timeout, moves can take arbitrarily long
1055                let sw = RawStatusWord(view.status_word());
1056                if sw.target_reached() {
1057                    self.complete_op();
1058                }
1059            },
1060            _ => self.complete_op(),
1061        }
1062    }
1063
1064    // ── Homing (hardware-delegated) ──
1065    // Step 0:  write homing method SDO (0x6098:0)
1066    // Step 1:  wait SDO ack
1067    // Step 2:  write homing speed SDO (0x6099:1 — search for switch)
1068    // Step 3:  wait SDO ack
1069    // Step 4:  write homing speed SDO (0x6099:2 — search for zero)
1070    // Step 5:  wait SDO ack
1071    // Step 6:  write homing accel SDO (0x609A:0)
1072    // Step 7:  wait SDO ack
1073    // Step 8:  set homing mode
1074    // Step 9:  wait mode confirmed
1075    // Step 10: trigger homing (bit 4)
1076    // Step 11: wait homing complete (bits 10+12 set, 13 clear)
1077    // Step 12: capture home offset, switch to PP → Idle
1078    //
1079    // If homing_speed and homing_accel are both 0, steps 2-7 are skipped
1080    // (preserves backward compatibility for users who pre-configure via SDO).
1081    fn tick_homing(
1082        &mut self,
1083        view: &mut impl AxisView,
1084        client: &mut CommandClient,
1085        step: u8,
1086    ) {
1087        match step {
1088            0 => {
1089                // Write homing method via SDO (0x6098:0)
1090                self.homing_sdo_tid = self.sdo.write(
1091                    client,
1092                    0x6098,
1093                    0,
1094                    json!(self.homing_method),
1095                );
1096                self.op = AxisOp::Homing(1);
1097            }
1098            1 => {
1099                // Wait for SDO write ack
1100                match self.sdo.result(client, self.homing_sdo_tid, Duration::from_secs(5)) {
1101                    SdoResult::Ok(_) => {
1102                        // Skip speed/accel SDOs if both are zero
1103                        if self.config.homing_speed == 0.0 && self.config.homing_accel == 0.0 {
1104                            self.op = AxisOp::Homing(8);
1105                        } else {
1106                            self.op = AxisOp::Homing(2);
1107                        }
1108                    }
1109                    SdoResult::Pending => {
1110                        if self.homing_timed_out() {
1111                            self.set_op_error("Homing timeout: SDO write for homing method");
1112                        }
1113                    }
1114                    SdoResult::Err(e) => {
1115                        self.set_op_error(&format!("Homing SDO error: {}", e));
1116                    }
1117                    SdoResult::Timeout => {
1118                        self.set_op_error("Homing timeout: SDO write timed out");
1119                    }
1120                }
1121            }
1122            2 => {
1123                // Write homing speed (0x6099:1 — search for switch)
1124                let speed_counts = self.config.to_counts(self.config.homing_speed).round() as u32;
1125                self.homing_sdo_tid = self.sdo.write(
1126                    client,
1127                    0x6099,
1128                    1,
1129                    json!(speed_counts),
1130                );
1131                self.op = AxisOp::Homing(3);
1132            }
1133            3 => {
1134                match self.sdo.result(client, self.homing_sdo_tid, Duration::from_secs(5)) {
1135                    SdoResult::Ok(_) => { self.op = AxisOp::Homing(4); }
1136                    SdoResult::Pending => {
1137                        if self.homing_timed_out() {
1138                            self.set_op_error("Homing timeout: SDO write for homing speed (switch)");
1139                        }
1140                    }
1141                    SdoResult::Err(e) => { self.set_op_error(&format!("Homing SDO error: {}", e)); }
1142                    SdoResult::Timeout => { self.set_op_error("Homing timeout: SDO write timed out"); }
1143                }
1144            }
1145            4 => {
1146                // Write homing speed (0x6099:2 — search for zero, same value)
1147                let speed_counts = self.config.to_counts(self.config.homing_speed).round() as u32;
1148                self.homing_sdo_tid = self.sdo.write(
1149                    client,
1150                    0x6099,
1151                    2,
1152                    json!(speed_counts),
1153                );
1154                self.op = AxisOp::Homing(5);
1155            }
1156            5 => {
1157                match self.sdo.result(client, self.homing_sdo_tid, Duration::from_secs(5)) {
1158                    SdoResult::Ok(_) => { self.op = AxisOp::Homing(6); }
1159                    SdoResult::Pending => {
1160                        if self.homing_timed_out() {
1161                            self.set_op_error("Homing timeout: SDO write for homing speed (zero)");
1162                        }
1163                    }
1164                    SdoResult::Err(e) => { self.set_op_error(&format!("Homing SDO error: {}", e)); }
1165                    SdoResult::Timeout => { self.set_op_error("Homing timeout: SDO write timed out"); }
1166                }
1167            }
1168            6 => {
1169                // Write homing acceleration (0x609A:0)
1170                let accel_counts = self.config.to_counts(self.config.homing_accel).round() as u32;
1171                self.homing_sdo_tid = self.sdo.write(
1172                    client,
1173                    0x609A,
1174                    0,
1175                    json!(accel_counts),
1176                );
1177                self.op = AxisOp::Homing(7);
1178            }
1179            7 => {
1180                match self.sdo.result(client, self.homing_sdo_tid, Duration::from_secs(5)) {
1181                    SdoResult::Ok(_) => { self.op = AxisOp::Homing(8); }
1182                    SdoResult::Pending => {
1183                        if self.homing_timed_out() {
1184                            self.set_op_error("Homing timeout: SDO write for homing acceleration");
1185                        }
1186                    }
1187                    SdoResult::Err(e) => { self.set_op_error(&format!("Homing SDO error: {}", e)); }
1188                    SdoResult::Timeout => { self.set_op_error("Homing timeout: SDO write timed out"); }
1189                }
1190            }
1191            8 => {
1192                // Set homing mode and ensure CW bit 4 starts LOW so the next
1193                // step can issue a clean rising edge.
1194                view.set_modes_of_operation(ModesOfOperation::Homing.as_i8());
1195                let mut cw = RawControlWord(view.control_word());
1196                cw.set_bit(4, false);
1197                view.set_control_word(cw.raw());
1198                self.op = AxisOp::Homing(9);
1199            }
1200            9 => {
1201                // Wait for mode confirmed
1202                if view.modes_of_operation_display() == ModesOfOperation::Homing.as_i8() {
1203                    self.op = AxisOp::Homing(10);
1204                } else if self.homing_timed_out() {
1205                    self.set_op_error("Homing timeout: mode not confirmed");
1206                }
1207            }
1208            10 => {
1209                // Trigger homing: rising edge on bit 4
1210                let mut cw = RawControlWord(view.control_word());
1211                cw.set_bit(4, true);
1212                view.set_control_word(cw.raw());
1213                self.op = AxisOp::Homing(11);
1214            }
1215            11 => {
1216                // Wait for the drive to clear bit 12 to acknowledge the start
1217                // of homing. Without this, stale bit 12 from the previous mode
1218                // (e.g. PP set-point acknowledge) would let the next step pass
1219                // instantly even though the drive never ran the method.
1220                let sw = view.status_word();
1221                let error = sw & (1 << 13) != 0;
1222                if error {
1223                    self.set_op_error("Homing error: drive reported homing failure");
1224                } else if sw & (1 << 12) == 0 {
1225                    self.op = AxisOp::Homing(12);
1226                } else if self.homing_timed_out() {
1227                    self.set_op_error(&format!("Homing timeout: drive did not acknowledge homing start (sw=0x{:04X})", sw));
1228                }
1229            }
1230            12 => {
1231                // Wait for homing complete
1232                // Bit 13 = error, Bit 12 = attained, Bit 10 = reached
1233                let sw = view.status_word();
1234                let error    = sw & (1 << 13) != 0;
1235                let attained = sw & (1 << 12) != 0;
1236                let reached  = sw & (1 << 10) != 0;
1237
1238                if error {
1239                    self.set_op_error("Homing error: drive reported homing failure");
1240                } else if attained && reached {
1241                    self.op = AxisOp::Homing(13);
1242                } else if self.homing_timed_out() {
1243                    self.set_op_error("Homing timeout: procedure did not complete");
1244                }
1245            }
1246            13 => {
1247                // Capture home offset, applying home_position so the reference
1248                // point reads as config.home_position in user units.
1249                self.home_offset = view.position_actual()
1250                    - self.config.to_counts(self.config.home_position).round() as i32;
1251                // Clear homing start bit in its own cycle before switching modes
1252                let mut cw = RawControlWord(view.control_word());
1253                cw.set_bit(4, false);
1254                view.set_control_word(cw.raw());
1255                self.op = AxisOp::Homing(14);
1256            }
1257            14 => {
1258                // One tick later, switch back to PP mode so the drive sees the
1259                // bit 4 falling edge before the mode change.
1260                view.set_modes_of_operation(ModesOfOperation::ProfilePosition.as_i8());
1261                log::info!("Homing complete — home offset: {}", self.home_offset);
1262                self.complete_op();
1263            }
1264            _ => self.complete_op(),
1265        }
1266    }
1267
1268    // ── Software homing helpers ──
1269
1270    fn configure_soft_homing(&mut self, method: HomingMethod) {
1271        match method {
1272            HomingMethod::LimitSwitchPosPnp => {
1273                self.soft_home_sensor = SoftHomeSensor::PositiveLimit;
1274                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
1275                self.soft_home_direction = 1.0;
1276            }
1277            HomingMethod::LimitSwitchNegPnp => {
1278                self.soft_home_sensor = SoftHomeSensor::NegativeLimit;
1279                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
1280                self.soft_home_direction = -1.0;
1281            }
1282            HomingMethod::LimitSwitchPosNpn => {
1283                self.soft_home_sensor = SoftHomeSensor::PositiveLimit;
1284                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
1285                self.soft_home_direction = 1.0;
1286            }
1287            HomingMethod::LimitSwitchNegNpn => {
1288                self.soft_home_sensor = SoftHomeSensor::NegativeLimit;
1289                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
1290                self.soft_home_direction = -1.0;
1291            }
1292            HomingMethod::HomeSensorPosPnp => {
1293                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
1294                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
1295                self.soft_home_direction = 1.0;
1296            }
1297            HomingMethod::HomeSensorNegPnp => {
1298                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
1299                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
1300                self.soft_home_direction = -1.0;
1301            }
1302            HomingMethod::HomeSensorPosNpn => {
1303                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
1304                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
1305                self.soft_home_direction = 1.0;
1306            }
1307            HomingMethod::HomeSensorNegNpn => {
1308                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
1309                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
1310                self.soft_home_direction = -1.0;
1311            }
1312            _ => {} // integrated methods handled elsewhere
1313        }
1314    }
1315
1316    fn start_soft_homing(&mut self, view: &mut impl AxisView) {
1317        self.op = AxisOp::SoftHoming(HomeState::EnsurePpMode as u8);
1318        self.op_started = Some(Instant::now());
1319    }
1320
1321    fn check_soft_home_trigger(&self, view: &impl AxisView) -> bool {
1322        let raw = match self.soft_home_sensor {
1323            SoftHomeSensor::PositiveLimit => view.positive_limit_active(),
1324            SoftHomeSensor::NegativeLimit => view.negative_limit_active(),
1325            SoftHomeSensor::HomeSensor    => view.home_sensor_active(),
1326        };
1327        match self.soft_home_sensor_type {
1328            SoftHomeSensorType::Pnp => raw,    // PNP: true = detected
1329            SoftHomeSensorType::Npn => !raw,   // NPN: false = detected
1330        }
1331    }
1332
1333
1334    /// Calculate the maximum relative target for the specified direction.
1335    /// The result is adjusted for whether the motor direction has been inverted.
1336    fn calculate_max_relative_target(&self, direction : f64) -> i32 {
1337        let dir = if !self.config.invert_direction  {
1338            direction
1339        } 
1340        else {
1341            -direction
1342        };
1343
1344        let target = if dir > 0.0 {
1345            i32::MAX 
1346        }
1347        else {
1348            i32::MIN
1349        };
1350
1351        return target;
1352    }
1353
1354
1355    /// Convenient macro
1356    /// Configure the command word for an immediate halt
1357    /// and reset the new setpoint bit, which should cause
1358    /// status word bit 12 to clear
1359    pub fn command_halt(&self, view: &mut impl AxisView) {
1360        let mut cw = RawControlWord(view.control_word());
1361        cw.set_bit(8, true);  // halt
1362        cw.set_bit(4, false);  // reset new setpoint bit
1363        cw.set_bit(5, true);  // single set-point. If false, the new move will be queued!
1364        cw.set_bit(6, false); // absolute move
1365        view.set_control_word(cw.raw());        
1366    }
1367
1368    /// Convenient macro
1369    /// Configure the command word to clear the halt bit
1370    pub fn command_clear_halt(&self, view: &mut impl AxisView) {
1371        let mut cw = RawControlWord(view.control_word());
1372        cw.set_bit(8, false);  // reset halt
1373        view.set_control_word(cw.raw());        
1374    }
1375
1376
1377    /// Convenient macro.
1378    /// Configures command bits and targets to cancel a previous move.
1379    /// Bit 4 should be off before calling this function.
1380    /// The current absolute position will be used as the target, so there 
1381    /// should be no motion
1382    /// Halt will be turned on, if not already.]
1383    /// After this, wait for bit 12 to be true before clearing the halt bit.
1384    pub fn command_cancel_move(&self, view: &mut impl AxisView) {
1385
1386        let mut cw = RawControlWord(view.control_word());
1387
1388        cw.set_bit(4, true);  // new set-point
1389        cw.set_bit(5, true);  // single set-point. If false, the new move will be queued!
1390        cw.set_bit(6, false); // absolute move
1391
1392        // Doesn't work with Teknic!
1393        // cw.set_bit(8, false); // clear halt
1394        
1395        view.set_control_word(cw.raw());        
1396
1397        let current_pos = view.position_actual();
1398        view.set_target_position(current_pos);
1399        view.set_profile_velocity(0);
1400    }
1401
1402
1403    /// Writes out the scaled homing speed into the bus.
1404    fn command_homing_speed(&self, view: &mut impl AxisView) {
1405        let cpu = self.config.counts_per_user();
1406        let vel = (self.config.homing_speed * cpu).round() as u32;
1407        let accel = (self.config.homing_accel * cpu).round() as u32;
1408        let decel = (self.config.homing_decel * cpu).round() as u32;
1409        view.set_profile_velocity(vel);
1410        view.set_profile_acceleration(accel);
1411        view.set_profile_deceleration(decel);        
1412    }
1413
1414    // ── Software homing state machine ──
1415    //
1416    // Phase 1: SEARCH (steps 0-3)
1417    //   Relative move in search direction until sensor triggers.
1418    //
1419    // Phase 2: HALT (steps 4-6)
1420    //   Stop the motor, cancel the old target.
1421    //
1422    // Phase 3: BACK-OFF (steps 7-11)
1423    //   Move opposite direction until sensor clears, then stop.
1424    //
1425    // Phase 4: SET HOME (steps 12-18)
1426    //   Write home offset to drive via SDO, trigger CurrentPosition homing,
1427    //   send hold set-point, complete.
1428    //
1429    fn tick_soft_homing(&mut self, view: &mut impl AxisView, client: &mut CommandClient, step: u8) {        
1430        match HomeState::from_repr(step) {
1431
1432            Some(HomeState::EnsurePpMode) => {
1433                //
1434                // If the drive crapped out in a previous mode, it might still be in homing mode.
1435                // Make sure we're in Profile Position mode.
1436                //
1437                log::info!("SoftHome: Ensuring PP mode..");
1438                self.fb_mode_of_operation.start(ModesOfOperation::ProfilePosition as i8);
1439                self.fb_mode_of_operation.tick(client, &mut self.sdo);
1440                self.op = AxisOp::SoftHoming(HomeState::WaitPpMode as u8);
1441            },
1442            Some(HomeState::WaitPpMode) => {
1443
1444                self.fb_mode_of_operation.tick(client, &mut self.sdo);
1445                if !self.fb_mode_of_operation.is_busy() {
1446                    if self.fb_mode_of_operation.is_error() {
1447                        self.set_op_error(&format!("Software homing SDO error writing homing mode of operation: {} {}", 
1448                            self.fb_mode_of_operation.error_code(), self.fb_mode_of_operation.error_message()
1449                        ));
1450                    }
1451                    else {
1452                        log::info!("SoftHome: Drive is in PP mode!");
1453
1454                        // If sensor is NOT triggered, search for it (issue a move).
1455                        // If sensor IS already triggered, skip search and go straight
1456                        // to the found-sensor halt/back-off sequence.
1457                        if !self.check_soft_home_trigger(view) {
1458                            log::info!("SoftHome: Not on home switch; seek out.");
1459                            self.op = AxisOp::SoftHoming(HomeState::Search as u8);
1460                        } else {
1461                            log::info!("SoftHome: Already on home switch, skipping ahead to back-off stage.");
1462                            self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);
1463                        }
1464                    }
1465                }
1466
1467
1468            },
1469
1470            // ── Phase 1: SEARCH ──
1471            Some(HomeState::Search) => {
1472                view.set_modes_of_operation(ModesOfOperation::ProfilePosition.as_i8());
1473
1474                // // Absolute move to a far-away position in the search direction.
1475                // // Use raw counts directly to avoid overflow with invert_direction.                
1476                // let far_counts = (self.soft_home_direction * 999_999.0 * cpu).round() as i32;
1477                // let target = if self.config.invert_direction { -far_counts } else { far_counts };
1478                // let target = target + view.position_actual(); // offset from current
1479
1480
1481                // move in a relative direction as far as possible
1482                // we will stop when we reach the switch
1483                let target = self.calculate_max_relative_target(self.soft_home_direction);
1484                view.set_target_position(target);
1485
1486                // let cpu = self.config.counts_per_user();
1487                // let vel = (self.config.homing_speed * cpu).round() as u32;
1488                // let accel = (self.config.homing_accel * cpu).round() as u32;
1489                // let decel = (self.config.homing_decel * cpu).round() as u32;
1490                // view.set_profile_velocity(vel);
1491                // view.set_profile_acceleration(accel);
1492                // view.set_profile_deceleration(decel);
1493
1494                self.command_homing_speed(view);
1495
1496                let mut cw = RawControlWord(view.control_word());
1497                cw.set_bit(4, true);  // new set-point
1498                cw.set_bit(6, true); // sets true for relative move
1499                cw.set_bit(8, false); // clear halt
1500                cw.set_bit(13, true); // move relative to the actual current motor position
1501                view.set_control_word(cw.raw());
1502
1503                log::info!("SoftHome[0]: SEARCH relative target={} vel={} dir={} pos={}",
1504                    target, self.config.homing_speed, self.soft_home_direction, view.position_actual());
1505                self.op = AxisOp::SoftHoming(HomeState::WaitSearching as u8);
1506            }
1507            Some(HomeState::WaitSearching) => {
1508                if self.check_soft_home_trigger(view) {
1509                    log::debug!("SoftHome[1]: sensor triggered during ack wait");
1510                    self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);
1511                    return;
1512                }
1513                let sw = RawStatusWord(view.status_word());
1514                if sw.raw() & (1 << 12) != 0 {
1515                    let mut cw = RawControlWord(view.control_word());
1516                    cw.set_bit(4, false);
1517                    view.set_control_word(cw.raw());
1518                    log::debug!("SoftHome[1]: set-point ack received, clearing bit 4");
1519                    self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);
1520                } else if self.homing_timed_out() {
1521                    self.set_op_error("Software homing timeout: set-point not acknowledged");
1522                }
1523            }
1524            // Some(HomeState::WaitSensor) => {
1525            //     if self.check_soft_home_trigger(view) {
1526            //         log::debug!("SoftHome[2]: sensor triggered during transition");
1527            //         self.op = AxisOp::SoftHoming(4);
1528            //         return;
1529            //     }
1530            //     log::debug!("SoftHome[2]: transition → monitoring");
1531            //     self.op = AxisOp::SoftHoming(3);
1532            // }
1533            Some(HomeState::WaitFoundSensor) => {
1534                if self.check_soft_home_trigger(view) {
1535                    log::info!("SoftHome[3]: sensor triggered at pos={}. HALTING", view.position_actual());
1536                    log::info!("ControlWord is : {} ", view.control_word());
1537
1538                    let mut cw = RawControlWord(view.control_word());
1539                    cw.set_bit(8, true);  // halt
1540                    cw.set_bit(4, false);  // reset new setpoint bit
1541                    view.set_control_word(cw.raw());
1542
1543
1544                    self.halt_stable_count = 0;
1545                    self.op = AxisOp::SoftHoming(HomeState::WaitStoppedFoundSensor as u8);
1546                } else if self.homing_timed_out() {
1547                    self.set_op_error("Software homing timeout: sensor not detected");
1548                }
1549            }
1550
1551
1552            Some(HomeState::WaitStoppedFoundSensor) => {
1553                const STABLE_WINDOW: i32 = 1;
1554                const STABLE_TICKS_REQUIRED: u8 = 10;
1555
1556                // let mut cw = RawControlWord(view.control_word());
1557                // cw.set_bit(8, true);
1558                // view.set_control_word(cw.raw());
1559
1560                let pos = view.position_actual();
1561                if (pos - self.last_raw_position).abs() <= STABLE_WINDOW {
1562                    self.halt_stable_count = self.halt_stable_count.saturating_add(1);
1563                } else {
1564                    self.halt_stable_count = 0;
1565                }
1566
1567                if self.halt_stable_count >= STABLE_TICKS_REQUIRED {
1568
1569                    log::info!("SoftHome[5] motor is stopped. Cancel move and wait for bit 12 go true.");
1570                    self.command_cancel_move(view);
1571                    self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensorAck as u8);
1572
1573                } else if self.homing_timed_out() {
1574                    self.set_op_error("Software homing timeout: motor did not stop after sensor trigger");
1575                }
1576            }
1577            Some(HomeState::WaitFoundSensorAck) => {
1578                let sw = RawStatusWord(view.status_word());
1579                if sw.raw() & (1 << 12) != 0 &&  sw.raw() & (1 << 10) != 0 {
1580
1581                    log::info!("SoftHome[6]: relative move cancel ack received. Waiting before back-off...");
1582
1583                    // reset bit 4 so we're clear for the next move
1584                    let mut cw = RawControlWord(view.control_word());
1585                    cw.set_bit(4, false);  // reset new setpoint bit
1586                    cw.set_bit(5, true); // single setpoint -- flush out any previous
1587                    view.set_control_word(cw.raw());
1588
1589                    self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensorAckClear as u8);
1590
1591                } else if self.homing_timed_out() {
1592                    self.set_op_error("Software homing timeout: cancel not acknowledged");
1593                }
1594            },
1595            Some(HomeState::WaitFoundSensorAckClear) => {
1596                let sw = RawStatusWord(view.status_word());
1597                // CRITICAL: Wait for the drive to acknowledge that the setpoint is gone
1598                if sw.raw() & (1 << 12) == 0 { 
1599
1600                    // turn off halt and it still shouldn't move
1601                    self.command_clear_halt(view);
1602
1603                    log::info!("SoftHome[6]: Handshake cleared (Bit 12 is LOW). Proceeding to delay.");
1604                    self.op = AxisOp::SoftHoming(HomeState::DebounceFoundSensor as u8);
1605                    self.ton.call(false, Duration::from_secs(3));
1606                }                   
1607            },
1608            // Delay before back-off (60 = wait ~1 second for drive to settle)
1609            Some(HomeState::DebounceFoundSensor) => {
1610                self.ton.call(true, Duration::from_secs(3));
1611
1612                let sw = RawStatusWord(view.status_word());
1613                if self.ton.q && sw.raw() & (1 << 12) == 0 { 
1614                    self.ton.call(false, Duration::from_secs(3));
1615                    log::info!("SoftHome[6.a.]: delay complete, starting back-off from pos={} cw=0x{:04X} sw={:04x}",
1616                    view.position_actual(), view.control_word(), view.status_word());
1617                    self.op = AxisOp::SoftHoming(HomeState::BackOff as u8);
1618                }
1619            }
1620
1621            // ── Phase 3: BACK-OFF until sensor clears ──
1622            Some(HomeState::BackOff) => {
1623
1624                let target = (self.calculate_max_relative_target(-self.soft_home_direction)) / 2;
1625                view.set_target_position(target);
1626
1627
1628                self.command_homing_speed(view);            
1629
1630                let mut cw = RawControlWord(view.control_word());
1631                cw.set_bit(4, true);  // new set-point                
1632                cw.set_bit(6, true); // relative move                
1633                cw.set_bit(13, true); // relative from current, actualy position
1634                view.set_control_word(cw.raw());
1635                log::info!("SoftHome[7]: BACK-OFF absolute target={} vel={} pos={} cw=0x{:04X}",
1636                    target, self.config.homing_speed, view.position_actual(), cw.raw());
1637                self.op = AxisOp::SoftHoming(HomeState::WaitBackingOff as u8);
1638            }
1639            Some(HomeState::WaitBackingOff) => {
1640                let sw = RawStatusWord(view.status_word());
1641                if sw.raw() & (1 << 12) != 0 {
1642                    let mut cw = RawControlWord(view.control_word());
1643                    cw.set_bit(4, false);
1644                    view.set_control_word(cw.raw());
1645                    log::info!("SoftHome[WaitBackingOff]: back-off ack received, pos={}", view.position_actual());
1646                    self.op = AxisOp::SoftHoming(HomeState::WaitLostSensor as u8);
1647                } else if self.homing_timed_out() {
1648                    self.set_op_error("Software homing timeout: back-off not acknowledged");
1649                }
1650            }
1651            Some(HomeState::WaitLostSensor) => {
1652                if !self.check_soft_home_trigger(view) {
1653                    log::info!("SoftHome[WaitLostSensor]: sensor lost at pos={}. Halting...", view.position_actual());
1654
1655                    self.command_halt(view);
1656                    self.op = AxisOp::SoftHoming(HomeState::WaitStoppedLostSensor as u8);
1657                } else if self.homing_timed_out() {
1658                    self.set_op_error("Software homing timeout: sensor did not clear during back-off");
1659                }
1660            }
1661            Some(HomeState::WaitStoppedLostSensor)  => {
1662                const STABLE_WINDOW: i32 = 1;
1663                const STABLE_TICKS_REQUIRED: u8 = 10;
1664
1665                // let mut cw = RawControlWord(view.control_word());
1666                // cw.set_bit(8, true);
1667                // view.set_control_word(cw.raw());
1668
1669                let pos = view.position_actual();
1670                if (pos - self.last_raw_position).abs() <= STABLE_WINDOW {
1671                    self.halt_stable_count = self.halt_stable_count.saturating_add(1);
1672                } else {
1673                    self.halt_stable_count = 0;
1674                }
1675
1676                if self.halt_stable_count >= STABLE_TICKS_REQUIRED {
1677                    log::info!("SoftHome[WaitStoppedLostSensor] motor is stopped. Cancel move and wait for bit 12 go true.");
1678                    self.command_cancel_move(view);
1679                    self.op = AxisOp::SoftHoming(HomeState::WaitLostSensorAck as u8);
1680                } else if self.homing_timed_out() {
1681                    self.set_op_error("Software homing timeout: motor did not stop after back-off");
1682                }
1683            }
1684            Some(HomeState::WaitLostSensorAck) => {
1685                let sw = RawStatusWord(view.status_word());
1686                if sw.raw() & (1 << 12) != 0 &&  sw.raw() & (1 << 10) != 0 {
1687
1688                    log::info!("SoftHome[WaitLostSensorAck]: relative move cancel ack received. Waiting before back-off...");
1689
1690                    // reset bit 4 so we're clear for the next move
1691                    let mut cw = RawControlWord(view.control_word());
1692                    cw.set_bit(4, false);  // reset new setpoint bit
1693                    view.set_control_word(cw.raw());
1694
1695                     self.op = AxisOp::SoftHoming(HomeState::WaitLostSensorAckClear as u8);
1696
1697
1698                } else if self.homing_timed_out() {
1699                    self.set_op_error("Software homing timeout: cancel not acknowledged");
1700                }
1701            }
1702            Some(HomeState::WaitLostSensorAckClear) => {
1703                // CRITICAL: Wait for the drive to acknowledge that the setpoint is gone
1704                let sw = RawStatusWord(view.status_word());
1705                if sw.raw() & (1 << 12) == 0 { 
1706
1707                    self.command_clear_halt(view);
1708
1709                    let desired_counts = self.config.to_counts(self.config.home_position).round() as i32;
1710                    // let current_pos = view.position_actual();
1711                    // let offset = desired_counts - current_pos;
1712                    self.homing_sdo_tid = self.sdo.write(
1713                        client, 0x607C, 0, json!(desired_counts),
1714                    );
1715
1716                    log::info!("SoftHome[WaitLostSensorAckClear]: Handshake cleared (Bit 12 is LOW). Writing home offset {} [{} counts].",
1717                        self.config.home_position, desired_counts
1718                    );
1719
1720                    self.op = AxisOp::SoftHoming(HomeState::WaitHomeOffsetDone as u8);
1721
1722                }                
1723            },
1724
1725            Some(HomeState::WaitHomeOffsetDone) => {
1726                // Wait for home offset SDO ack
1727                match self.sdo.result(client, self.homing_sdo_tid, Duration::from_secs(5)) {
1728                    SdoResult::Ok(_) => { self.op = AxisOp::SoftHoming(HomeState::WriteHomingModeOp as u8); }
1729                    SdoResult::Pending => {
1730                        if self.homing_timed_out() {
1731                            self.set_op_error("Software homing timeout: home offset SDO write");
1732                        }
1733                    }
1734                    SdoResult::Err(e) => {
1735                        self.set_op_error(&format!("Software homing SDO error: {}", e));
1736                    }
1737                    SdoResult::Timeout => {
1738                        self.set_op_error("Software homing: home offset SDO timed out");
1739                    }
1740                }
1741            },            
1742            Some(HomeState::WriteHomingModeOp) => {
1743
1744                // Switch the mode of operation into Homing Mode so that we can execute
1745                // the homing command.
1746
1747                self.fb_mode_of_operation.reset();
1748                self.fb_mode_of_operation.start(ModesOfOperation::Homing as i8);
1749                self.fb_mode_of_operation.tick(client, &mut self.sdo);
1750                self.op = AxisOp::SoftHoming(HomeState::WaitWriteHomingModeOp as u8);
1751
1752                
1753            },       
1754            Some(HomeState::WaitWriteHomingModeOp) => {
1755                // Wait for method SDO ack
1756                self.fb_mode_of_operation.tick(client, &mut self.sdo);
1757
1758                if !self.fb_mode_of_operation.is_busy() {
1759                    if self.fb_mode_of_operation.is_error() {
1760                        self.set_op_error(&format!("Software homing SDO error writing homing mode of operation: {} {}", 
1761                            self.fb_mode_of_operation.error_code(), self.fb_mode_of_operation.error_message()
1762                        ));
1763                    }
1764                    else {
1765                        log::info!("SoftHome: Drive is now in Homing Mode.");
1766                        self.op = AxisOp::SoftHoming(HomeState::WriteHomingMethod as u8);
1767                    }
1768                }
1769            },
1770            Some(HomeState::WriteHomingMethod) => {
1771                // Write homing method = CurrentPosition (default 37, configurable
1772                // via AxisConfig::soft_home_method — Inovance SV660N needs 35).
1773                self.homing_sdo_tid = self.sdo.write(
1774                    client, 0x6098, 0, json!(self.config.soft_home_method),
1775                );
1776                self.op = AxisOp::SoftHoming(HomeState::WaitWriteHomingMethodDone as u8);
1777            }
1778            Some(HomeState::WaitWriteHomingMethodDone) => {
1779                // Wait for method SDO ack
1780                match self.sdo.result(client, self.homing_sdo_tid, Duration::from_secs(5)) {
1781                    SdoResult::Ok(_) => { 
1782                        log::info!("SoftHome: Successfully wrote homing method.");
1783                        self.op = AxisOp::SoftHoming(HomeState::ClearHomingTrigger as u8); 
1784                    }
1785                    SdoResult::Pending => {
1786                        if self.homing_timed_out() {
1787                            self.restore_pp_after_error("Software homing timeout: homing method SDO write");
1788                        }
1789                    }
1790                    SdoResult::Err(e) => {
1791                        self.restore_pp_after_error(&format!("Software homing SDO error: {}", e));
1792                    }
1793                    SdoResult::Timeout => {
1794                        self.restore_pp_after_error("Software homing: homing method SDO timed out");
1795                    }
1796                }
1797            }
1798            Some(HomeState::ClearHomingTrigger) => {
1799                // Switch to homing mode and ensure CW bit 4 starts LOW, so the
1800                // next state can issue a clean rising edge the drive will see.
1801                let mut cw = RawControlWord(view.control_word());
1802                cw.set_bit(4, false);
1803                view.set_control_word(cw.raw());
1804                self.op = AxisOp::SoftHoming(HomeState::TriggerHoming as u8);
1805            }
1806            Some(HomeState::TriggerHoming) => {
1807                // Rising edge on CW bit 4 to start homing.
1808                let mut cw = RawControlWord(view.control_word());
1809                cw.set_bit(4, true);
1810                view.set_control_word(cw.raw());
1811                log::info!("SoftHome[TriggerHoming]: start homing");
1812                self.op = AxisOp::SoftHoming(HomeState::WaitHomingStarted as u8);
1813            }
1814            Some(HomeState::WaitHomingStarted) => {
1815                // Wait for the drive to clear bit 12 (Homing attained) to acknowledge
1816                // the start of homing. Without this handshake, stale bit 12 carried
1817                // over from the previous mode (e.g. PP set-point acknowledge) would
1818                // cause WaitHomingDone to pass instantly, and the drive would never
1819                // actually perform the homing method.
1820                let sw = view.status_word();
1821                let error = sw & (1 << 13) != 0;
1822                if error {
1823                    self.restore_pp_after_error("Software homing: drive reported homing error");
1824                } else if sw & (1 << 12) == 0 {
1825                    self.op = AxisOp::SoftHoming(HomeState::WaitHomingDone as u8);
1826                } else if self.homing_timed_out() {
1827                    self.restore_pp_after_error(&format!("Software homing timeout: drive did not acknowledge homing start (sw=0x{:04X})", sw));
1828                }
1829            }
1830            Some(HomeState::WaitHomingDone) => {
1831                // Wait for homing complete (bit 12 attained + bit 10 reached).
1832                let sw = view.status_word();
1833                let error    = sw & (1 << 13) != 0;
1834                let attained = sw & (1 << 12) != 0;
1835                let reached  = sw & (1 << 10) != 0;
1836
1837                if error {
1838                    self.restore_pp_after_error("Software homing: drive reported homing error");
1839                } else if attained && reached {
1840                    log::info!("SoftHome[WaitHomingDone]: homing complete (sw=0x{:04X})", sw);
1841                    self.op = AxisOp::SoftHoming(HomeState::ResetHomingTrigger as u8);
1842                } else if self.homing_timed_out() {
1843                    self.restore_pp_after_error(&format!("Software homing timeout: drive homing did not complete (sw=0x{:04X} attained={} reached={})", sw, attained, reached));
1844                }
1845            }
1846            Some(HomeState::ResetHomingTrigger) => {
1847                // Clear CW bit 4 first, in its own RxPDO cycle, so the drive sees
1848                // the falling edge *before* we change modes_of_operation away from
1849                // Homing. Changing both at once can leave the drive committing
1850                // ambiguous state.
1851                let mut cw = RawControlWord(view.control_word());
1852                cw.set_bit(4, false);
1853                view.set_control_word(cw.raw());
1854                self.op = AxisOp::SoftHoming(HomeState::WaitHomingTriggerCleared as u8);
1855            }
1856            Some(HomeState::WaitHomingTriggerCleared) => {
1857                // One tick later, switch back to PP mode and record that the drive
1858                // now owns the offset so our software-side offset is zero.
1859                self.home_offset = 0; // drive handles it now
1860                self.op = AxisOp::SoftHoming(HomeState::WriteMotionModeOfOperation as u8);
1861            }
1862
1863
1864            Some(HomeState::WriteMotionModeOfOperation) => {
1865
1866                // Switch back to PP motion mode
1867
1868                self.fb_mode_of_operation.reset();
1869                self.fb_mode_of_operation.start(ModesOfOperation::ProfilePosition as i8);
1870                self.fb_mode_of_operation.tick(client, &mut self.sdo);
1871                self.op = AxisOp::SoftHoming(HomeState::WaitWriteMotionModeOfOperation  as u8);
1872                
1873            },       
1874            Some(HomeState::WaitWriteMotionModeOfOperation) => {
1875                // Wait for method SDO ack
1876                self.fb_mode_of_operation.tick(client, &mut self.sdo);
1877
1878                if !self.fb_mode_of_operation.is_busy() {
1879                    if self.fb_mode_of_operation.is_error() {
1880                        self.set_op_error(&format!("Software homing SDO error writing homing mode of operation: {} {}", 
1881                            self.fb_mode_of_operation.error_code(), self.fb_mode_of_operation.error_message()
1882                        ));
1883                    }
1884                    else {
1885                        if self.is_error {
1886                            log::error!("Drive back in PP mode after error. Homing sequence did not complete!");
1887                            self.finish_op_error();
1888                        }
1889                        else {
1890                            // Set the target position so this drive doesn't go wandering off after homing
1891                            // changed the position
1892                            self.op = AxisOp::SoftHoming(HomeState::SendCurrentPositionTarget as u8);
1893                        }
1894                        
1895                    }
1896                }
1897            },
1898
1899            Some(HomeState::SendCurrentPositionTarget) => {
1900                // Hold position: send set-point to current position
1901                let current_pos = view.position_actual();
1902                view.set_target_position(current_pos);
1903                view.set_profile_velocity(0);
1904                let mut cw = RawControlWord(view.control_word());
1905                cw.set_bit(4, true);
1906                cw.set_bit(5, true);
1907                cw.set_bit(6, false); // absolute
1908                view.set_control_word(cw.raw());
1909                self.op = AxisOp::SoftHoming(HomeState::WaitCurrentPositionTargetSent as u8);
1910            }
1911            Some(HomeState::WaitCurrentPositionTargetSent) => {
1912                // Wait for hold ack
1913                let sw = RawStatusWord(view.status_word());
1914                if sw.raw() & (1 << 12) != 0 {
1915                    let mut cw = RawControlWord(view.control_word());
1916                    cw.set_bit(4, false);
1917                    view.set_control_word(cw.raw());
1918                    log::info!("Software homing complete — position set to {} user units",
1919                        self.config.home_position);
1920                    self.complete_op();
1921                } else if self.homing_timed_out() {
1922                    self.set_op_error("Software homing timeout: hold position not acknowledged");
1923                }
1924            }
1925            _ => self.complete_op(),
1926        }
1927    }
1928
1929    // ── Halting ──
1930    //
1931    // Three-stage close-out of the PP handshake, mirroring the soft-home
1932    // stop sequence (WaitStoppedFoundSensor → WaitFoundSensorAck →
1933    // WaitFoundSensorAckClear). Leaving any stage out results in a dirty
1934    // handshake that makes the next `move_absolute` time out at
1935    // "set-point not acknowledged."
1936    //
1937    // Step 0: (done in halt()) command_halt — bit 8 set, bit 4 cleared.
1938    // Step 1: wait for position to be stable → command_cancel_move.
1939    // Step 2: wait for SW bit 12 AND bit 10 → clear bit 4, set bit 5.
1940    // Step 3: wait for SW bit 12 to drop → Idle.
1941    fn tick_halting(&mut self, view: &mut impl AxisView, step: u8) {
1942        match HaltState::from_repr(step) {
1943            Some(HaltState::WaitStopped) => {
1944                // `update_outputs` writes `last_raw_position` at the end
1945                // of the previous tick, so this compares delta across
1946                // exactly one scan period.
1947                let pos = view.position_actual();
1948                let pos_stable = (pos - self.last_raw_position).abs() <= HALT_STABLE_WINDOW;
1949
1950                let vel = view.velocity_actual().abs();
1951                let vel_stopped = vel <= HALT_STOPPED_VELOCITY;
1952
1953                // Either signal is sufficient — position jitter during
1954                // servo hold can exceed the window even when the drive
1955                // reports ~0 velocity, and vice versa on slow drives
1956                // that report stale velocity briefly.
1957                if pos_stable || vel_stopped {
1958                    self.halt_stable_count = self.halt_stable_count.saturating_add(1);
1959                } else {
1960                    self.halt_stable_count = 0;
1961                }
1962
1963                if self.halt_stable_count >= HALT_STABLE_TICKS_REQUIRED {
1964                    self.command_cancel_move(view);
1965                    self.op_started = Some(Instant::now());
1966                    self.op = AxisOp::Halting(HaltState::WaitCancelAck as u8);
1967                } else if self.op_stage_timed_out(HALT_STAGE_TIMEOUT) {
1968                    self.set_op_error("Halt timeout: motor did not stop");
1969                }
1970            }
1971            Some(HaltState::WaitCancelAck) => {
1972                let sw = RawStatusWord(view.status_word());
1973                let setpoint_ack   = sw.raw() & (1 << 12) != 0;
1974                // let target_reached = sw.raw() & (1 << 10) != 0;
1975                if setpoint_ack /* && target_reached */  {
1976                    // Reset the rising edge for the next move; bit 5 flushes
1977                    // any queued setpoint so we start clean.
1978                    let mut cw = RawControlWord(view.control_word());
1979                    cw.set_bit(4, false);
1980                    cw.set_bit(5, true);
1981                    view.set_control_word(cw.raw());
1982                    self.op_started = Some(Instant::now());
1983                    self.op = AxisOp::Halting(HaltState::WaitCancelAckClear as u8);
1984                } else if self.op_stage_timed_out(HALT_STAGE_TIMEOUT) {
1985                    self.set_op_error("Halt timeout: cancel not acknowledged");
1986                }
1987            }
1988            Some(HaltState::WaitCancelAckClear) => {
1989                let sw = RawStatusWord(view.status_word());
1990                if sw.raw() & (1 << 12) == 0 {
1991                    // setpoint_ack dropped — drive is ready for the next move.
1992                    self.command_clear_halt(view);                    
1993                    self.complete_op();
1994                } else if self.op_stage_timed_out(HALT_STAGE_TIMEOUT) {
1995                    self.set_op_error("Halt timeout: ack did not clear");
1996                }
1997            }
1998            None => {
1999                log::warn!("Axis halt: unknown sub-step {}, forcing idle", step);
2000                self.complete_op();
2001            }
2002        }
2003    }
2004
2005    // ── Fault Recovery ──
2006    // Step 0: (done in reset_faults()) clear bit 7
2007    // Step 1: assert bit 7 (fault reset rising edge)
2008    // Step 2: wait fault cleared → Idle
2009    fn tick_fault_recovery(&mut self, view: &mut impl AxisView, step: u8) {
2010        match step {
2011            1 => {
2012                // Assert fault reset (rising edge on bit 7)
2013                let mut cw = RawControlWord(view.control_word());
2014                cw.cmd_fault_reset();
2015                view.set_control_word(cw.raw());
2016                self.op = AxisOp::FaultRecovery(2);
2017            }
2018            2 => {
2019                // Wait for fault to clear
2020                let sw = RawStatusWord(view.status_word());
2021                let state = sw.state();
2022                if !matches!(state, Cia402State::Fault | Cia402State::FaultReactionActive) {
2023                    log::info!("Fault cleared (drive state: {})", state);
2024                    self.complete_op();
2025                } else if self.op_timed_out() {
2026                    self.set_op_error("Fault reset timeout: drive still faulted");
2027                }
2028            }
2029            _ => self.complete_op(),
2030        }
2031    }
2032}
2033
2034// ──────────────────────────────────────────────
2035// Tests
2036// ──────────────────────────────────────────────
2037
2038#[cfg(test)]
2039mod tests {
2040    use super::*;
2041
2042    /// Mock AxisView for testing.
2043    struct MockView {
2044        control_word: u16,
2045        status_word: u16,
2046        target_position: i32,
2047        profile_velocity: u32,
2048        profile_acceleration: u32,
2049        profile_deceleration: u32,
2050        modes_of_operation: i8,
2051        modes_of_operation_display: i8,
2052        position_actual: i32,
2053        velocity_actual: i32,
2054        error_code: u16,
2055        positive_limit: bool,
2056        negative_limit: bool,
2057        home_sensor: bool,
2058    }
2059
2060    impl MockView {
2061        fn new() -> Self {
2062            Self {
2063                control_word: 0,
2064                status_word: 0x0040, // SwitchOnDisabled
2065                target_position: 0,
2066                profile_velocity: 0,
2067                profile_acceleration: 0,
2068                profile_deceleration: 0,
2069                modes_of_operation: 0,
2070                modes_of_operation_display: 1, // PP
2071                position_actual: 0,
2072                velocity_actual: 0,
2073                error_code: 0,
2074                positive_limit: false,
2075                negative_limit: false,
2076                home_sensor: false,
2077            }
2078        }
2079
2080        fn set_state(&mut self, state: u16) {
2081            self.status_word = state;
2082        }
2083    }
2084
2085    impl AxisView for MockView {
2086        fn control_word(&self) -> u16 { self.control_word }
2087        fn set_control_word(&mut self, word: u16) { self.control_word = word; }
2088        fn set_target_position(&mut self, pos: i32) { self.target_position = pos; }
2089        fn set_profile_velocity(&mut self, vel: u32) { self.profile_velocity = vel; }
2090        fn set_profile_acceleration(&mut self, accel: u32) { self.profile_acceleration = accel; }
2091        fn set_profile_deceleration(&mut self, decel: u32) { self.profile_deceleration = decel; }
2092        fn set_modes_of_operation(&mut self, mode: i8) { self.modes_of_operation = mode; }
2093        fn modes_of_operation_display(&self) -> i8 { self.modes_of_operation_display }
2094        fn status_word(&self) -> u16 { self.status_word }
2095        fn position_actual(&self) -> i32 { self.position_actual }
2096        fn velocity_actual(&self) -> i32 { self.velocity_actual }
2097        fn error_code(&self) -> u16 { self.error_code }
2098        fn positive_limit_active(&self) -> bool { self.positive_limit }
2099        fn negative_limit_active(&self) -> bool { self.negative_limit }
2100        fn home_sensor_active(&self) -> bool { self.home_sensor }
2101    }
2102
2103    fn test_config() -> AxisConfig {
2104        AxisConfig::new(12_800).with_user_scale(360.0)
2105    }
2106
2107    /// Helper: create axis + mock client channels.
2108    fn test_axis() -> (Axis, CommandClient, tokio::sync::mpsc::UnboundedSender<mechutil::ipc::CommandMessage>, tokio::sync::mpsc::UnboundedReceiver<String>) {
2109        use tokio::sync::mpsc;
2110        let (write_tx, write_rx) = mpsc::unbounded_channel();
2111        let (response_tx, response_rx) = mpsc::unbounded_channel();
2112        let client = CommandClient::new(write_tx, response_rx);
2113        let axis = Axis::new(test_config(), "TestDrive");
2114        (axis, client, response_tx, write_rx)
2115    }
2116
2117    #[test]
2118    fn axis_config_conversion() {
2119        let cfg = test_config();
2120        // 45 degrees = 1600 counts
2121        assert!((cfg.to_counts(45.0) - 1600.0).abs() < 0.01);
2122    }
2123
2124    #[test]
2125    fn enable_sequence_sets_pp_mode_and_shutdown() {
2126        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2127        let mut view = MockView::new();
2128
2129        axis.enable(&mut view);
2130
2131        // Should have set PP mode
2132        assert_eq!(view.modes_of_operation, ModesOfOperation::ProfilePosition.as_i8());
2133        // Should have issued shutdown command (bits 1,2 set; 0,3,7 clear)
2134        assert_eq!(view.control_word & 0x008F, 0x0006);
2135        // Should be in Enabling state
2136        assert_eq!(axis.op, AxisOp::Enabling(1));
2137
2138        // Simulate drive reaching ReadyToSwitchOn
2139        view.set_state(0x0021); // ReadyToSwitchOn
2140        axis.tick(&mut view, &mut client);
2141
2142        // Should have issued enable_operation (bits 0-3 set; 7 clear)
2143        assert_eq!(view.control_word & 0x008F, 0x000F);
2144        assert_eq!(axis.op, AxisOp::Enabling(2));
2145
2146        // Simulate drive reaching OperationEnabled
2147        view.set_state(0x0027); // OperationEnabled
2148        axis.tick(&mut view, &mut client);
2149
2150        // Should be idle now, motor_on = true
2151        assert_eq!(axis.op, AxisOp::Idle);
2152        assert!(axis.motor_on);
2153    }
2154
2155    #[test]
2156    fn move_absolute_sets_target() {
2157        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2158        let mut view = MockView::new();
2159        view.set_state(0x0027); // OperationEnabled
2160        axis.tick(&mut view, &mut client); // update outputs
2161
2162        // Move to 45 degrees at 90 deg/s, 180 deg/s² accel/decel
2163        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2164
2165        // Target should be ~1600 counts (45° at 12800 cpr / 360°)
2166        assert_eq!(view.target_position, 1600);
2167        // Velocity: 90 deg/s * (12800/360) ≈ 3200 counts/s
2168        assert_eq!(view.profile_velocity, 3200);
2169        // Accel: 180 deg/s² * (12800/360) ≈ 6400 counts/s²
2170        assert_eq!(view.profile_acceleration, 6400);
2171        assert_eq!(view.profile_deceleration, 6400);
2172        // Bit 4 (new set-point) should be set
2173        assert!(view.control_word & (1 << 4) != 0);
2174        // Bit 6 (relative) should be clear for absolute move
2175        assert!(view.control_word & (1 << 6) == 0);
2176        // Should be in Moving state
2177        assert!(matches!(axis.op, AxisOp::Moving(MoveKind::Absolute, 1, _, _)));
2178    }
2179
2180    #[test]
2181    fn move_relative_sets_relative_bit() {
2182        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2183        let mut view = MockView::new();
2184        view.set_state(0x0027);
2185        axis.tick(&mut view, &mut client);
2186
2187        axis.move_relative(&mut view, 10.0, 90.0, 180.0, 180.0);
2188
2189        // Bit 6 (relative) should be set
2190        assert!(view.control_word & (1 << 6) != 0);
2191        assert!(matches!(axis.op, AxisOp::Moving(MoveKind::Relative, 1, _, _)));
2192    }
2193
2194    #[test]
2195    fn move_completes_on_target_reached() {
2196        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2197        let mut view = MockView::new();
2198        view.set_state(0x0027); // OperationEnabled
2199        axis.tick(&mut view, &mut client);
2200
2201        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2202
2203        // Step 1: simulate set-point acknowledge (bit 12)
2204        view.status_word = 0x1027; // OperationEnabled + bit 12
2205        axis.tick(&mut view, &mut client);
2206        // Should have cleared bit 4
2207        assert!(view.control_word & (1 << 4) == 0);
2208
2209        // Step 2: simulate target reached (bit 10)
2210        view.status_word = 0x0427; // OperationEnabled + bit 10
2211        axis.tick(&mut view, &mut client);
2212        // Should be idle now
2213        assert_eq!(axis.op, AxisOp::Idle);
2214        assert!(!axis.in_motion);
2215    }
2216
2217    #[test]
2218    fn fault_detected_sets_error() {
2219        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2220        let mut view = MockView::new();
2221        view.set_state(0x0008); // Fault
2222        view.error_code = 0x1234;
2223
2224        axis.tick(&mut view, &mut client);
2225
2226        assert!(axis.is_error);
2227        assert_eq!(axis.error_code, 0x1234);
2228        assert!(axis.error_message.contains("fault"));
2229    }
2230
2231    #[test]
2232    fn fault_recovery_sequence() {
2233        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2234        let mut view = MockView::new();
2235        view.set_state(0x0008); // Fault
2236
2237        axis.reset_faults(&mut view);
2238        // Step 0: bit 7 should be cleared
2239        assert!(view.control_word & 0x0080 == 0);
2240
2241        // Step 1: tick should assert bit 7
2242        axis.tick(&mut view, &mut client);
2243        assert!(view.control_word & 0x0080 != 0);
2244
2245        // Step 2: simulate fault cleared → SwitchOnDisabled
2246        view.set_state(0x0040);
2247        axis.tick(&mut view, &mut client);
2248        assert_eq!(axis.op, AxisOp::Idle);
2249        assert!(!axis.is_error);
2250    }
2251
2252    #[test]
2253    fn reset_faults_software_only_is_synchronous() {
2254        // When the axis hits a software error (e.g. target outside the
2255        // software limits) the drive stays in OperationEnabled — there is
2256        // no CiA 402 fault to clear. reset_faults() must return the axis
2257        // to Idle on the same call without engaging the drive's bit-7
2258        // fault-reset handshake.
2259        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2260        let mut view = MockView::new();
2261        view.set_state(0x0027); // OperationEnabled
2262        axis.tick(&mut view, &mut client);
2263
2264        // Trigger a software-only error via target outside software limit.
2265        axis.set_software_min_limit(207.0);
2266        axis.move_absolute(&mut view, 200.0, 90.0, 180.0, 180.0);
2267        assert!(axis.is_error, "move past software limit must set is_error");
2268        assert!(!axis.is_busy);
2269
2270        // Capture cw before reset. reset_faults must not modify it for
2271        // a software-only error (drive is healthy, no handshake needed).
2272        let cw_before = view.control_word;
2273
2274        axis.reset_faults(&mut view);
2275
2276        // Synchronous: error cleared, axis already Idle, not busy.
2277        assert!(!axis.is_error);
2278        assert_eq!(axis.error_code, 0);
2279        assert!(axis.error_message.is_empty());
2280        assert!(!axis.is_busy);
2281        assert_eq!(axis.op, AxisOp::Idle);
2282        // No drive handshake — control word untouched.
2283        assert_eq!(view.control_word, cw_before);
2284    }
2285
2286    #[test]
2287    fn disable_sequence() {
2288        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2289        let mut view = MockView::new();
2290        view.set_state(0x0027); // OperationEnabled
2291
2292        axis.disable(&mut view);
2293        // Should have sent disable_operation command
2294        assert_eq!(view.control_word & 0x008F, 0x0007);
2295
2296        // Simulate drive leaving OperationEnabled
2297        view.set_state(0x0023); // SwitchedOn
2298        axis.tick(&mut view, &mut client);
2299        assert_eq!(axis.op, AxisOp::Idle);
2300    }
2301
2302    #[test]
2303    fn position_tracks_with_home_offset() {
2304        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2305        let mut view = MockView::new();
2306        view.set_state(0x0027);
2307        view.position_actual = 5000;
2308
2309        // Enable to capture home offset
2310        axis.enable(&mut view);
2311        view.set_state(0x0021);
2312        axis.tick(&mut view, &mut client);
2313        view.set_state(0x0027);
2314        axis.tick(&mut view, &mut client);
2315
2316        // Home offset should be 5000
2317        assert_eq!(axis.home_offset, 5000);
2318
2319        // Position should be 0 (at home)
2320        assert!((axis.position - 0.0).abs() < 0.01);
2321
2322        // Move actual position to 5000 + 1600 = 6600
2323        view.position_actual = 6600;
2324        axis.tick(&mut view, &mut client);
2325
2326        // Should read as 45 degrees
2327        assert!((axis.position - 45.0).abs() < 0.1);
2328    }
2329
2330    #[test]
2331    fn set_position_adjusts_home_offset() {
2332        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2333        let mut view = MockView::new();
2334        view.position_actual = 3200;
2335
2336        axis.set_position(&view, 90.0);
2337        axis.tick(&mut view, &mut client);
2338
2339        // home_offset = 3200 - to_counts(90.0) = 3200 - 3200 = 0
2340        assert_eq!(axis.home_offset, 0);
2341        assert!((axis.position - 90.0).abs() < 0.01);
2342    }
2343
2344    #[test]
2345    fn halt_runs_multi_stage_close_out() {
2346        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2347        let mut view = MockView::new();
2348        view.set_state(0x0027);
2349
2350        axis.halt(&mut view);
2351
2352        // halt() sets CW bit 8 (halt) and clears CW bit 4 (new setpoint).
2353        assert!(view.control_word & (1 << 8) != 0, "halt bit must be set");
2354        assert!(view.control_word & (1 << 4) == 0, "new_setpoint must be cleared");
2355
2356        // Halt is a multi-stage process. The first stage is WaitStopped.
2357        assert!(matches!(axis.op, AxisOp::Halting(_)),
2358                "halt should enter Halting state, not Idle");
2359        let AxisOp::Halting(step) = axis.op.clone() else { unreachable!() };
2360        assert_eq!(step, HaltState::WaitStopped as u8);
2361
2362        // Tick alone does NOT immediately return to Idle anymore —
2363        // WaitStopped polls position stability (5 consecutive ticks
2364        // with position stable or velocity near zero). With a static
2365        // MockView, position stays at 0 and velocity stays at 0, so
2366        // vel_stopped is true every tick → the counter accumulates
2367        // and the state progresses after HALT_STABLE_TICKS_REQUIRED.
2368        for _ in 0..HALT_STABLE_TICKS_REQUIRED {
2369            axis.tick(&mut view, &mut client);
2370        }
2371        // After enough stable ticks we advance to WaitCancelAck.
2372        assert!(matches!(axis.op, AxisOp::Halting(_)));
2373        let AxisOp::Halting(step) = axis.op.clone() else { unreachable!() };
2374        assert_eq!(step, HaltState::WaitCancelAck as u8,
2375                   "should advance past WaitStopped once position/velocity is stable");
2376
2377        // axis.is_busy must remain true through the whole halt sequence so
2378        // callers like MoveToLoad don't see "stopped" until the PP state
2379        // is fully cleaned up.
2380        assert!(axis.is_busy, "is_busy must stay true across Halting stages");
2381    }
2382
2383    #[test]
2384    fn is_busy_tracks_operations() {
2385        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2386        let mut view = MockView::new();
2387
2388        // Idle — not busy
2389        axis.tick(&mut view, &mut client);
2390        assert!(!axis.is_busy);
2391
2392        // Enable — busy
2393        axis.enable(&mut view);
2394        axis.tick(&mut view, &mut client);
2395        assert!(axis.is_busy);
2396
2397        // Complete enable
2398        view.set_state(0x0021);
2399        axis.tick(&mut view, &mut client);
2400        view.set_state(0x0027);
2401        axis.tick(&mut view, &mut client);
2402        assert!(!axis.is_busy);
2403
2404        // Move — busy
2405        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2406        axis.tick(&mut view, &mut client);
2407        assert!(axis.is_busy);
2408        assert!(axis.in_motion);
2409    }
2410
2411    #[test]
2412    fn fault_during_move_cancels_op() {
2413        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2414        let mut view = MockView::new();
2415        view.set_state(0x0027); // OperationEnabled
2416        axis.tick(&mut view, &mut client);
2417
2418        // Start a move
2419        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2420        axis.tick(&mut view, &mut client);
2421        assert!(axis.is_busy);
2422        assert!(!axis.is_error);
2423
2424        // Fault occurs mid-move
2425        view.set_state(0x0008); // Fault
2426        axis.tick(&mut view, &mut client);
2427
2428        // is_busy should be false, is_error should be true
2429        assert!(!axis.is_busy);
2430        assert!(axis.is_error);
2431        assert_eq!(axis.op, AxisOp::Idle);
2432    }
2433
2434    #[test]
2435    fn move_absolute_rejected_by_max_limit() {
2436        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2437        let mut view = MockView::new();
2438        view.set_state(0x0027);
2439        axis.tick(&mut view, &mut client);
2440
2441        axis.set_software_max_limit(90.0);
2442        axis.move_absolute(&mut view, 100.0, 90.0, 180.0, 180.0);
2443
2444        // Should not have started a move — error instead
2445        assert!(axis.is_error);
2446        assert_eq!(axis.op, AxisOp::Idle);
2447        assert!(axis.error_message.contains("max software limit"));
2448    }
2449
2450    #[test]
2451    fn move_absolute_rejected_by_min_limit() {
2452        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2453        let mut view = MockView::new();
2454        view.set_state(0x0027);
2455        axis.tick(&mut view, &mut client);
2456
2457        axis.set_software_min_limit(-10.0);
2458        axis.move_absolute(&mut view, -20.0, 90.0, 180.0, 180.0);
2459
2460        assert!(axis.is_error);
2461        assert_eq!(axis.op, AxisOp::Idle);
2462        assert!(axis.error_message.contains("min software limit"));
2463    }
2464
2465    #[test]
2466    fn move_relative_rejected_by_max_limit() {
2467        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2468        let mut view = MockView::new();
2469        view.set_state(0x0027);
2470        axis.tick(&mut view, &mut client);
2471
2472        // Position is 0, max limit 50 — relative move of +60 should be rejected
2473        axis.set_software_max_limit(50.0);
2474        axis.move_relative(&mut view, 60.0, 90.0, 180.0, 180.0);
2475
2476        assert!(axis.is_error);
2477        assert_eq!(axis.op, AxisOp::Idle);
2478        assert!(axis.error_message.contains("max software limit"));
2479    }
2480
2481    #[test]
2482    fn move_within_limits_allowed() {
2483        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2484        let mut view = MockView::new();
2485        view.set_state(0x0027);
2486        axis.tick(&mut view, &mut client);
2487
2488        axis.set_software_max_limit(90.0);
2489        axis.set_software_min_limit(-90.0);
2490        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2491
2492        // Should have started normally
2493        assert!(!axis.is_error);
2494        assert!(matches!(axis.op, AxisOp::Moving(MoveKind::Absolute, 1, _, _)));
2495    }
2496
2497    #[test]
2498    fn runtime_limit_halts_move_in_violated_direction() {
2499        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2500        let mut view = MockView::new();
2501        view.set_state(0x0027);
2502        axis.tick(&mut view, &mut client);
2503
2504        axis.set_software_max_limit(45.0);
2505        // Start a move to exactly the limit (allowed)
2506        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2507
2508        // Simulate the drive overshooting past 45° (position_actual in counts)
2509        // home_offset is 0, so 1650 counts = 46.4°
2510        view.position_actual = 1650;
2511        view.velocity_actual = 100; // moving positive
2512
2513        // Simulate set-point ack so we're in Moving step 2
2514        view.status_word = 0x1027;
2515        axis.tick(&mut view, &mut client);
2516        view.status_word = 0x0027;
2517        axis.tick(&mut view, &mut client);
2518
2519        // Should have halted cleanly without error. The axis enters the
2520        // Halting close-out (caller waits for !is_busy then checks
2521        // at_max_limit).
2522        assert!(!axis.is_error);
2523        assert!(axis.at_max_limit);
2524        assert!(axis.is_busy);
2525        assert!(matches!(axis.op, AxisOp::Halting(_)));
2526        // Halt bit (bit 8) should be set
2527        assert!(view.control_word & (1 << 8) != 0);
2528    }
2529
2530    #[test]
2531    fn runtime_limit_allows_move_in_opposite_direction() {
2532        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2533        let mut view = MockView::new();
2534        view.set_state(0x0027);
2535        // Start at 50° (past max limit)
2536        view.position_actual = 1778; // ~50°
2537        axis.set_software_max_limit(45.0);
2538        axis.tick(&mut view, &mut client);
2539        assert!(axis.at_max_limit);
2540
2541        // Move back toward 0 — should be allowed even though at max limit
2542        axis.move_absolute(&mut view, 0.0, 90.0, 180.0, 180.0);
2543        assert!(!axis.is_error);
2544        assert!(matches!(axis.op, AxisOp::Moving(MoveKind::Absolute, 1, _, _)));
2545
2546        // Simulate moving negative — limit check should not halt
2547        view.velocity_actual = -100;
2548        view.status_word = 0x1027; // ack
2549        axis.tick(&mut view, &mut client);
2550        // Still moving, no error from limit
2551        assert!(!axis.is_error);
2552    }
2553
2554    #[test]
2555    fn positive_limit_switch_halts_positive_move() {
2556        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2557        let mut view = MockView::new();
2558        view.set_state(0x0027);
2559        axis.tick(&mut view, &mut client);
2560
2561        // Start a move in the positive direction
2562        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2563        view.velocity_actual = 100; // moving positive
2564        // Simulate set-point ack so we're in Moving step 2
2565        view.status_word = 0x1027;
2566        axis.tick(&mut view, &mut client);
2567        view.status_word = 0x0027;
2568
2569        // Now the positive limit switch trips
2570        view.positive_limit = true;
2571        axis.tick(&mut view, &mut client);
2572
2573        // Limit hit during a regular move enters the Halting close-out:
2574        // no error, halt bit asserted, drive's queued setpoint will be
2575        // canceled and halt cleared before the axis returns to Idle.
2576        // Caller waits for !is_busy then inspects at_positive_limit_switch.
2577        assert!(!axis.is_error);
2578        assert!(axis.at_positive_limit_switch);
2579        assert!(axis.is_busy);
2580        assert!(matches!(axis.op, AxisOp::Halting(_)));
2581        // Halt bit should be set
2582        assert!(view.control_word & (1 << 8) != 0);
2583    }
2584
2585    #[test]
2586    fn negative_limit_switch_halts_negative_move() {
2587        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2588        let mut view = MockView::new();
2589        view.set_state(0x0027);
2590        axis.tick(&mut view, &mut client);
2591
2592        // Start a move in the negative direction
2593        axis.move_absolute(&mut view, -45.0, 90.0, 180.0, 180.0);
2594        view.velocity_actual = -100; // moving negative
2595        view.status_word = 0x1027;
2596        axis.tick(&mut view, &mut client);
2597        view.status_word = 0x0027;
2598
2599        // Negative limit switch trips
2600        view.negative_limit = true;
2601        axis.tick(&mut view, &mut client);
2602
2603        // Limit hit during a regular move enters the Halting close-out:
2604        // no error, halt bit asserted, drive's queued setpoint will be
2605        // canceled and halt cleared before the axis returns to Idle.
2606        // Caller waits for !is_busy then inspects at_negative_limit_switch.
2607        assert!(!axis.is_error);
2608        assert!(axis.at_negative_limit_switch);
2609        assert!(axis.is_busy);
2610        assert!(matches!(axis.op, AxisOp::Halting(_)));
2611        assert!(view.control_word & (1 << 8) != 0);
2612    }
2613
2614    #[test]
2615    fn limit_halt_cleanup_then_next_move_starts_cleanly() {
2616        // After a limit-switch halt, the axis must run the full Halting
2617        // close-out (motor stop → cancel queued setpoint → clear halt) so
2618        // the drive ends in a clean state. The next move then starts via
2619        // the normal one-tick start_move path.
2620        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2621        let mut view = MockView::new();
2622        view.set_state(0x0027); // OperationEnabled
2623        axis.tick(&mut view, &mut client);
2624
2625        // Drive an initial move into a positive limit.
2626        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
2627        view.velocity_actual = 100;
2628        view.status_word = 0x1027;
2629        axis.tick(&mut view, &mut client);
2630        view.status_word = 0x0027;
2631        view.positive_limit = true;
2632        axis.tick(&mut view, &mut client);
2633
2634        // Limit halt: in Halting close-out, halt asserted, busy, no error.
2635        assert!(!axis.is_error);
2636        assert!(axis.is_busy);
2637        assert!(matches!(axis.op, AxisOp::Halting(_)));
2638        assert!(view.control_word & (1 << 8) != 0);
2639
2640        // Drive the close-out to completion. WaitStopped polls position
2641        // stability; with static MockView (vel=0 after we clear it), it
2642        // accumulates HALT_STABLE_TICKS_REQUIRED and advances to
2643        // WaitCancelAck.
2644        view.velocity_actual = 0;
2645        view.positive_limit = false;
2646        for _ in 0..HALT_STABLE_TICKS_REQUIRED {
2647            axis.tick(&mut view, &mut client);
2648        }
2649        assert!(matches!(axis.op, AxisOp::Halting(_)));
2650        let AxisOp::Halting(step) = axis.op.clone() else { unreachable!() };
2651        assert_eq!(step, HaltState::WaitCancelAck as u8);
2652
2653        // WaitCancelAck: drive acks the cancel. We mock by setting bit 12.
2654        view.status_word = 0x1027;
2655        axis.tick(&mut view, &mut client);
2656        let AxisOp::Halting(step) = axis.op.clone() else { unreachable!() };
2657        assert_eq!(step, HaltState::WaitCancelAckClear as u8);
2658
2659        // WaitCancelAckClear: drive drops bit 12. Halting completes,
2660        // halt bit cleared, op back to Idle.
2661        view.status_word = 0x0027;
2662        axis.tick(&mut view, &mut client);
2663        assert_eq!(axis.op, AxisOp::Idle);
2664        assert!(!axis.is_busy);
2665        assert!(view.control_word & (1 << 8) == 0, "halt should be cleared after close-out");
2666
2667        // Now a fresh move should start via the normal one-tick path —
2668        // bit 4 asserted immediately, op at step 1.
2669        axis.move_absolute(&mut view, 30.0, 90.0, 180.0, 180.0);
2670        assert!(view.control_word & (1 << 4) != 0, "new-setpoint asserted on start_move tick");
2671        assert!(view.control_word & (1 << 8) == 0, "halt stays cleared");
2672        assert!(matches!(axis.op, AxisOp::Moving(MoveKind::Absolute, 1, _, _)));
2673    }
2674
2675    #[test]
2676    fn limit_switch_allows_move_in_opposite_direction() {
2677        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2678        let mut view = MockView::new();
2679        view.set_state(0x0027);
2680        // Positive limit is active, but we're moving negative (retreating)
2681        view.positive_limit = true;
2682        view.velocity_actual = -100;
2683        axis.tick(&mut view, &mut client);
2684        assert!(axis.at_positive_limit_switch);
2685
2686        // Move in the negative direction should be allowed
2687        axis.move_absolute(&mut view, -10.0, 90.0, 180.0, 180.0);
2688        view.status_word = 0x1027;
2689        axis.tick(&mut view, &mut client);
2690
2691        // Should still be moving, no error
2692        assert!(!axis.is_error);
2693        assert!(matches!(axis.op, AxisOp::Moving(_, _, _, _)));
2694    }
2695
2696    #[test]
2697    fn limit_switch_ignored_when_not_moving() {
2698        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2699        let mut view = MockView::new();
2700        view.set_state(0x0027);
2701        view.positive_limit = true;
2702
2703        axis.tick(&mut view, &mut client);
2704
2705        // Output flag is set, but no error since we're not moving
2706        assert!(axis.at_positive_limit_switch);
2707        assert!(!axis.is_error);
2708    }
2709
2710    #[test]
2711    fn home_sensor_output_tracks_view() {
2712        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2713        let mut view = MockView::new();
2714        view.set_state(0x0027);
2715
2716        axis.tick(&mut view, &mut client);
2717        assert!(!axis.home_sensor);
2718
2719        view.home_sensor = true;
2720        axis.tick(&mut view, &mut client);
2721        assert!(axis.home_sensor);
2722
2723        view.home_sensor = false;
2724        axis.tick(&mut view, &mut client);
2725        assert!(!axis.home_sensor);
2726    }
2727
2728    #[test]
2729    fn velocity_output_converted() {
2730        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
2731        let mut view = MockView::new();
2732        view.set_state(0x0027);
2733        // 3200 counts/s = 90 deg/s
2734        view.velocity_actual = 3200;
2735
2736        axis.tick(&mut view, &mut client);
2737
2738        assert!((axis.speed - 90.0).abs() < 0.1);
2739        assert!(axis.moving_positive);
2740        assert!(!axis.moving_negative);
2741    }
2742
2743    // ── Software homing tests ──
2744
2745    fn soft_homing_config() -> AxisConfig {
2746        let mut cfg = AxisConfig::new(12_800).with_user_scale(360.0);
2747        cfg.homing_speed = 10.0;
2748        cfg.homing_accel = 20.0;
2749        cfg.homing_decel = 20.0;
2750        cfg
2751    }
2752
2753    fn soft_homing_axis() -> (Axis, CommandClient, tokio::sync::mpsc::UnboundedSender<mechutil::ipc::CommandMessage>, tokio::sync::mpsc::UnboundedReceiver<String>) {
2754        use tokio::sync::mpsc;
2755        let (write_tx, write_rx) = mpsc::unbounded_channel();
2756        let (response_tx, response_rx) = mpsc::unbounded_channel();
2757        let client = CommandClient::new(write_tx, response_rx);
2758        let axis = Axis::new(soft_homing_config(), "TestDrive");
2759        (axis, client, response_tx, write_rx)
2760    }
2761
2762    /// Helper: enable the axis and put it in OperationEnabled state.
2763    fn enable_axis(axis: &mut Axis, view: &mut MockView, client: &mut CommandClient) {
2764        view.set_state(0x0027); // OperationEnabled
2765        axis.tick(view, client);
2766    }
2767
2768    /// Helper: drive the soft homing state machine through phases 2-4
2769    /// (halt, back-off, set home). Call after sensor triggers (step 4).
2770    /// `trigger_pos`: position where sensor triggered
2771    /// `clear_sensor`: closure to deactivate the sensor on the view
2772    fn complete_soft_homing(
2773        axis: &mut Axis,
2774        view: &mut MockView,
2775        client: &mut CommandClient,
2776        resp_tx: &tokio::sync::mpsc::UnboundedSender<mechutil::ipc::CommandMessage>,
2777        trigger_pos: i32,
2778        clear_sensor: impl FnOnce(&mut MockView),
2779    ) {
2780        use mechutil::ipc::CommandMessage as IpcMsg;
2781
2782        // Phase 2: HALT (steps 4-6)
2783        // Step 4: halt
2784        axis.tick(view, client);
2785        assert!(matches!(axis.op, AxisOp::SoftHoming(5)));
2786
2787        // Step 5: motor decelerating then stopped
2788        view.position_actual = trigger_pos + 100;
2789        axis.tick(view, client);
2790        view.position_actual = trigger_pos + 120;
2791        axis.tick(view, client);
2792        // 10 stable ticks
2793        for _ in 0..10 { axis.tick(view, client); }
2794        assert!(matches!(axis.op, AxisOp::SoftHoming(6)));
2795
2796        // Step 6: cancel ack → delay step 60
2797        view.status_word = 0x1027;
2798        axis.tick(view, client);
2799        assert!(matches!(axis.op, AxisOp::SoftHoming(60)));
2800        view.status_word = 0x0027;
2801
2802        // Step 60: delay (~1 second = 100 ticks)
2803        for _ in 0..100 { axis.tick(view, client); }
2804        assert!(matches!(axis.op, AxisOp::SoftHoming(7)));
2805
2806        // Phase 3: BACK-OFF (steps 7-11)
2807        // Step 7: start back-off move
2808        axis.tick(view, client);
2809        assert!(matches!(axis.op, AxisOp::SoftHoming(8)));
2810
2811        // Step 8: ack
2812        view.status_word = 0x1027;
2813        axis.tick(view, client);
2814        assert!(matches!(axis.op, AxisOp::SoftHoming(9)));
2815        view.status_word = 0x0027;
2816
2817        // Step 9: sensor still active, then clears
2818        axis.tick(view, client);
2819        assert!(matches!(axis.op, AxisOp::SoftHoming(9)));
2820        clear_sensor(view);
2821        view.position_actual = trigger_pos - 200;
2822        axis.tick(view, client);
2823        assert!(matches!(axis.op, AxisOp::SoftHoming(10)));
2824
2825        // Step 10-11: halt after back-off, wait stable
2826        axis.tick(view, client);
2827        assert!(matches!(axis.op, AxisOp::SoftHoming(11)));
2828        for _ in 0..10 { axis.tick(view, client); }
2829        assert!(matches!(axis.op, AxisOp::SoftHoming(12)));
2830
2831        // Phase 4: SET HOME (steps 12-19)
2832        // Step 12: cancel ack + SDO write home offset
2833        view.status_word = 0x1027;
2834        axis.tick(view, client);
2835        view.status_word = 0x0027;
2836        assert!(matches!(axis.op, AxisOp::SoftHoming(13)));
2837
2838        // Step 13: SDO ack for home offset
2839        let tid = axis.homing_sdo_tid;
2840        resp_tx.send(IpcMsg::response(tid, json!(null))).unwrap();
2841        client.poll();
2842        axis.tick(view, client);
2843        assert!(matches!(axis.op, AxisOp::SoftHoming(14)));
2844
2845        // Step 14→15: SDO write homing method, ack
2846        axis.tick(view, client);
2847        let tid = axis.homing_sdo_tid;
2848        resp_tx.send(IpcMsg::response(tid, json!(null))).unwrap();
2849        client.poll();
2850        axis.tick(view, client);
2851        assert!(matches!(axis.op, AxisOp::SoftHoming(16)));
2852
2853        // Step 16: switch to homing mode + trigger
2854        view.modes_of_operation_display = ModesOfOperation::Homing.as_i8();
2855        axis.tick(view, client);
2856        assert!(matches!(axis.op, AxisOp::SoftHoming(17)));
2857
2858        // Step 17: homing complete (attained + reached)
2859        view.status_word = 0x1427; // bit 12 + bit 10
2860        axis.tick(view, client);
2861        assert!(matches!(axis.op, AxisOp::SoftHoming(18)));
2862        view.modes_of_operation_display = ModesOfOperation::ProfilePosition.as_i8();
2863        view.status_word = 0x0027;
2864
2865        // Step 18: hold position
2866        axis.tick(view, client);
2867        assert!(matches!(axis.op, AxisOp::SoftHoming(19)));
2868
2869        // Step 19: hold ack
2870        view.status_word = 0x1027;
2871        axis.tick(view, client);
2872        view.status_word = 0x0027;
2873
2874        assert_eq!(axis.op, AxisOp::Idle);
2875        assert!(!axis.is_busy);
2876        assert!(!axis.is_error);
2877        assert_eq!(axis.home_offset, 0); // drive handles it now
2878    }
2879
2880    #[test]
2881    fn soft_homing_pnp_home_sensor_full_sequence() {
2882        let (mut axis, mut client, resp_tx, _write_rx) = soft_homing_axis();
2883        let mut view = MockView::new();
2884        enable_axis(&mut axis, &mut view, &mut client);
2885
2886        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
2887
2888        // Phase 1: search
2889        axis.tick(&mut view, &mut client); // step 0→1
2890        view.status_word = 0x1027;
2891        axis.tick(&mut view, &mut client); // step 1→2 (ack)
2892        view.status_word = 0x0027;
2893        axis.tick(&mut view, &mut client); // step 2→3
2894
2895        // Sensor triggers
2896        view.home_sensor = true;
2897        view.position_actual = 5000;
2898        axis.tick(&mut view, &mut client);
2899        assert!(matches!(axis.op, AxisOp::SoftHoming(4)));
2900
2901        complete_soft_homing(&mut axis, &mut view, &mut client, &resp_tx, 5000,
2902            |v| { v.home_sensor = false; });
2903    }
2904
2905    #[test]
2906    fn soft_homing_npn_home_sensor_full_sequence() {
2907        let (mut axis, mut client, resp_tx, _write_rx) = soft_homing_axis();
2908        let mut view = MockView::new();
2909        // NPN: sensor reads true normally, false when detected
2910        view.home_sensor = true;
2911        enable_axis(&mut axis, &mut view, &mut client);
2912
2913        axis.home(&mut view, HomingMethod::HomeSensorPosNpn);
2914
2915        // Phase 1: search
2916        axis.tick(&mut view, &mut client);
2917        view.status_word = 0x1027;
2918        axis.tick(&mut view, &mut client);
2919        view.status_word = 0x0027;
2920        axis.tick(&mut view, &mut client);
2921
2922        // NPN: sensor goes false = detected
2923        view.home_sensor = false;
2924        view.position_actual = 3000;
2925        axis.tick(&mut view, &mut client);
2926        assert!(matches!(axis.op, AxisOp::SoftHoming(4)));
2927
2928        complete_soft_homing(&mut axis, &mut view, &mut client, &resp_tx, 3000,
2929            |v| { v.home_sensor = true; }); // NPN: back to true = cleared
2930    }
2931
2932    #[test]
2933    fn soft_homing_limit_switch_suppresses_halt() {
2934        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
2935        let mut view = MockView::new();
2936        enable_axis(&mut axis, &mut view, &mut client);
2937
2938        // Software homing on positive limit switch (rising edge)
2939        axis.home(&mut view, HomingMethod::LimitSwitchPosPnp);
2940
2941        // Progress through initial steps
2942        axis.tick(&mut view, &mut client); // step 0 → 1
2943        view.status_word = 0x1027; // ack
2944        axis.tick(&mut view, &mut client); // step 1 → 2
2945        view.status_word = 0x0027;
2946        axis.tick(&mut view, &mut client); // step 2 → 3
2947
2948        // Positive limit switch trips — should NOT halt (suppressed)
2949        view.positive_limit = true;
2950        view.velocity_actual = 100; // moving positive
2951        view.position_actual = 8000;
2952        axis.tick(&mut view, &mut client);
2953
2954        // Should have detected rising edge → step 4, NOT an error halt
2955        assert!(matches!(axis.op, AxisOp::SoftHoming(4)));
2956        assert!(!axis.is_error);
2957    }
2958
2959    #[test]
2960    fn soft_homing_opposite_limit_still_protects() {
2961        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
2962        let mut view = MockView::new();
2963        enable_axis(&mut axis, &mut view, &mut client);
2964
2965        // Software homing on home sensor (positive direction)
2966        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
2967
2968        // Progress through initial steps
2969        axis.tick(&mut view, &mut client); // step 0 → 1
2970        view.status_word = 0x1027; // ack
2971        axis.tick(&mut view, &mut client); // step 1 → 2
2972        view.status_word = 0x0027;
2973        axis.tick(&mut view, &mut client); // step 2 → 3
2974
2975        // Negative limit switch trips while searching positive (shouldn't happen
2976        // in practice, but tests protection)
2977        view.negative_limit = true;
2978        view.velocity_actual = -100; // moving negative
2979        axis.tick(&mut view, &mut client);
2980
2981        // Should have halted with error (negative limit protects)
2982        assert!(axis.is_error);
2983        assert!(axis.error_message.contains("Negative limit switch"));
2984    }
2985
2986    #[test]
2987    // fn soft_homing_sensor_already_active_rejects() {
2988    //     let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
2989    //     let mut view = MockView::new();
2990    //     enable_axis(&mut axis, &mut view, &mut client);
2991
2992    //     // Home sensor is already active (rising edge would never happen)
2993    //     view.home_sensor = true;
2994    //     axis.tick(&mut view, &mut client); // update prev state
2995
2996    //     axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
2997
2998    //     // Should have been rejected immediately
2999    //     assert!(axis.is_error);
3000    //     assert!(axis.error_message.contains("already in trigger state"));
3001    //     assert_eq!(axis.op, AxisOp::Idle);
3002    // }
3003
3004    #[test]
3005    fn soft_homing_negative_direction_sets_negative_target() {
3006        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
3007        let mut view = MockView::new();
3008        enable_axis(&mut axis, &mut view, &mut client);
3009
3010        axis.home(&mut view, HomingMethod::HomeSensorNegPnp);
3011        axis.tick(&mut view, &mut client); // step 0
3012
3013        // Target should be negative (large negative value in counts)
3014        assert!(view.target_position < 0);
3015    }
3016
3017    #[test]
3018    fn home_integrated_method_starts_hardware_homing() {
3019        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
3020        let mut view = MockView::new();
3021        enable_axis(&mut axis, &mut view, &mut client);
3022
3023        axis.home(&mut view, HomingMethod::CurrentPosition);
3024        assert!(matches!(axis.op, AxisOp::Homing(0)));
3025        assert_eq!(axis.homing_method, 37);
3026    }
3027
3028    #[test]
3029    fn home_integrated_arbitrary_code() {
3030        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
3031        let mut view = MockView::new();
3032        enable_axis(&mut axis, &mut view, &mut client);
3033
3034        axis.home(&mut view, HomingMethod::Integrated(35));
3035        assert!(matches!(axis.op, AxisOp::Homing(0)));
3036        assert_eq!(axis.homing_method, 35);
3037    }
3038
3039    #[test]
3040    fn hardware_homing_skips_speed_sdos_when_zero() {
3041        use mechutil::ipc::CommandMessage;
3042
3043        let (mut axis, mut client, resp_tx, mut write_rx) = test_axis();
3044        let mut view = MockView::new();
3045        enable_axis(&mut axis, &mut view, &mut client);
3046
3047        // Config has homing_speed = 0 and homing_accel = 0 (defaults)
3048        axis.home(&mut view, HomingMethod::Integrated(37));
3049
3050        // Step 0: writes homing method SDO
3051        axis.tick(&mut view, &mut client);
3052        assert!(matches!(axis.op, AxisOp::Homing(1)));
3053
3054        // Drain the SDO write message
3055        let _ = write_rx.try_recv();
3056
3057        // Simulate SDO ack — need to use the correct tid from the sdo write
3058        let tid = axis.homing_sdo_tid;
3059        resp_tx.send(CommandMessage::response(tid, serde_json::json!(null))).unwrap();
3060        client.poll();
3061        axis.tick(&mut view, &mut client);
3062
3063        // Should have skipped to step 8 (set homing mode)
3064        assert!(matches!(axis.op, AxisOp::Homing(8)));
3065    }
3066
3067    #[test]
3068    fn hardware_homing_writes_speed_sdos_when_nonzero() {
3069        use mechutil::ipc::CommandMessage;
3070
3071        let (mut axis, mut client, resp_tx, mut write_rx) = soft_homing_axis();
3072        let mut view = MockView::new();
3073        enable_axis(&mut axis, &mut view, &mut client);
3074
3075        // Config has homing_speed = 10.0, homing_accel = 20.0
3076        axis.home(&mut view, HomingMethod::Integrated(37));
3077
3078        // Step 0: writes homing method SDO
3079        axis.tick(&mut view, &mut client);
3080        assert!(matches!(axis.op, AxisOp::Homing(1)));
3081        let _ = write_rx.try_recv();
3082
3083        // SDO ack for homing method
3084        let tid = axis.homing_sdo_tid;
3085        resp_tx.send(CommandMessage::response(tid, serde_json::json!(null))).unwrap();
3086        client.poll();
3087        axis.tick(&mut view, &mut client);
3088        // Should go to step 2 (write speed SDO), not skip to 8
3089        assert!(matches!(axis.op, AxisOp::Homing(2)));
3090    }
3091
3092    #[test]
3093    fn soft_homing_edge_during_ack_step() {
3094        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
3095        let mut view = MockView::new();
3096        enable_axis(&mut axis, &mut view, &mut client);
3097
3098        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
3099        axis.tick(&mut view, &mut client); // step 0 → 1
3100
3101        // Sensor rises during step 1 (before ack)
3102        view.home_sensor = true;
3103        view.position_actual = 2000;
3104        axis.tick(&mut view, &mut client);
3105
3106        // Should jump straight to step 4 (edge detected)
3107        assert!(matches!(axis.op, AxisOp::SoftHoming(4)));
3108    }
3109
3110    #[test]
3111    fn soft_homing_applies_home_position() {
3112        let mut cfg = soft_homing_config();
3113        cfg.home_position = 90.0;
3114
3115        use tokio::sync::mpsc;
3116        let (write_tx, _write_rx) = mpsc::unbounded_channel();
3117        let (resp_tx, response_rx) = mpsc::unbounded_channel();
3118        let mut client = CommandClient::new(write_tx, response_rx);
3119        let mut axis = Axis::new(cfg, "TestDrive");
3120
3121        let mut view = MockView::new();
3122        enable_axis(&mut axis, &mut view, &mut client);
3123
3124        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
3125
3126        // Search phase
3127        axis.tick(&mut view, &mut client);
3128        view.status_word = 0x1027;
3129        axis.tick(&mut view, &mut client);
3130        view.status_word = 0x0027;
3131        axis.tick(&mut view, &mut client);
3132
3133        // Sensor triggers
3134        view.home_sensor = true;
3135        view.position_actual = 5000;
3136        axis.tick(&mut view, &mut client);
3137        assert!(matches!(axis.op, AxisOp::SoftHoming(4)));
3138
3139        // Complete full sequence (halt, back-off, set home via drive)
3140        complete_soft_homing(&mut axis, &mut view, &mut client, &resp_tx, 5000,
3141            |v| { v.home_sensor = false; });
3142
3143        // After completion, home_offset = 0 (drive handles it)
3144        assert_eq!(axis.home_offset, 0);
3145    }
3146
3147    #[test]
3148    fn soft_homing_default_home_position_zero() {
3149        let (mut axis, mut client, resp_tx, _write_rx) = soft_homing_axis();
3150        let mut view = MockView::new();
3151        enable_axis(&mut axis, &mut view, &mut client);
3152
3153        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
3154
3155        // Search phase
3156        axis.tick(&mut view, &mut client);
3157        view.status_word = 0x1027;
3158        axis.tick(&mut view, &mut client);
3159        view.status_word = 0x0027;
3160        axis.tick(&mut view, &mut client);
3161
3162        // Sensor triggers
3163        view.home_sensor = true;
3164        view.position_actual = 5000;
3165        axis.tick(&mut view, &mut client);
3166
3167        complete_soft_homing(&mut axis, &mut view, &mut client, &resp_tx, 5000,
3168            |v| { v.home_sensor = false; });
3169
3170        assert_eq!(axis.home_offset, 0);
3171    }
3172}