zwo_mount_control 0.2.1

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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! ZWO AM5/AM3 Serial Protocol Commands
//!
//! This module defines the serial commands used to communicate with ZWO telescope mounts.
//! The protocol is largely compatible with the Meade LX200 protocol with ZWO extensions.
//!
//! # Command Format
//!
//! Most commands follow the format `:XX#` where XX is the command code.
//! Responses typically end with `#` as a terminator.
//!
//! # Response Behavior
//!
//! Many commands are "fire and forget" - they don't return a response.
//! Commands that do return responses are documented as such.

use std::fmt;

/// Movement direction for manual slewing operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    North,
    South,
    East,
    West,
}

impl fmt::Display for Direction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Direction::North => write!(f, "North"),
            Direction::South => write!(f, "South"),
            Direction::East => write!(f, "East"),
            Direction::West => write!(f, "West"),
        }
    }
}

impl Direction {
    /// Get the opposite direction.
    pub fn opposite(&self) -> Self {
        match self {
            Direction::North => Direction::South,
            Direction::South => Direction::North,
            Direction::East => Direction::West,
            Direction::West => Direction::East,
        }
    }
}

/// Tracking rate modes supported by ZWO mounts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TrackingRate {
    /// Sidereal rate (for stars) - default
    #[default]
    Sidereal,
    /// Lunar rate (for the Moon)
    Lunar,
    /// Solar rate (for the Sun)
    Solar,
    /// No tracking (tracking disabled)
    Off,
}

impl fmt::Display for TrackingRate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TrackingRate::Sidereal => write!(f, "Sidereal"),
            TrackingRate::Lunar => write!(f, "Lunar"),
            TrackingRate::Solar => write!(f, "Solar"),
            TrackingRate::Off => write!(f, "Off"),
        }
    }
}

/// Mount operating mode (physical configuration).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MountMode {
    /// Alt-Azimuth mode (tripod, no wedge)
    AltAz,
    /// Equatorial mode (polar aligned, on wedge)
    #[default]
    Equatorial,
    /// Unknown mode
    Unknown,
}

impl fmt::Display for MountMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MountMode::AltAz => write!(f, "Alt-Az"),
            MountMode::Equatorial => write!(f, "Equatorial"),
            MountMode::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Slew speed presets (0-9 scale).
///
/// Rate mappings:
/// - 0: Guide rate (~0.5x sidereal)
/// - 1-3: Centering rates (1-8x sidereal)
/// - 4-6: Find rates (16-64x sidereal)
/// - 7-9: Slew rates (up to 1440x sidereal - fastest)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlewRate(u8);

impl SlewRate {
    /// Guide rate (slowest, ~0.5x sidereal)
    pub const GUIDE: SlewRate = SlewRate(0);
    /// Centering rate
    pub const CENTER: SlewRate = SlewRate(3);
    /// Find rate
    pub const FIND: SlewRate = SlewRate(6);
    /// Maximum slew rate (fastest, up to 1440x sidereal)
    pub const MAX: SlewRate = SlewRate(9);

    /// Create a new slew rate (clamped to 0-9).
    pub fn new(rate: u8) -> Self {
        SlewRate(rate.min(9))
    }

    /// Get the numeric rate value.
    pub fn value(&self) -> u8 {
        self.0
    }
}

impl Default for SlewRate {
    fn default() -> Self {
        SlewRate::FIND
    }
}

impl From<u8> for SlewRate {
    fn from(rate: u8) -> Self {
        SlewRate::new(rate)
    }
}

/// ZWO Protocol Commands
///
/// This struct provides methods to generate command strings for the ZWO mount protocol.
/// Commands are categorized by whether they return responses or are fire-and-forget.
pub struct Protocol;

impl Protocol {
    // ============================================
    // GETTER COMMANDS (expect responses)
    // ============================================

    /// Get mount firmware version.
    /// Response: version string followed by #
    pub fn get_version() -> &'static str {
        ":GV#"
    }

    /// Get mount model name.
    /// Response: model name followed by #
    pub fn get_mount_model() -> &'static str {
        ":GVP#"
    }

    /// Get current Right Ascension.
    /// Response format: HH:MM:SS# or HH:MM.T#
    pub fn get_ra() -> &'static str {
        ":GR#"
    }

    /// Get current Declination.
    /// Response format: sDD*MM:SS# or sDD*MM#
    pub fn get_dec() -> &'static str {
        ":GD#"
    }

    /// Get current Azimuth.
    /// Response format: DDD*MM:SS#
    pub fn get_azimuth() -> &'static str {
        ":GZ#"
    }

    /// Get current Altitude (elevation).
    /// Response format: sDD*MM:SS#
    pub fn get_altitude() -> &'static str {
        ":GA#"
    }

    /// Get date in MM/DD/YY format.
    pub fn get_date() -> &'static str {
        ":GC#"
    }

    /// Get local time in HH:MM:SS format.
    pub fn get_time() -> &'static str {
        ":GL#"
    }

    /// Get UTC offset.
    pub fn get_timezone() -> &'static str {
        ":GG#"
    }

    /// Get sidereal time.
    pub fn get_sidereal_time() -> &'static str {
        ":GS#"
    }

    /// Get site latitude.
    /// Response format: sDD*MM#
    pub fn get_latitude() -> &'static str {
        ":Gt#"
    }

    /// Get site longitude.
    /// Response format: DDD*MM#
    pub fn get_longitude() -> &'static str {
        ":Gg#"
    }

    /// Get guide rate.
    pub fn get_guide_rate() -> &'static str {
        ":Ggr#"
    }

    /// Get tracking status.
    /// Response: 0 = not tracking, 1 = tracking
    pub fn get_tracking_status() -> &'static str {
        ":GAT#"
    }

    /// Get mount status flags.
    ///
    /// Response flags (ZWO-specific):
    /// - `n` = not tracking
    /// - `N` = not slewing/moving
    /// - `H` = at home position
    /// - `G` = equatorial (German equatorial) mode
    /// - `Z` = alt-az mode
    pub fn get_status() -> &'static str {
        ":GU#"
    }

    /// Get cardinal direction (pier side).
    pub fn get_cardinal_direction() -> &'static str {
        ":Gm#"
    }

    /// Get meridian flip settings.
    pub fn get_meridian_settings() -> &'static str {
        ":GTa#"
    }

    /// Get buzzer volume.
    pub fn get_buzzer_volume() -> &'static str {
        ":GBu#"
    }

    // ============================================
    // SETTER COMMANDS - Target Coordinates
    // (These return "1" on success, "0" on failure)
    // ============================================

    /// Set target Right Ascension.
    /// Format: HH:MM:SS
    /// Response: 1 if valid, 0 if invalid
    pub fn set_target_ra(hours: u8, minutes: u8, seconds: u8) -> String {
        format!(":Sr{:02}:{:02}:{:02}#", hours, minutes, seconds)
    }

    /// Set target Azimuth.
    /// Format: DDD*MM:SS
    /// Response: 1 if valid, 0 if invalid
    pub fn set_target_azimuth(degrees: u16, minutes: u8, seconds: u8) -> String {
        format!(":Sz{:03}*{:02}:{:02}#", degrees % 360, minutes, seconds)
    }

    /// Set target Azimuth from decimal degrees.
    pub fn set_target_azimuth_decimal(az_degrees: f64) -> String {
        let az = if az_degrees < 0.0 {
            az_degrees + 360.0
        } else {
            az_degrees % 360.0
        };
        let total_arcsec = (az * 3600.0).round() as u32;
        let degrees = (total_arcsec / 3600) % 360;
        let minutes = (total_arcsec % 3600) / 60;
        let seconds = total_arcsec % 60;
        format!(":Sz{:03}*{:02}:{:02}#", degrees, minutes, seconds)
    }

    /// Set target Altitude.
    /// Format: sDD*MM:SS
    /// Response: 1 if valid, 0 if invalid
    pub fn set_target_altitude(degrees: i8, minutes: u8, seconds: u8) -> String {
        let sign = if degrees >= 0 { '+' } else { '-' };
        format!(
            ":Sa{}{}*{:02}:{:02}#",
            sign,
            degrees.unsigned_abs(),
            minutes,
            seconds
        )
    }

    /// Set target Altitude from decimal degrees.
    pub fn set_target_altitude_decimal(alt_degrees: f64) -> String {
        let sign = if alt_degrees >= 0.0 { '+' } else { '-' };
        let total_arcsec = (alt_degrees.abs() * 3600.0).round() as u32;
        let degrees = total_arcsec / 3600;
        let minutes = (total_arcsec % 3600) / 60;
        let seconds = total_arcsec % 60;
        format!(":Sa{}{}*{:02}:{:02}#", sign, degrees, minutes, seconds)
    }

    /// Set target Right Ascension from decimal hours.
    pub fn set_target_ra_decimal(ra_hours: f64) -> String {
        let total_seconds = (ra_hours * 3600.0).round() as u32;
        let hours = (total_seconds / 3600) % 24;
        let minutes = (total_seconds % 3600) / 60;
        let seconds = total_seconds % 60;
        format!(":Sr{:02}:{:02}:{:02}#", hours, minutes, seconds)
    }

    /// Set target Declination.
    /// Format: sDD*MM:SS
    /// Response: 1 if valid, 0 if invalid
    pub fn set_target_dec(degrees: i16, minutes: u8, seconds: u8) -> String {
        let sign = if degrees >= 0 { '+' } else { '-' };
        format!(
            ":Sd{}{}*{:02}:{:02}#",
            sign,
            degrees.unsigned_abs(),
            minutes,
            seconds
        )
    }

    /// Set target Declination from decimal degrees.
    pub fn set_target_dec_decimal(dec_degrees: f64) -> String {
        let sign = if dec_degrees >= 0.0 { '+' } else { '-' };
        let total_arcsec = (dec_degrees.abs() * 3600.0).round() as u32;
        let degrees = total_arcsec / 3600;
        let minutes = (total_arcsec % 3600) / 60;
        let seconds = total_arcsec % 60;
        format!(":Sd{}{}*{:02}:{:02}#", sign, degrees, minutes, seconds)
    }

    // ============================================
    // SETTER COMMANDS - Slewing & GoTo
    // ============================================

    /// Execute GoTo to the previously set target coordinates.
    /// Response: 0 = success, 1 = below horizon, 2 = below min elevation,
    ///           4 = unreachable, 5 = not aligned, 6 = outside limits, 7 = pier side limit
    pub fn goto() -> &'static str {
        ":MS#"
    }

    /// Sync mount to the previously set target coordinates.
    /// Response: coordinate string on success
    pub fn sync() -> &'static str {
        ":CM#"
    }

    /// Stop all mount movement.
    /// No response expected.
    pub fn stop_all() -> &'static str {
        ":Q#"
    }

    // ============================================
    // SETTER COMMANDS - Motion Control
    // (Fire and forget - no responses)
    // ============================================

    /// Start moving north.
    pub fn move_north() -> &'static str {
        ":Mn#"
    }

    /// Start moving south.
    pub fn move_south() -> &'static str {
        ":Ms#"
    }

    /// Start moving east.
    pub fn move_east() -> &'static str {
        ":Me#"
    }

    /// Start moving west.
    pub fn move_west() -> &'static str {
        ":Mw#"
    }

    /// Start moving in the specified direction.
    pub fn move_direction(direction: Direction) -> &'static str {
        match direction {
            Direction::North => Self::move_north(),
            Direction::South => Self::move_south(),
            Direction::East => Self::move_east(),
            Direction::West => Self::move_west(),
        }
    }

    /// Stop moving north.
    pub fn stop_north() -> &'static str {
        ":Qn#"
    }

    /// Stop moving south.
    pub fn stop_south() -> &'static str {
        ":Qs#"
    }

    /// Stop moving east.
    pub fn stop_east() -> &'static str {
        ":Qe#"
    }

    /// Stop moving west.
    pub fn stop_west() -> &'static str {
        ":Qw#"
    }

    /// Stop moving in the specified direction.
    pub fn stop_direction(direction: Direction) -> &'static str {
        match direction {
            Direction::North => Self::stop_north(),
            Direction::South => Self::stop_south(),
            Direction::East => Self::stop_east(),
            Direction::West => Self::stop_west(),
        }
    }

    /// Set slew rate preset (0-9).
    ///
    /// Rate mappings:
    /// - 0: Guide rate (~0.5x sidereal)
    /// - 1-3: Centering rates (1-8x sidereal)
    /// - 4-6: Find rates (16-64x sidereal)
    /// - 7-9: Slew rates (up to 1440x sidereal - fastest)
    pub fn set_slew_rate(rate: SlewRate) -> String {
        format!(":R{}#", rate.value())
    }

    // ============================================
    // SETTER COMMANDS - Guiding
    // (Fire and forget - no responses)
    // ============================================

    /// Set guide rate as a fraction of sidereal (0.1 to 0.9).
    pub fn set_guide_rate(rate: f64) -> String {
        let clamped = rate.clamp(0.1, 0.9);
        format!(":Rg{:.1}#", clamped)
    }

    /// Send guide pulse North for specified milliseconds (0-9999).
    pub fn guide_pulse_north(ms: u32) -> String {
        format!(":Mgn{:04}#", ms.min(9999))
    }

    /// Send guide pulse South for specified milliseconds (0-9999).
    pub fn guide_pulse_south(ms: u32) -> String {
        format!(":Mgs{:04}#", ms.min(9999))
    }

    /// Send guide pulse East for specified milliseconds (0-9999).
    pub fn guide_pulse_east(ms: u32) -> String {
        format!(":Mge{:04}#", ms.min(9999))
    }

    /// Send guide pulse West for specified milliseconds (0-9999).
    pub fn guide_pulse_west(ms: u32) -> String {
        format!(":Mgw{:04}#", ms.min(9999))
    }

    /// Send guide pulse in specified direction for milliseconds.
    pub fn guide_pulse(direction: Direction, ms: u32) -> String {
        match direction {
            Direction::North => Self::guide_pulse_north(ms),
            Direction::South => Self::guide_pulse_south(ms),
            Direction::East => Self::guide_pulse_east(ms),
            Direction::West => Self::guide_pulse_west(ms),
        }
    }

    // ============================================
    // SETTER COMMANDS - Tracking
    // (Fire and forget - no responses)
    // ============================================

    /// Enable tracking.
    pub fn tracking_on() -> &'static str {
        ":Te#"
    }

    /// Disable tracking.
    pub fn tracking_off() -> &'static str {
        ":Td#"
    }

    /// Set sidereal tracking rate.
    pub fn tracking_sidereal() -> &'static str {
        ":TQ#"
    }

    /// Set lunar tracking rate.
    pub fn tracking_lunar() -> &'static str {
        ":TL#"
    }

    /// Set solar tracking rate.
    pub fn tracking_solar() -> &'static str {
        ":TS#"
    }

    /// Set tracking rate for the specified mode.
    pub fn set_tracking_rate(rate: TrackingRate) -> &'static str {
        match rate {
            TrackingRate::Sidereal => Self::tracking_sidereal(),
            TrackingRate::Lunar => Self::tracking_lunar(),
            TrackingRate::Solar => Self::tracking_solar(),
            TrackingRate::Off => Self::tracking_off(),
        }
    }

    // ============================================
    // SETTER COMMANDS - Home & Park
    // (Fire and forget - no responses)
    // ============================================

    /// Find home position (slews both axes to limit switches for calibration).
    pub fn find_home() -> &'static str {
        ":hC#"
    }

    /// Go to park position.
    pub fn goto_park() -> &'static str {
        ":hP#"
    }

    /// Unpark the mount.
    pub fn unpark() -> &'static str {
        ":hR#"
    }

    /// Clear alignment data.
    pub fn clear_alignment() -> &'static str {
        ":SRC#"
    }

    // ============================================
    // SETTER COMMANDS - Mount Mode
    // (Fire and forget - no responses)
    // ============================================

    /// Set mount to Alt-Az (azimuth/altitude) mode.
    /// Use this when the mount is physically installed on a tripod (no wedge).
    pub fn set_altaz_mode() -> &'static str {
        ":AA#"
    }

    /// Set mount to Polar (equatorial) mode.
    /// Use this when the mount is physically installed on an equatorial wedge.
    pub fn set_polar_mode() -> &'static str {
        ":AP#"
    }

    // ============================================
    // SETTER COMMANDS - Site & Time Configuration
    // (These return "1" on success, "0" on failure)
    // ============================================

    /// Set date (MM/DD/YY).
    pub fn set_date(month: u8, day: u8, year: u8) -> String {
        format!(":SC{:02}/{:02}/{:02}#", month, day, year % 100)
    }

    /// Set local time (HH:MM:SS).
    pub fn set_time(hour: u8, minute: u8, second: u8) -> String {
        format!(":SL{:02}:{:02}:{:02}#", hour, minute, second)
    }

    /// Set UTC offset (hours from UTC, -12 to +12).
    pub fn set_timezone(offset: i8) -> String {
        let sign = if offset >= 0 { '+' } else { '-' };
        format!(":SG{}{:02}#", sign, offset.abs())
    }

    /// Set site latitude from decimal degrees.
    /// Format: sDD*MM
    pub fn set_latitude(latitude: f64) -> String {
        let sign = if latitude >= 0.0 { '+' } else { '-' };
        let total_arcmin = (latitude.abs() * 60.0).round() as u32;
        let degrees = total_arcmin / 60;
        let minutes = total_arcmin % 60;
        format!(":St{}{}*{:02}#", sign, degrees, minutes)
    }

    /// Set site longitude from decimal degrees.
    /// Format: DDD*MM (0-360 range)
    pub fn set_longitude(longitude: f64) -> String {
        // Normalize to 0-360 range if negative
        let lon = if longitude < 0.0 {
            longitude + 360.0
        } else {
            longitude
        };
        let total_arcmin = (lon * 60.0).round() as u32;
        let degrees = total_arcmin / 60;
        let minutes = total_arcmin % 60;
        format!(":Sg{:03}*{:02}#", degrees, minutes)
    }

    // ============================================
    // SETTER COMMANDS - Meridian & Buzzer
    // ============================================

    /// Set meridian action (0 = stop at meridian, 1 = flip at meridian).
    pub fn set_meridian_action(action: u8) -> String {
        format!(":STa{}#", action.min(1))
    }

    /// Set buzzer volume (0-2).
    pub fn set_buzzer_volume(volume: u8) -> String {
        format!(":SBu{}#", volume.min(2))
    }
}

/// Response parser utilities for ZWO mount responses.
pub struct ResponseParser;

impl ResponseParser {
    /// Parse a boolean/acknowledgment response (0 or 1).
    pub fn parse_bool(response: &str) -> Option<bool> {
        let trimmed = response.trim_end_matches('#');
        match trimmed {
            "0" => Some(false),
            "1" => Some(true),
            _ => None,
        }
    }

    /// Parse an RA response in HH:MM:SS format.
    /// Returns (hours, minutes, seconds).
    pub fn parse_ra(response: &str) -> Option<(u8, u8, f64)> {
        let trimmed = response.trim_end_matches('#');
        let parts: Vec<&str> = trimmed.split(':').collect();
        if parts.len() >= 3 {
            let hours = parts[0].parse().ok()?;
            let minutes = parts[1].parse().ok()?;
            let seconds = parts[2].parse().ok()?;
            Some((hours, minutes, seconds))
        } else if parts.len() == 2 {
            // HH:MM.T format
            let hours = parts[0].parse().ok()?;
            let min_frac: f64 = parts[1].parse().ok()?;
            let minutes = min_frac.floor() as u8;
            let seconds = min_frac.fract() * 60.0;
            Some((hours, minutes, seconds))
        } else {
            None
        }
    }

    /// Parse a Dec response in sDD*MM:SS format.
    /// Returns (degrees, minutes, seconds) where degrees is signed.
    pub fn parse_dec(response: &str) -> Option<(i16, u8, f64)> {
        let trimmed = response.trim_end_matches('#');

        // Handle sign
        let (sign, rest) = if trimmed.starts_with('+') {
            (1i16, &trimmed[1..])
        } else if trimmed.starts_with('-') {
            (-1i16, &trimmed[1..])
        } else {
            (1i16, trimmed)
        };

        // Split on * or °
        let rest = rest.replace('°', "*");
        let parts: Vec<&str> = rest.split('*').collect();
        if parts.len() < 2 {
            return None;
        }

        let degrees: i16 = parts[0].parse().ok()?;

        // Split remainder on :
        let min_sec: Vec<&str> = parts[1].split(':').collect();
        let minutes: u8 = min_sec[0].parse().ok()?;
        let seconds: f64 = if min_sec.len() > 1 {
            min_sec[1].parse().ok()?
        } else {
            0.0
        };

        Some((sign * degrees, minutes, seconds))
    }

    /// Parse an azimuth response in DDD*MM:SS format.
    /// Returns (degrees, minutes, seconds).
    pub fn parse_azimuth(response: &str) -> Option<(u16, u8, f64)> {
        let trimmed = response.trim_end_matches('#');
        let rest = trimmed.replace('°', "*");
        let parts: Vec<&str> = rest.split('*').collect();

        if parts.len() < 2 {
            return None;
        }

        let degrees: u16 = parts[0].parse().ok()?;
        let min_sec: Vec<&str> = parts[1].split(':').collect();
        let minutes: u8 = min_sec[0].parse().ok()?;
        let seconds: f64 = if min_sec.len() > 1 {
            min_sec[1].parse().ok()?
        } else {
            0.0
        };

        Some((degrees, minutes, seconds))
    }

    /// Parse an altitude response in sDD*MM:SS format.
    /// Returns (degrees, minutes, seconds) where degrees is signed.
    pub fn parse_altitude(response: &str) -> Option<(i8, u8, f64)> {
        let (degrees, minutes, seconds) = Self::parse_dec(response)?;
        Some((degrees as i8, minutes, seconds))
    }

    /// Parse goto response.
    /// Returns Ok(()) if slew started, Err with reason otherwise.
    pub fn parse_goto_response(response: &str) -> Result<(), String> {
        let trimmed = response.trim_end_matches('#');
        match trimmed {
            "0" => Ok(()),
            "1" => Err("Object below horizon".to_string()),
            "2" => Err("Object below minimum elevation".to_string()),
            "4" => Err("Position unreachable".to_string()),
            "5" => Err("Not aligned".to_string()),
            "6" => Err("Outside limits".to_string()),
            "7" | "e7" => Err("Pier side limit".to_string()),
            other => Err(format!("Unknown error: {}", other)),
        }
    }

    /// Parse mount status response from :GU# command.
    /// Returns (tracking, slewing, at_home, mount_mode)
    pub fn parse_status(response: &str) -> (bool, bool, bool, MountMode) {
        let flags = response.trim_end_matches('#');

        let tracking = !flags.contains('n');
        let slewing = !flags.contains('N');
        let at_home = flags.contains('H');
        let mount_mode = if flags.contains('G') {
            MountMode::Equatorial
        } else if flags.contains('Z') {
            MountMode::AltAz
        } else {
            MountMode::Unknown
        };

        (tracking, slewing, at_home, mount_mode)
    }

    /// Parse tracking status response (0 or 1).
    pub fn parse_tracking_status(response: &str) -> Option<bool> {
        Self::parse_bool(response)
    }
}

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

    #[test]
    fn test_direction_opposite() {
        assert_eq!(Direction::North.opposite(), Direction::South);
        assert_eq!(Direction::South.opposite(), Direction::North);
        assert_eq!(Direction::East.opposite(), Direction::West);
        assert_eq!(Direction::West.opposite(), Direction::East);
    }

    #[test]
    fn test_slew_rate() {
        assert_eq!(SlewRate::GUIDE.value(), 0);
        assert_eq!(SlewRate::MAX.value(), 9);
        assert_eq!(SlewRate::new(10).value(), 9); // Clamped
        assert_eq!(SlewRate::new(5).value(), 5);
    }

    #[test]
    fn test_set_target_ra() {
        let cmd = Protocol::set_target_ra(12, 30, 45);
        assert_eq!(cmd, ":Sr12:30:45#");
    }

    #[test]
    fn test_set_target_ra_decimal() {
        let cmd = Protocol::set_target_ra_decimal(12.5);
        assert_eq!(cmd, ":Sr12:30:00#");
    }

    #[test]
    fn test_set_target_dec() {
        let cmd = Protocol::set_target_dec(45, 30, 15);
        assert_eq!(cmd, ":Sd+45*30:15#");

        let cmd = Protocol::set_target_dec(-23, 26, 21);
        assert_eq!(cmd, ":Sd-23*26:21#");
    }

    #[test]
    fn test_set_target_dec_decimal() {
        let cmd = Protocol::set_target_dec_decimal(45.5);
        assert_eq!(cmd, ":Sd+45*30:00#");

        let cmd = Protocol::set_target_dec_decimal(-23.5);
        assert_eq!(cmd, ":Sd-23*30:00#");
    }

    #[test]
    fn test_guide_pulse() {
        let cmd = Protocol::guide_pulse_north(500);
        assert_eq!(cmd, ":Mgn0500#");

        let cmd = Protocol::guide_pulse(Direction::East, 150);
        assert_eq!(cmd, ":Mge0150#");
    }

    #[test]
    fn test_set_slew_rate() {
        let cmd = Protocol::set_slew_rate(SlewRate::MAX);
        assert_eq!(cmd, ":R9#");

        let cmd = Protocol::set_slew_rate(SlewRate::GUIDE);
        assert_eq!(cmd, ":R0#");
    }

    #[test]
    fn test_set_latitude() {
        let cmd = Protocol::set_latitude(46.5);
        assert_eq!(cmd, ":St+46*30#");

        let cmd = Protocol::set_latitude(-33.75);
        assert_eq!(cmd, ":St-33*45#");
    }

    #[test]
    fn test_set_longitude() {
        let cmd = Protocol::set_longitude(6.25);
        assert_eq!(cmd, ":Sg006*15#");

        // Negative longitude should be normalized to 0-360
        let cmd = Protocol::set_longitude(-118.5);
        assert_eq!(cmd, ":Sg241*30#");
    }

    #[test]
    fn test_parse_bool() {
        assert_eq!(ResponseParser::parse_bool("0#"), Some(false));
        assert_eq!(ResponseParser::parse_bool("1#"), Some(true));
        assert_eq!(ResponseParser::parse_bool("invalid"), None);
    }

    #[test]
    fn test_parse_ra() {
        let (h, m, s) = ResponseParser::parse_ra("12:30:45#").unwrap();
        assert_eq!(h, 12);
        assert_eq!(m, 30);
        assert!((s - 45.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_dec() {
        let (d, m, s) = ResponseParser::parse_dec("+45*30:15#").unwrap();
        assert_eq!(d, 45);
        assert_eq!(m, 30);
        assert!((s - 15.0).abs() < 0.001);

        let (d, m, s) = ResponseParser::parse_dec("-23*26:21#").unwrap();
        assert_eq!(d, -23);
        assert_eq!(m, 26);
        assert!((s - 21.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_goto_response() {
        assert!(ResponseParser::parse_goto_response("0#").is_ok());
        assert!(ResponseParser::parse_goto_response("1#").is_err());
        assert!(ResponseParser::parse_goto_response("7#").is_err());
    }

    #[test]
    fn test_parse_status() {
        // Tracking, not slewing, not at home, equatorial
        let (tracking, slewing, at_home, mode) = ResponseParser::parse_status("NG#");
        assert!(tracking);
        assert!(!slewing);
        assert!(!at_home);
        assert_eq!(mode, MountMode::Equatorial);

        // Not tracking, not slewing, at home, alt-az
        let (tracking, slewing, at_home, mode) = ResponseParser::parse_status("nNHZ#");
        assert!(!tracking);
        assert!(!slewing);
        assert!(at_home);
        assert_eq!(mode, MountMode::AltAz);
    }

    #[test]
    fn test_tracking_commands() {
        assert_eq!(Protocol::set_tracking_rate(TrackingRate::Sidereal), ":TQ#");
        assert_eq!(Protocol::set_tracking_rate(TrackingRate::Lunar), ":TL#");
        assert_eq!(Protocol::set_tracking_rate(TrackingRate::Solar), ":TS#");
        assert_eq!(Protocol::set_tracking_rate(TrackingRate::Off), ":Td#");
    }

    #[test]
    fn test_set_target_azimuth() {
        assert_eq!(Protocol::set_target_azimuth(180, 30, 45), ":Sz180*30:45#");
        assert_eq!(Protocol::set_target_azimuth(0, 0, 0), ":Sz000*00:00#");
        assert_eq!(Protocol::set_target_azimuth(359, 59, 59), ":Sz359*59:59#");
    }

    #[test]
    fn test_set_target_azimuth_decimal() {
        assert_eq!(Protocol::set_target_azimuth_decimal(180.0), ":Sz180*00:00#");
        assert_eq!(Protocol::set_target_azimuth_decimal(90.5), ":Sz090*30:00#");
        assert_eq!(Protocol::set_target_azimuth_decimal(0.0), ":Sz000*00:00#");
        // Test negative wrapping
        assert_eq!(Protocol::set_target_azimuth_decimal(-90.0), ":Sz270*00:00#");
    }

    #[test]
    fn test_set_target_altitude() {
        assert_eq!(Protocol::set_target_altitude(45, 30, 15), ":Sa+45*30:15#");
        assert_eq!(Protocol::set_target_altitude(-10, 15, 30), ":Sa-10*15:30#");
        assert_eq!(Protocol::set_target_altitude(0, 0, 0), ":Sa+0*00:00#");
        assert_eq!(Protocol::set_target_altitude(90, 0, 0), ":Sa+90*00:00#");
    }

    #[test]
    fn test_set_target_altitude_decimal() {
        assert_eq!(Protocol::set_target_altitude_decimal(45.0), ":Sa+45*00:00#");
        assert_eq!(
            Protocol::set_target_altitude_decimal(-10.5),
            ":Sa-10*30:00#"
        );
        assert_eq!(Protocol::set_target_altitude_decimal(0.0), ":Sa+0*00:00#");
        assert_eq!(Protocol::set_target_altitude_decimal(90.0), ":Sa+90*00:00#");
    }
}