zwo_mount_control 0.2.0

Rust library for controlling ZWO AM5/AM3 telescope mounts with satellite tracking support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! Mock mount implementation for testing without physical hardware.
//!
//! Note: MountMode::Unknown is handled by defaulting to Equatorial behavior.
//!
//! The `MockMount` provides a fully simulated ZWO mount that maintains internal
//! state and simulates realistic movement behavior. This is useful for:
//!
//! - Testing application logic without a physical mount
//! - Developing and debugging tracking algorithms
//! - Running automated tests
//!
//! # Example
//!
//! ```rust
//! use zwo_mount_control::{MockMount, Mount, EquatorialPosition};
//!
//! let mut mount = MockMount::new();
//! mount.connect().unwrap();
//! mount.unpark().unwrap();
//!
//! // Get current position
//! let pos = mount.get_position().unwrap();
//! println!("Current position: {}", pos);
//!
//! // Slew to Vega
//! let vega = EquatorialPosition::from_hms_dms(18, 36, 56.0, 38, 47, 1.0);
//! mount.goto_equatorial(vega).unwrap();
//! ```

use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use chrono::{DateTime, Utc};

use crate::coordinates::{Coordinates, EquatorialPosition, HorizontalPosition, TrackingRates};
use crate::error::{MountError, MountResult};
use crate::mount::{Mount, MountStatus, SimulatedMount, SiteLocation};
use crate::protocol::{Direction, MountMode, SlewRate, TrackingRate};

/// Internal state for the mock mount.
#[derive(Debug, Clone)]
struct MockState {
    // Connection state
    connected: bool,

    // Current position (RA in hours, Dec in degrees)
    ra: f64,
    dec: f64,

    // Target position for slewing
    target_ra: f64,
    target_dec: f64,

    // Movement state
    is_slewing: bool,
    slew_start_time: Option<Instant>,
    slew_duration: Duration,

    // Manual movement
    moving_north: bool,
    moving_south: bool,
    moving_east: bool,
    moving_west: bool,

    // Tracking state
    is_tracking: bool,
    tracking_rate: TrackingRate,
    custom_ra_rate: f64,  // arcsec/sec
    custom_dec_rate: f64, // arcsec/sec

    // Mount configuration
    mount_mode: MountMode,
    slew_rate: SlewRate,
    guide_rate: f64,
    is_parked: bool,

    // Site location
    site_location: SiteLocation,

    // Simulation time tracking
    last_update: Instant,
    time_multiplier: f64,
    simulated_time: DateTime<Utc>,
}

impl Default for MockState {
    fn default() -> Self {
        Self {
            connected: false,
            ra: 0.0,
            dec: 0.0,
            target_ra: 0.0,
            target_dec: 0.0,
            is_slewing: false,
            slew_start_time: None,
            slew_duration: Duration::from_secs(0),
            moving_north: false,
            moving_south: false,
            moving_east: false,
            moving_west: false,
            is_tracking: false,
            tracking_rate: TrackingRate::Sidereal,
            custom_ra_rate: Coordinates::SIDEREAL_RATE_ARCSEC_PER_SEC,
            custom_dec_rate: 0.0,
            mount_mode: MountMode::Equatorial,
            slew_rate: SlewRate::FIND,
            guide_rate: 0.5,
            is_parked: true,
            site_location: SiteLocation::default(),
            last_update: Instant::now(),
            time_multiplier: 1.0,
            simulated_time: Utc::now(),
        }
    }
}

/// A simulated ZWO telescope mount for testing.
///
/// This mock implementation maintains realistic internal state and simulates
/// mount behavior including:
///
/// - Position tracking
/// - Slewing with configurable duration
/// - Manual movement
/// - Tracking with various rates
/// - Park/unpark operations
pub struct MockMount {
    state: Arc<Mutex<MockState>>,
    /// Maximum slew speed in degrees per second
    pub max_slew_speed: f64,
    /// Firmware version string
    pub firmware_version: String,
    /// Model name string
    pub model_name: String,
}

impl Default for MockMount {
    fn default() -> Self {
        Self::new()
    }
}

impl MockMount {
    /// Create a new mock mount with default settings.
    pub fn new() -> Self {
        Self {
            state: Arc::new(Mutex::new(MockState::default())),
            max_slew_speed: 6.0, // 6 degrees per second typical for AM5
            firmware_version: "1.0.0-mock".to_string(),
            model_name: "ZWO AM5 (Mock)".to_string(),
        }
    }

    /// Create a mock mount with a specific initial position.
    pub fn with_position(ra_hours: f64, dec_degrees: f64) -> Self {
        let mount = Self::new();
        {
            let mut state = mount.state.lock().unwrap();
            state.ra = Coordinates::normalize_ra(ra_hours);
            state.dec = Coordinates::normalize_dec(dec_degrees);
        }
        mount
    }

    /// Create a mock mount with a specific site location.
    pub fn with_location(latitude: f64, longitude: f64, altitude: f64) -> Self {
        let mount = Self::new();
        {
            let mut state = mount.state.lock().unwrap();
            state.site_location = SiteLocation::new(latitude, longitude, altitude);
        }
        mount
    }

    /// Update the internal state (simulate time passing).
    fn update_state(&self) {
        let mut state = self.state.lock().unwrap();
        let now = Instant::now();
        let elapsed = now.duration_since(state.last_update);
        let dt_seconds = elapsed.as_secs_f64() * state.time_multiplier;
        state.last_update = now;

        // Update simulated time
        let simulated_elapsed = chrono::Duration::milliseconds((dt_seconds * 1000.0) as i64);
        state.simulated_time = state.simulated_time + simulated_elapsed;

        // Handle slewing
        if state.is_slewing {
            if let Some(start_time) = state.slew_start_time {
                let slew_elapsed = now.duration_since(start_time);
                if slew_elapsed >= state.slew_duration {
                    // Slew complete
                    state.ra = state.target_ra;
                    state.dec = state.target_dec;
                    state.is_slewing = false;
                    state.slew_start_time = None;
                } else {
                    // Interpolate position during slew
                    let progress = slew_elapsed.as_secs_f64() / state.slew_duration.as_secs_f64();
                    let start_ra = state.ra;
                    let start_dec = state.dec;

                    // Calculate shortest path for RA (handle wrap-around)
                    let mut ra_diff = state.target_ra - start_ra;
                    if ra_diff > 12.0 {
                        ra_diff -= 24.0;
                    } else if ra_diff < -12.0 {
                        ra_diff += 24.0;
                    }

                    state.ra = Coordinates::normalize_ra(start_ra + ra_diff * progress);
                    state.dec = start_dec + (state.target_dec - start_dec) * progress;
                }
            }
        }

        // Handle manual movement
        if !state.is_slewing && !state.is_parked {
            let rate_deg_per_sec = Self::slew_rate_to_deg_per_sec(state.slew_rate);
            let movement = rate_deg_per_sec * dt_seconds;

            if state.moving_north {
                state.dec = (state.dec + movement).min(90.0);
            }
            if state.moving_south {
                state.dec = (state.dec - movement).max(-90.0);
            }
            if state.moving_east {
                // East = decreasing RA (in equatorial mode)
                state.ra = Coordinates::normalize_ra(state.ra - movement / 15.0);
            }
            if state.moving_west {
                // West = increasing RA (in equatorial mode)
                state.ra = Coordinates::normalize_ra(state.ra + movement / 15.0);
            }
        }

        // Handle tracking
        if state.is_tracking && !state.is_slewing && !state.is_parked {
            let ra_rate_arcsec = match state.tracking_rate {
                TrackingRate::Sidereal => Coordinates::SIDEREAL_RATE_ARCSEC_PER_SEC,
                TrackingRate::Lunar => 14.685, // Slightly slower than sidereal
                TrackingRate::Solar => 15.0,   // Exactly 15 arcsec/sec
                TrackingRate::Off => state.custom_ra_rate, // Use custom rate when "off" but tracking enabled
            };

            // Convert arcsec/sec to hours/sec (RA is in hours)
            let ra_rate_hours_per_sec = ra_rate_arcsec / 3600.0 / 15.0;
            state.ra = Coordinates::normalize_ra(state.ra + ra_rate_hours_per_sec * dt_seconds);

            // Apply dec rate if custom tracking
            if state.tracking_rate == TrackingRate::Off || state.custom_dec_rate.abs() > 0.0 {
                let dec_rate_deg_per_sec = state.custom_dec_rate / 3600.0;
                state.dec =
                    Coordinates::normalize_dec(state.dec + dec_rate_deg_per_sec * dt_seconds);
            }
        }
    }

    /// Convert slew rate setting to degrees per second.
    fn slew_rate_to_deg_per_sec(rate: SlewRate) -> f64 {
        // Map 1-9 scale to actual speeds
        match rate.value() {
            1 => 0.004, // Guide rate (~15 arcsec/sec)
            2 => 0.015,
            3 => 0.05,
            4 => 0.2, // Center rate
            5 => 0.5,
            6 => 1.0, // Find rate
            7 => 2.0,
            8 => 4.0,
            9 => 6.0, // Max slew rate
            _ => 1.0,
        }
    }

    /// Calculate slew duration based on angular distance.
    fn calculate_slew_duration(
        &self,
        from_ra: f64,
        from_dec: f64,
        to_ra: f64,
        to_dec: f64,
    ) -> Duration {
        // Calculate angular distance
        let ra_diff = {
            let mut diff = (to_ra - from_ra).abs();
            if diff > 12.0 {
                diff = 24.0 - diff;
            }
            diff * 15.0 // Convert hours to degrees
        };
        let dec_diff = (to_dec - from_dec).abs();

        // Total angular distance (approximate)
        let total_distance = (ra_diff * ra_diff + dec_diff * dec_diff).sqrt();

        // Calculate time based on max slew speed
        let seconds = total_distance / self.max_slew_speed;

        // Add minimum slew time for mount startup/settling
        Duration::from_secs_f64(seconds + 0.5)
    }

    /// Check if the mount is connected (internal helper).
    fn ensure_connected(&self) -> MountResult<()> {
        let state = self.state.lock().unwrap();
        if !state.connected {
            Err(MountError::NotConnected)
        } else {
            Ok(())
        }
    }

    /// Check if the mount is not parked (internal helper).
    fn ensure_not_parked(&self) -> MountResult<()> {
        let state = self.state.lock().unwrap();
        if state.is_parked {
            Err(MountError::unsupported("Mount is parked"))
        } else {
            Ok(())
        }
    }
}

impl Mount for MockMount {
    fn connect(&mut self) -> MountResult<()> {
        let mut state = self.state.lock().unwrap();
        state.connected = true;
        state.last_update = Instant::now();
        log::info!("Mock mount connected");
        Ok(())
    }

    fn disconnect(&mut self) -> MountResult<()> {
        let mut state = self.state.lock().unwrap();
        state.connected = false;
        state.is_tracking = false;
        state.is_slewing = false;
        log::info!("Mock mount disconnected");
        Ok(())
    }

    fn is_connected(&self) -> bool {
        self.state.lock().unwrap().connected
    }

    fn get_position(&self) -> MountResult<EquatorialPosition> {
        self.ensure_connected()?;
        self.update_state();
        let state = self.state.lock().unwrap();
        Ok(EquatorialPosition::new(state.ra, state.dec))
    }

    fn get_altaz(&self) -> MountResult<HorizontalPosition> {
        self.ensure_connected()?;
        self.update_state();
        let state = self.state.lock().unwrap();

        // Calculate LST (simplified - uses current UTC time)
        let jd = {
            let dt = state.simulated_time;
            let year = dt.format("%Y").to_string().parse::<i32>().unwrap();
            let month = dt.format("%m").to_string().parse::<u8>().unwrap();
            let day = dt.format("%d").to_string().parse::<f64>().unwrap();
            let hour = dt.format("%H").to_string().parse::<f64>().unwrap();
            let min = dt.format("%M").to_string().parse::<f64>().unwrap();
            let sec = dt.format("%S").to_string().parse::<f64>().unwrap();
            let day_frac = day + (hour + min / 60.0 + sec / 3600.0) / 24.0;
            Coordinates::to_julian_date(year, month, day_frac)
        };
        let lst = Coordinates::julian_to_lst(jd, state.site_location.longitude);

        let (az, alt) = Coordinates::equatorial_to_horizontal(
            state.ra,
            state.dec,
            state.site_location.latitude,
            lst,
        );
        Ok(HorizontalPosition::new(az, alt))
    }

    fn goto_equatorial(&mut self, position: EquatorialPosition) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;
        self.update_state();

        let mut state = self.state.lock().unwrap();

        // Calculate slew duration
        let duration = self.calculate_slew_duration(state.ra, state.dec, position.ra, position.dec);

        state.target_ra = position.ra;
        state.target_dec = position.dec;
        state.is_slewing = true;
        state.slew_start_time = Some(Instant::now());
        state.slew_duration = duration;

        log::info!(
            "Mock mount slewing to RA={:.4}h, Dec={:.4}° (duration: {:.1}s)",
            position.ra,
            position.dec,
            duration.as_secs_f64()
        );

        Ok(())
    }

    fn goto_altaz(&mut self, position: HorizontalPosition) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;

        let state = self.state.lock().unwrap();
        if state.mount_mode != MountMode::AltAz {
            return Err(MountError::unsupported(
                "Mount must be in Alt-Az mode for Az/Alt slewing",
            ));
        }

        // Check if target is above horizon
        if !position.is_above_horizon() {
            return Err(MountError::BelowHorizon(position.altitude));
        }

        // Convert to equatorial and slew
        let jd = {
            let dt = state.simulated_time;
            let year = dt.format("%Y").to_string().parse::<i32>().unwrap();
            let month = dt.format("%m").to_string().parse::<u8>().unwrap();
            let day = dt.format("%d").to_string().parse::<f64>().unwrap();
            let hour = dt.format("%H").to_string().parse::<f64>().unwrap();
            let min = dt.format("%M").to_string().parse::<f64>().unwrap();
            let sec = dt.format("%S").to_string().parse::<f64>().unwrap();
            let day_frac = day + (hour + min / 60.0 + sec / 3600.0) / 24.0;
            Coordinates::to_julian_date(year, month, day_frac)
        };
        let lst = Coordinates::julian_to_lst(jd, state.site_location.longitude);
        let eq_pos = position.to_equatorial(state.site_location.latitude, lst);

        drop(state); // Release lock before calling goto_equatorial
        self.goto_equatorial(eq_pos)
    }

    fn is_slewing(&self) -> MountResult<bool> {
        self.ensure_connected()?;
        self.update_state();
        Ok(self.state.lock().unwrap().is_slewing)
    }

    fn abort_slew(&mut self) -> MountResult<()> {
        self.ensure_connected()?;
        let mut state = self.state.lock().unwrap();
        state.is_slewing = false;
        state.slew_start_time = None;
        state.moving_north = false;
        state.moving_south = false;
        state.moving_east = false;
        state.moving_west = false;
        log::info!("Mock mount slew aborted");
        Ok(())
    }

    fn move_axis(&mut self, direction: Direction) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;

        let mut state = self.state.lock().unwrap();
        match direction {
            Direction::North => state.moving_north = true,
            Direction::South => state.moving_south = true,
            Direction::East => state.moving_east = true,
            Direction::West => state.moving_west = true,
        }
        log::debug!("Mock mount moving {:?}", direction);
        Ok(())
    }

    fn stop_axis(&mut self, direction: Direction) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        match direction {
            Direction::North => state.moving_north = false,
            Direction::South => state.moving_south = false,
            Direction::East => state.moving_east = false,
            Direction::West => state.moving_west = false,
        }
        log::debug!("Mock mount stopped {:?}", direction);
        Ok(())
    }

    fn stop_all(&mut self) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        state.is_slewing = false;
        state.slew_start_time = None;
        state.moving_north = false;
        state.moving_south = false;
        state.moving_east = false;
        state.moving_west = false;
        log::info!("Mock mount all movement stopped");
        Ok(())
    }

    fn set_slew_rate(&mut self, rate: SlewRate) -> MountResult<()> {
        self.ensure_connected()?;
        self.state.lock().unwrap().slew_rate = rate;
        log::debug!("Mock mount slew rate set to {}", rate.value());
        Ok(())
    }

    fn set_tracking(&mut self, rate: TrackingRate) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;

        let mut state = self.state.lock().unwrap();
        state.tracking_rate = rate;
        state.is_tracking = rate != TrackingRate::Off;
        log::info!("Mock mount tracking rate set to {:?}", rate);
        Ok(())
    }

    fn tracking_on(&mut self) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;

        let mut state = self.state.lock().unwrap();
        state.is_tracking = true;
        log::info!("Mock mount tracking enabled");
        Ok(())
    }

    fn tracking_off(&mut self) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        state.is_tracking = false;
        log::info!("Mock mount tracking disabled");
        Ok(())
    }

    fn is_tracking(&self) -> MountResult<bool> {
        self.ensure_connected()?;
        Ok(self.state.lock().unwrap().is_tracking)
    }

    fn set_custom_tracking_rates(&mut self, rates: TrackingRates) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;

        if !rates.is_valid_for_satellite() {
            return Err(MountError::invalid_coords(format!(
                "Tracking rates too high: RA={:.2}\"/s, Dec={:.2}\"/s",
                rates.ra_rate, rates.dec_rate
            )));
        }

        let mut state = self.state.lock().unwrap();
        state.custom_ra_rate = rates.ra_rate;
        state.custom_dec_rate = rates.dec_rate;
        state.is_tracking = true;
        log::info!(
            "Mock mount custom tracking rates set: RA={:.2}\"/s, Dec={:.2}\"/s",
            rates.ra_rate,
            rates.dec_rate
        );
        Ok(())
    }

    fn set_guide_rate(&mut self, rate: f64) -> MountResult<()> {
        self.ensure_connected()?;

        let clamped = rate.clamp(0.1, 0.9);
        self.state.lock().unwrap().guide_rate = clamped;
        log::debug!("Mock mount guide rate set to {:.1}", clamped);
        Ok(())
    }

    fn get_guide_rate(&self) -> MountResult<f64> {
        self.ensure_connected()?;
        Ok(self.state.lock().unwrap().guide_rate)
    }

    fn guide_pulse(&mut self, direction: Direction, duration_ms: u32) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;

        let state = self.state.lock().unwrap();
        let guide_rate = state.guide_rate;
        let ra = state.ra;
        let dec = state.dec;
        drop(state);

        // Calculate guide movement
        let guide_speed = guide_rate * Coordinates::SIDEREAL_RATE_ARCSEC_PER_SEC / 3600.0; // deg/sec
        let duration_sec = duration_ms as f64 / 1000.0;
        let movement = guide_speed * duration_sec;

        let mut state = self.state.lock().unwrap();
        match direction {
            Direction::North => state.dec = (dec + movement).min(90.0),
            Direction::South => state.dec = (dec - movement).max(-90.0),
            Direction::East => state.ra = Coordinates::normalize_ra(ra - movement / 15.0),
            Direction::West => state.ra = Coordinates::normalize_ra(ra + movement / 15.0),
        }

        log::debug!(
            "Mock mount guide pulse: {:?} for {}ms",
            direction,
            duration_ms
        );
        Ok(())
    }

    fn set_altaz_mode(&mut self) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        state.mount_mode = MountMode::AltAz;
        log::info!("Mock mount set to Alt-Az mode");
        Ok(())
    }

    fn set_polar_mode(&mut self) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        state.mount_mode = MountMode::Equatorial;
        log::info!("Mock mount set to Polar/Equatorial mode");
        Ok(())
    }

    fn get_mount_mode(&self) -> MountResult<MountMode> {
        self.ensure_connected()?;
        let mode = self.state.lock().unwrap().mount_mode;
        // Convert Unknown to Equatorial for mock mount
        Ok(if mode == MountMode::Unknown {
            MountMode::Equatorial
        } else {
            mode
        })
    }

    fn go_home(&mut self) -> MountResult<()> {
        self.ensure_connected()?;
        self.ensure_not_parked()?;

        // Home position is typically RA=0, Dec=90 (or Dec=lat for polar alignment)
        self.goto_equatorial(EquatorialPosition::new(0.0, 90.0))
    }

    fn park(&mut self) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        state.is_tracking = false;
        state.is_slewing = false;
        state.is_parked = true;
        log::info!("Mock mount parked");
        Ok(())
    }

    fn unpark(&mut self) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        state.is_parked = false;
        log::info!("Mock mount unparked");
        Ok(())
    }

    fn is_parked(&self) -> MountResult<bool> {
        self.ensure_connected()?;
        Ok(self.state.lock().unwrap().is_parked)
    }

    fn sync(&mut self, position: EquatorialPosition) -> MountResult<()> {
        self.ensure_connected()?;

        let mut state = self.state.lock().unwrap();
        state.ra = position.ra;
        state.dec = position.dec;
        log::info!(
            "Mock mount synced to RA={:.4}h, Dec={:.4}°",
            position.ra,
            position.dec
        );
        Ok(())
    }

    fn set_site_location(&mut self, location: SiteLocation) -> MountResult<()> {
        self.ensure_connected()?;

        self.state.lock().unwrap().site_location = location;
        log::info!(
            "Mock mount site location set to lat={:.4}°, lon={:.4}°, alt={:.1}m",
            location.latitude,
            location.longitude,
            location.altitude
        );
        Ok(())
    }

    fn get_site_location(&self) -> MountResult<SiteLocation> {
        self.ensure_connected()?;
        Ok(self.state.lock().unwrap().site_location)
    }

    fn get_status(&self) -> MountResult<MountStatus> {
        self.ensure_connected()?;
        self.update_state();

        let state = self.state.lock().unwrap();
        Ok(MountStatus {
            is_tracking: state.is_tracking,
            is_slewing: state.is_slewing,
            mount_mode: state.mount_mode,
            tracking_rate: state.tracking_rate,
            is_parked: state.is_parked,
            is_connected: state.connected,
            slew_rate: state.slew_rate,
            guide_rate: state.guide_rate,
            pier_side: "East".to_string(), // Mock always returns East
        })
    }

    fn get_firmware_version(&self) -> MountResult<String> {
        self.ensure_connected()?;
        Ok(self.firmware_version.clone())
    }

    fn get_model(&self) -> MountResult<String> {
        self.ensure_connected()?;
        Ok(self.model_name.clone())
    }

    fn send_raw_command(&mut self, command: &str) -> MountResult<String> {
        self.ensure_connected()?;
        log::debug!("Mock mount raw command: {}", command);
        // Return a generic "1" response for most commands (success)
        Ok("1#".to_string())
    }
}

impl SimulatedMount for MockMount {
    fn advance_time(&mut self, duration: Duration) {
        let mut state = self.state.lock().unwrap();
        let simulated_elapsed = chrono::Duration::milliseconds((duration.as_millis()) as i64);
        state.simulated_time = state.simulated_time + simulated_elapsed;
    }

    fn set_time_multiplier(&mut self, multiplier: f64) {
        self.state.lock().unwrap().time_multiplier = multiplier.max(0.0);
    }

    fn get_simulation_time(&self) -> DateTime<Utc> {
        self.state.lock().unwrap().simulated_time
    }
}

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

    #[test]
    fn test_mock_mount_connect() {
        let mut mount = MockMount::new();
        assert!(!mount.is_connected());

        mount.connect().unwrap();
        assert!(mount.is_connected());

        mount.disconnect().unwrap();
        assert!(!mount.is_connected());
    }

    #[test]
    fn test_mock_mount_position() {
        let mut mount = MockMount::with_position(12.0, 45.0);
        mount.connect().unwrap();

        let pos = mount.get_position().unwrap();
        assert!((pos.ra - 12.0).abs() < 0.001);
        assert!((pos.dec - 45.0).abs() < 0.001);
    }

    #[test]
    fn test_mock_mount_slew() {
        let mut mount = MockMount::with_position(0.0, 0.0);
        mount.connect().unwrap();
        mount.unpark().unwrap();

        // Start slewing
        let target = EquatorialPosition::new(1.0, 10.0);
        mount.goto_equatorial(target).unwrap();

        assert!(mount.is_slewing().unwrap());

        // Wait for slew to complete (with timeout)
        for _ in 0..100 {
            if !mount.is_slewing().unwrap() {
                break;
            }
            sleep(Duration::from_millis(100));
        }

        assert!(!mount.is_slewing().unwrap());

        let pos = mount.get_position().unwrap();
        assert!((pos.ra - 1.0).abs() < 0.01);
        assert!((pos.dec - 10.0).abs() < 0.01);
    }

    #[test]
    fn test_mock_mount_tracking() {
        let mut mount = MockMount::with_position(12.0, 45.0);
        mount.connect().unwrap();
        mount.unpark().unwrap();

        assert!(!mount.is_tracking().unwrap());

        mount.set_tracking(TrackingRate::Sidereal).unwrap();
        assert!(mount.is_tracking().unwrap());

        mount.tracking_off().unwrap();
        assert!(!mount.is_tracking().unwrap());
    }

    #[test]
    fn test_mock_mount_park() {
        let mut mount = MockMount::new();
        mount.connect().unwrap();

        assert!(mount.is_parked().unwrap());

        mount.unpark().unwrap();
        assert!(!mount.is_parked().unwrap());

        mount.park().unwrap();
        assert!(mount.is_parked().unwrap());
    }

    #[test]
    fn test_mock_mount_sync() {
        let mut mount = MockMount::with_position(0.0, 0.0);
        mount.connect().unwrap();

        let sync_pos = EquatorialPosition::new(18.0, 38.0);
        mount.sync(sync_pos).unwrap();

        let pos = mount.get_position().unwrap();
        assert!((pos.ra - 18.0).abs() < 0.001);
        assert!((pos.dec - 38.0).abs() < 0.001);
    }

    #[test]
    fn test_mock_mount_modes() {
        let mut mount = MockMount::new();
        mount.connect().unwrap();

        assert_eq!(mount.get_mount_mode().unwrap(), MountMode::Equatorial);

        mount.set_altaz_mode().unwrap();
        assert_eq!(mount.get_mount_mode().unwrap(), MountMode::AltAz);

        mount.set_polar_mode().unwrap();
        assert_eq!(mount.get_mount_mode().unwrap(), MountMode::Equatorial);
    }

    #[test]
    fn test_mock_mount_guide_rate() {
        let mut mount = MockMount::new();
        mount.connect().unwrap();

        mount.set_guide_rate(0.5).unwrap();
        assert!((mount.get_guide_rate().unwrap() - 0.5).abs() < 0.01);

        // Test clamping
        mount.set_guide_rate(2.0).unwrap();
        assert!((mount.get_guide_rate().unwrap() - 0.9).abs() < 0.01);
    }

    #[test]
    fn test_mock_mount_site_location() {
        let mut mount = MockMount::new();
        mount.connect().unwrap();

        let loc = SiteLocation::new(34.0522, -118.2437, 71.0);
        mount.set_site_location(loc).unwrap();

        let retrieved = mount.get_site_location().unwrap();
        assert!((retrieved.latitude - 34.0522).abs() < 0.0001);
        assert!((retrieved.longitude - (-118.2437)).abs() < 0.0001);
    }

    #[test]
    fn test_mock_mount_not_connected_error() {
        let mount = MockMount::new();
        assert!(mount.get_position().is_err());
    }

    #[test]
    fn test_mock_mount_parked_error() {
        let mut mount = MockMount::new();
        mount.connect().unwrap();
        // Mount starts parked

        let target = EquatorialPosition::new(12.0, 45.0);
        assert!(mount.goto_equatorial(target).is_err());
    }
}