greaseweazle 0.2.0

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

use byteorder::{LE, ReadBytesExt, WriteBytesExt as _};
use num_enum::{FromPrimitive, IntoPrimitive};
use serialport::{ClearBuffer, SerialPort, SerialPortInfo, SerialPortType, UsbPortInfo};
use std::{
    borrow::Cow,
    error::Error,
    fmt,
    io::{self, BufRead, BufReader, Read, Write as _},
    time::Duration,
};
pub use {config::*, flux::*};

mod config;
mod flux;

/// The connection to the Greaseweazle device.
///
/// The Greaseweazle does not handle multiple connections, and creating more than one
/// `Greaseweazle` object for the same device will probably result in errors.
#[derive(Debug)]
pub struct Greaseweazle {
    serial: BufReader<Box<dyn SerialPort>>,
    write_buf: Vec<u8>,
}

impl Greaseweazle {
    /// Creates a new connection to the Greaseweazle device, using the serial port located at the
    /// given `serial_path`.
    ///
    /// This does not check whether the device connected to the serial port is in fact a
    /// Greaseweazle. You should call [`get_firmware_info`](Self::get_firmware_info) after creating
    /// a connection, to ensure that the device accepts Greaseweazle commands and responds as
    /// expected.
    pub fn new<'a>(serial_path: impl Into<Cow<'a, str>>) -> Result<Self, io::Error> {
        let mut serial = serialport::new(serial_path, BaudRate::ClearComms.into())
            .timeout(Duration::from_secs(60))
            .dtr_on_open(true)
            .open()?;

        serial.set_baud_rate(BaudRate::Normal.into())?;
        serial.clear(ClearBuffer::All)?;
        serial.write_request_to_send(true)?;

        Ok(Self {
            serial: BufReader::new(serial),
            write_buf: Vec::with_capacity(1024),
        })
    }

    /// Returns a reference to the internal serial port.
    #[inline]
    pub fn serial(&self) -> &dyn SerialPort {
        self.serial.get_ref().as_ref()
    }

    /// Returns a mutable reference to the internal serial port. This can be used for raw
    /// communication with the Greaseweazle.
    ///
    /// You can send invalid data this way, which may disrupt future commands and require creating
    /// a new connection. Use with care.
    #[inline]
    pub fn serial_mut(&mut self) -> &mut dyn SerialPort {
        self.serial.get_mut().as_mut()
    }

    /// Resets the Greaseweazle to its default state when first powered on.
    pub fn reset(&mut self) -> Result<(), CommandError> {
        self.send_command(Command::Reset, |_write| Ok(()))
    }

    // *** Configuration ***

    /// Returns information about the hardware and firmware of the Greaseweazle device.
    pub fn get_firmware_info(&mut self) -> Result<FirmwareInfo, CommandError> {
        self.send_command(Command::GetInfo, |write| {
            write.write_u8(GetInfo::Firmware.into())?;
            Ok(())
        })?;

        let mut buf = [0; 32];
        self.serial.read_exact(&mut buf)?;
        FirmwareInfo::read_from(buf.as_slice()).map_err(Into::into)
    }

    /// Sets the floppy bus type for future commands.
    pub fn set_bus_type(&mut self, bus_type: BusType) -> Result<(), CommandError> {
        self.send_command(Command::SetBusType, |write| {
            write.write_u8(bus_type.into())?;
            Ok(())
        })
    }

    /// Returns information about the specified drive, or the currently selected drive if
    /// not specified.
    ///
    /// You must have called [`set_bus_type`](Self::set_bus_type) first, and `drive_num` must be
    /// a valid drive number for the selected bus type. If `drive_num` is `None`, you must also
    /// have called [`select_drive`](Self::select_drive) first.
    pub fn get_drive_info(&mut self, drive_num: Option<u8>) -> Result<DriveInfo, CommandError> {
        if let Some(drive_num) = drive_num {
            let code = u8::from(GetInfo::Drive)
                .checked_add(drive_num)
                .ok_or(GreaseweazleError::InvalidDriveNumber)?;
            self.send_command(Command::GetInfo, |write| {
                write.write_u8(code)?;
                Ok(())
            })?;
        } else {
            self.send_command(Command::GetInfo, |write| {
                write.write_u8(GetInfo::CurrentDrive.into())?;
                Ok(())
            })?;
        }

        let mut buf = [0; 32];
        self.serial.read_exact(&mut buf)?;
        DriveInfo::read_from(buf.as_slice()).map_err(Into::into)
    }

    /// Returns the current delay/timing settings.
    pub fn get_delays(&mut self) -> Result<Delays, CommandError> {
        let mut value_count = 8;

        // Older firmware does not support all values, so if an error is returned,
        // incrementally ask for fewer values.
        while let Err(err) = self.send_command(Command::GetParams, |write| {
            write.write_u8(Param::Delays.into())?;
            write.write_u8(value_count * 2)?;
            Ok(())
        }) {
            if value_count > 5
                && matches!(
                    err,
                    CommandError::GreaseweazleError(GreaseweazleError::BadCommand)
                )
            {
                value_count -= 1;
            } else {
                return Err(err);
            }
        }

        Ok(Delays {
            select_us: self.serial.read_u16::<LE>()?,
            step_us: self.serial.read_u16::<LE>()?,
            seek_settle_ms: self.serial.read_u16::<LE>()?,
            motor_ms: self.serial.read_u16::<LE>()?,
            watchdog_ms: self.serial.read_u16::<LE>()?,
            pre_write_us: if value_count >= 6 {
                Some(self.serial.read_u16::<LE>()?)
            } else {
                None
            },
            post_write_us: if value_count >= 7 {
                Some(self.serial.read_u16::<LE>()?)
            } else {
                None
            },
            index_mask_us: if value_count >= 8 {
                Some(self.serial.read_u16::<LE>()?)
            } else {
                None
            },
        })
    }

    /// Sets new delay/timing settings.
    pub fn set_delays(&mut self, delays: Delays) -> Result<(), CommandError> {
        self.send_command(Command::SetParams, |write| {
            write.write_u8(Param::Delays.into())?;

            let Delays {
                select_us: select,
                step_us: step,
                seek_settle_ms: seek_settle,
                motor_ms: motor,
                watchdog_ms: watchdog,
                pre_write_us: pre_write,
                post_write_us: post_write,
                index_mask_us: index_mask,
            } = delays;

            write.write_u16::<LE>(select)?;
            write.write_u16::<LE>(step)?;
            write.write_u16::<LE>(seek_settle)?;
            write.write_u16::<LE>(motor)?;
            write.write_u16::<LE>(watchdog)?;

            let Some(pre_write) = pre_write else {
                return Ok(());
            };
            write.write_u16::<LE>(pre_write)?;

            let Some(post_write) = post_write else {
                return Ok(());
            };
            write.write_u16::<LE>(post_write)?;

            let Some(index_mask) = index_mask else {
                return Ok(());
            };
            write.write_u16::<LE>(index_mask)?;

            Ok(())
        })
    }

    // *** Control ***

    /// Returns whether a pin on the floppy interface is high.
    pub fn get_pin(&mut self, pin: Pin) -> Result<PinLevel, CommandError> {
        self.send_command(Command::GetPin, |write| {
            write.write_u8(pin.into())?;
            Ok(())
        })?;

        Ok(self.serial.read_u8()?.into())
    }

    /// Sets the level of a pin on the floppy interface.
    pub fn set_pin(&mut self, pin: Pin, level: PinLevel) -> Result<(), CommandError> {
        self.send_command(Command::SetPin, |write| {
            write.write_u8(pin.into())?;
            write.write_u8(level.into())?;
            Ok(())
        })
    }

    /// Selects the drive that future commands should be sent to. If `drive_num` is `None`,
    /// deselects all drives.
    ///
    /// You must have called [`set_bus_type`](Self::set_bus_type) first, and `drive_num` must be
    /// a valid drive number for the selected bus type.
    pub fn select_drive(&mut self, drive_num: Option<u8>) -> Result<(), CommandError> {
        if let Some(drive_num) = drive_num {
            self.send_command(Command::Select, |write| {
                write.write_u8(drive_num)?;
                Ok(())
            })
        } else {
            self.send_command(Command::Deselect, |_write| Ok(()))
        }
    }

    /// Selects which head on the drive should be used for future read/write commands.
    ///
    /// Head `0` is the bottom head, head `1` is the top head. Other values will probably result in
    /// an error.
    pub fn select_head(&mut self, head: u8) -> Result<(), CommandError> {
        self.send_command(Command::Head, |write| {
            write.write_u8(head)?;
            Ok(())
        })
    }

    /// Sets the state of the drive motor for the drive.
    ///
    /// You must have called [`set_bus_type`](Self::set_bus_type) first, and `drive_num` must be
    /// a valid drive number for the selected bus type.
    pub fn set_drive_motor(&mut self, drive_num: u8, on: bool) -> Result<(), CommandError> {
        self.send_command(Command::Motor, |write| {
            write.write_u8(drive_num)?;
            write.write_u8(on.into())?;
            Ok(())
        })
    }

    /// Seeks the head to the specified cylinder.
    ///
    /// You must have called [`set_bus_type`](Self::set_bus_type) and
    /// [`select_drive`](Self::select_drive) first. Negative numbers for `cylinder` are supported
    /// for "flippy" drives. For normal drives, you should use only non-negative values.
    ///
    /// After seeking, you can call [`get_pin`](Self::get_pin) with [`Pin::Track0`] to ensure that
    /// the track 0 indicator has the expected state.
    ///
    /// # Notes on Greaseweazle record-keeping
    ///
    /// The Greaseweazle internally keeps a record of the cylinder that the head is currently on,
    /// and updates it when seeking. However, this is not perfect, and can be disrupted if you seek
    /// to an invalid cylinder (beyond the capabilities of the drive), if the Greaseweazle loses
    /// contact with the drive, or if the drive seeks on its own without being told to
    /// (some drives do this when first powered on).
    ///
    /// When first powered on, the Greaseweazle will always seek down on each drive until the
    /// drive indicates track 0. If, during operation, the Greaseweazle has lost track of
    /// the head position, you can call [`reset`](Self::reset) to let it recalibrate.
    pub fn seek(&mut self, cylinder: i16) -> Result<(), CommandError> {
        if let Ok(cylinder) = i8::try_from(cylinder) {
            self.send_command(Command::Seek, |write| {
                write.write_i8(cylinder)?;
                Ok(())
            })
        } else {
            self.send_command(Command::Seek, |write| {
                write.write_i16::<LE>(cylinder)?;
                Ok(())
            })
        }
    }

    /// Seeks the head to cylinder 0, then attempts to step down by one cylinder.
    ///
    /// For most drives, this is equivalent to simply seeking to cylinder 0 directly, as stepping
    /// down from cylinder 0 is not possible. However, some flippy-modded drives erroneously do not
    /// indicate track 0 when they step upwards from cylinder -1. This command exists to correct
    /// for those.
    pub fn no_click_step(&mut self) -> Result<(), CommandError> {
        self.send_command(Command::NoClickStep, |_write| Ok(()))
    }

    // *** Flux ***

    /// Reads flux from the currently selected drive, head and cylinder.
    /// The drive motor must be on for this to work.
    ///
    /// Reading continues for the specified duration or the specified number of index pulses,
    /// whichever limit is reached first.
    /// Specifying `0` for either of these values means no limit is set.
    pub fn read_flux(
        &mut self,
        duration: Ticks,
        indexes: u16,
    ) -> Result<EncodedFlux, CommandError> {
        self.send_command(Command::ReadFlux, |write| {
            write.write_u32::<LE>(duration.into())?;
            write.write_u16::<LE>(indexes)?;
            Ok(())
        })?;

        let mut buf = Vec::new();
        self.serial.read_until(0, &mut buf)?;
        self.send_command(Command::GetFluxStatus, |_write| Ok(()))?;

        Ok(EncodedFlux::from_encoded_bytes(buf))
    }

    /// Writes flux to the currently selected drive, head and cylinder.
    /// The drive motor must be on for this to work.
    ///
    /// If `start_at_index` is `true`, writing starts when the next index pulse occurs,
    /// otherwise writing starts immediately. Writing ends when all the provided flux is written.
    /// If `stop_at_index` is `true`, writing ends earlier if an index pulse occurs first, and
    /// the remaining flux is discarded.
    ///
    /// `hard_sector_period`, if not `0`, specifies that the disk is hard-sectored, and the
    /// Greaseweazle should expect sector pulses at roughly this interval.
    /// This helps the Greaseweazle distinguish between sector holes and index holes.
    pub fn write_flux(
        &mut self,
        flux: &EncodedFlux,
        start_at_index: bool,
        stop_at_index: bool,
        hard_sector_period: Ticks,
    ) -> Result<(), CommandError> {
        if hard_sector_period.0 == 0 {
            self.send_command(Command::WriteFlux, |write| {
                write.write_u8(start_at_index.into())?;
                write.write_u8(stop_at_index.into())?;
                Ok(())
            })?;
        } else {
            self.send_command(Command::WriteFlux, |write| {
                write.write_u8(start_at_index.into())?;
                write.write_u8(stop_at_index.into())?;
                write.write_u32::<LE>(hard_sector_period.into())?;
                Ok(())
            })?;
        }

        self.serial.get_mut().write_all(flux.as_bytes())?;
        self.serial.read_u8()?; // wait for Greaseweazle to finish
        self.send_command(Command::GetFluxStatus, |_write| Ok(()))?;

        Ok(())
    }

    /// Erases flux on the currently selected drive, head and cylinder, for the specified duration.
    /// The drive motor must be on for this to work.
    pub fn erase_flux(&mut self, duration: Ticks) -> Result<(), CommandError> {
        self.send_command(Command::EraseFlux, |write| {
            write.write_u32::<LE>(duration.into())?;
            Ok(())
        })?;

        self.serial.read_u8()?; // wait for Greaseweazle to finish
        self.send_command(Command::GetFluxStatus, |_write| Ok(()))?;

        Ok(())
    }

    // *** Bandwidth ***

    /// Receives randomly generated bytes from the Greaseweazle.
    ///
    /// This is used for the [`get_bandwidth_stats`](Self::get_bandwidth_stats) command.
    pub fn source_bytes(&mut self, buf: &mut [u8], seed: u32) -> Result<(), CommandError> {
        self.send_command(Command::SourceBytes, |write| {
            write.write_u32::<LE>(buf.len().try_into().expect("buffer was too long"))?;
            write.write_u32::<LE>(seed)?;
            Ok(())
        })?;

        self.serial.read_exact(buf).map_err(Into::into)
    }

    /// Sends randomly generated bytes to the Greaseweazle.
    ///
    /// This is used for the [`get_bandwidth_stats`](Self::get_bandwidth_stats) command.
    pub fn sink_bytes(&mut self, buf: &[u8], seed: u32) -> Result<(), CommandError> {
        self.send_command(Command::SinkBytes, |write| {
            write.write_u32::<LE>(buf.len().try_into().expect("buffer was too long"))?;
            write.write_u32::<LE>(seed)?;
            Ok(())
        })?;

        self.serial.get_mut().write_all(buf)?;
        let ack_code = self.serial.read_u8()?;

        if ack_code != 0 {
            return Err(GreaseweazleError::from(ack_code).into());
        }

        Ok(())
    }

    /// Gets bandwidth statistics after calling [`source_bytes`](Self::source_bytes) and/or
    /// [`sink_bytes`](Self::sink_bytes).
    pub fn get_bandwidth_stats(&mut self) -> Result<BandwidthStats, CommandError> {
        self.send_command(Command::GetInfo, |write| {
            write.write_u8(GetInfo::BandwidthStats.into())?;
            Ok(())
        })?;

        let mut buf = [0; 32];
        self.serial.read_exact(&mut buf)?;
        BandwidthStats::read_from(buf.as_slice()).map_err(Into::into)
    }

    fn send_command(
        &mut self,
        command: Command,
        write_data: impl FnOnce(&mut Vec<u8>) -> Result<(), io::Error>,
    ) -> Result<(), CommandError> {
        let sent_command = u8::from(command);

        self.write_buf.clear();
        self.write_buf.write_u8(sent_command)?;
        self.write_buf.write_u8(0)?;
        write_data(&mut self.write_buf)?;
        self.write_buf[1] = self
            .write_buf
            .len()
            .try_into()
            .expect("command was too long");

        let serial = self.serial.get_mut();
        serial.write_all(&self.write_buf)?;
        serial.flush()?;

        #[cfg(feature = "log")]
        log::trace!("Sent command `{command:?}` with data: {:?}", self.write_buf);

        let mut response = [0; 2];
        self.serial.read_exact(&mut response)?;
        let mut response = response.as_slice();
        let received_command = response.read_u8()?;

        let result = match response.read_u8()? {
            0 => {
                #[cfg(feature = "log")]
                log::trace!("Received command `{received_command:?}` response `Ok`");
                Ok(())
            }
            code => {
                let err = GreaseweazleError::from(code);
                #[cfg(feature = "log")]
                log::trace!("Received command `{received_command:?}` response `{err:?}`");
                Err(err.into())
            }
        };

        if received_command != sent_command {
            return Err(CommandError::ResponseCommandMismatch {
                sent_command,
                received_command,
            });
        }

        result
    }
}

/// Error that can occur when executing a Greaseweazle command.
#[derive(Debug)]
#[non_exhaustive]
pub enum CommandError {
    /// An I/O error occurred while sending/receiving data.
    IoError(io::Error),

    /// The Greaseweazle responded with an error code.
    GreaseweazleError(GreaseweazleError),

    /// The command code returned by the Greaseweazle does not match the code of the command that
    /// was sent.
    ///
    /// This may indicate that the communication with the Greaseweazle has gone out of sync,
    /// and requires recreating the connection. It may also happen if the connected device is not
    /// actually a Greaseweazle.
    ResponseCommandMismatch {
        /// The command code that was sent to the Greaseweazle.
        sent_command: u8,

        /// The command code that was received back from the Greaseweazle.
        received_command: u8,
    },
}

impl fmt::Display for CommandError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            Self::IoError(_) => {
                write!(f, "an I/O error occurred while sending/receiving data")
            }
            Self::GreaseweazleError(_) => {
                write!(f, "the Greaseweazle responded with an error code")
            }
            Self::ResponseCommandMismatch { .. } => {
                write!(
                    f,
                    "the command code returned by the Greaseweazle does not match the code of the \
                    command that was sent."
                )
            }
        }
    }
}

impl Error for CommandError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::IoError(error) => Some(error),
            Self::GreaseweazleError(error) => Some(error),
            Self::ResponseCommandMismatch { .. } => None,
        }
    }
}

impl From<io::Error> for CommandError {
    fn from(value: io::Error) -> Self {
        Self::IoError(value)
    }
}

impl From<GreaseweazleError> for CommandError {
    fn from(value: GreaseweazleError) -> Self {
        Self::GreaseweazleError(value)
    }
}

/// An error code that can be returned by the Greaseweazle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, IntoPrimitive)]
#[non_exhaustive]
#[repr(u8)]
pub enum GreaseweazleError {
    /// Bad command.
    BadCommand = 1,

    /// No index.
    NoIndex = 2,

    /// Track 0 not found.
    NoTrack0 = 3,

    /// Flux overflow.
    FluxOverflow = 4,

    /// Flux underflow.
    FluxUnderflow = 5,

    /// Disk is write protected.
    WriteProtected = 6,

    /// No drive selected
    /// (using [`select_drive`](Greaseweazle::select_drive)).
    NoDriveSelected = 7,

    /// No bus type selected
    /// (using [`set_bus_type`](Greaseweazle::set_bus_type)).
    NoBusTypeSelected = 8,

    /// Invalid drive number.
    InvalidDriveNumber = 9,

    /// Invalid pin.
    InvalidPin = 10,

    /// Invalid cylinder.
    InvalidCylinder = 11,

    /// Out of SRAM.
    OutOfSram = 12,

    /// Out of flash.
    OutOfFlash = 13,

    /// Unknown error.
    #[num_enum(catch_all)]
    Unknown(u8),
}

/// Returns a list of all Greaseweazle devices that can be found on the system.
///
/// # Linux note
///
/// On Linux, this uses standard system APIs, but may give better results by using the `udev`
/// library. To use it, enable the `libudev` feature on this crate.
pub fn enumerate() -> Result<Vec<SerialPortInfo>, io::Error> {
    let mut infos = serialport::available_ports()?;

    infos.retain(|info| {
        let SerialPortType::UsbPort(info) = &info.port_type else {
            return false;
        };

        let &UsbPortInfo {
            vid,
            pid,
            ref serial_number,
            ref manufacturer,
            ref product,
        } = info;

        if vid == 0x1209 {
            if pid == 0x4d69 {
                return true;
            }

            if pid == 0x0001
                && serial_number
                    .as_deref()
                    .is_some_and(|serial_number| serial_number.starts_with("GW"))
            {
                return true;
            }
        }

        if let Some(product) = product {
            if product == "Greaseweazle" && manufacturer.as_deref() == Some("Keir Fraser") {
                return true;
            }

            if product.to_ascii_lowercase().contains("gw-compat") {
                return true;
            }
        }

        false
    });

    Ok(infos)
}

/// A time duration expressed in Greaseweazle sample ticks.
///
/// A sample tick is a time unit equal to the period of a sample.
/// There are [`FirmwareInfo::sample_freq`] sample ticks in a second, and one sample tick is
/// `1.0 / sample_freq` seconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Ticks(pub u32);

impl Ticks {
    /// Converts `duration` to sample ticks, with the provided sample frequency.
    ///
    /// Panics if overflow occurs.
    #[inline]
    pub fn from_duration(duration: Duration, sample_freq: u32) -> Self {
        Self::try_from_duration(duration, sample_freq).expect("overflow occurred")
    }

    /// Tries to convert `duration` to sample ticks, with the provided sample frequency.
    ///
    /// Returns `None` if the value is too big to fit in a `u32`. The conversion is lossless if
    /// `duration` is an exact multiple of the tick duration for `sample_freq`.
    #[inline]
    pub fn try_from_duration(duration: Duration, sample_freq: u32) -> Option<Self> {
        Some(Self(
            u32::try_from(duration.saturating_mul(sample_freq).as_secs()).ok()?,
        ))
    }

    /// Converts sample ticks to a `Duration`, with the provided sample frequency.
    ///
    /// Rounding errors may occur during division.
    #[inline]
    pub fn to_duration(self, sample_freq: u32) -> Duration {
        Duration::from_secs(self.0.into()) / sample_freq
    }
}

impl From<u32> for Ticks {
    #[inline]
    fn from(value: u32) -> Self {
        Self(value)
    }
}

impl From<Ticks> for u32 {
    #[inline]
    fn from(value: Ticks) -> Self {
        value.0
    }
}

impl fmt::Display for GreaseweazleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            Self::BadCommand => write!(f, "bad command"),
            Self::NoIndex => write!(f, "no index"),
            Self::NoTrack0 => write!(f, "track 0 not found"),
            Self::FluxOverflow => write!(f, "flux overflow"),
            Self::FluxUnderflow => write!(f, "flux underflow"),
            Self::WriteProtected => write!(f, "disk is write protected"),
            Self::NoDriveSelected => write!(f, "no drive selected"),
            Self::NoBusTypeSelected => write!(f, "no bus type selected"),
            Self::InvalidDriveNumber => write!(f, "invalid drive number"),
            Self::InvalidPin => write!(f, "invalid pin"),
            Self::InvalidCylinder => write!(f, "invalid cylinder"),
            Self::OutOfSram => write!(f, "out of SRAM"),
            Self::OutOfFlash => write!(f, "out of flash"),
            Self::Unknown(code) => write!(f, "unknown error {code}"),
        }
    }
}

impl Error for GreaseweazleError {}

/// A pin on the floppy interface of the Greaseweazle.
///
/// This type contains only pins that can be used with [`get_pin`](Greaseweazle::get_pin) and
/// [`set_pin`](Greaseweazle::set_pin). Some pins have two or more incompatible functions,
/// depending on the drive and how it's configured, and there may be more obscure drives with yet
/// other functions not mentioned here.
#[derive(Debug, Clone, Copy, FromPrimitive, IntoPrimitive)]
#[non_exhaustive]
#[repr(u8)]
pub enum Pin {
    /// Can be set.
    ///
    /// - **Density select**:
    ///   - [`Low`] = High density.
    ///   - [`High`] = Low density.
    /// - **Head load**: This function is used on some early floppy drives.
    ///   - [`Low`] = The head is pressed down onto the disk, ready for reading/writing.
    ///   - [`High`] = The head is released from the disk.
    ///
    /// [`Low`]: PinLevel::Low
    /// [`High`]: PinLevel::High
    DensitySelect = 2,

    /// Can be set.
    ///
    /// - **Head load**:
    ///   - [`Low`] = The head is pressed down onto the disk, ready for reading/writing.
    ///   - [`High`] = The head is released from the disk.
    /// - **In use**:
    ///   - [`Low`] = The drive is prepared for reading/writing.
    ///     Some drives may lock the door/eject mechanism, but on others, this signal only makes
    ///     the drive light turn on.
    ///
    /// [`Low`]: PinLevel::Low
    /// [`High`]: PinLevel::High
    #[allow(non_camel_case_types)]
    HeadLoad_InUse = 4,

    /// Can be set.
    ///
    /// - **Drive select 3**: This function is used on most floppy drives, but is not present on
    ///   the IBM PC floppy controller.
    ///   - [`Low`] = Selects drive 3. This probably should not be used with the Greaseweazle.
    /// - **Ready**: This function is used on a few early floppy drives.
    ///   - [`Low`] = Disk is inserted and spinning.
    ///
    /// [`Low`]: PinLevel::Low
    #[allow(non_camel_case_types)]
    DriveSelect3 = 6,

    /// Read-only, cannot be set.
    ///
    /// - **Index**:
    ///   - [`Low`] = The index hole is over the index sensor.
    ///
    /// [`Low`]: PinLevel::Low
    Index = 8,

    /// Read-only, cannot be set.
    ///
    /// - **Track 0**:
    ///   - [`Low`] = The head is positioned above cylinder 0.
    ///
    /// [`Low`]: PinLevel::Low
    Track0 = 26,

    /// Read-only, cannot be set.
    ///
    /// - **Write protect**:
    ///   - [`Low`] = The disk is write-protected.
    ///
    /// [`Low`]: PinLevel::Low
    WriteProtect = 28,

    /// Read-only, cannot be set.
    ///
    /// - **Disk change**: This function is used on the IBM PC.
    ///   - [`Low`] = Disk has been changed since the last access.
    /// - **Ready**: This function is used on some non-IBM PC drives.
    ///   - [`Low`] = The disk is inserted and spinning, ready to load the head.
    /// - **In use**: This function is used on a few early floppy drives.
    ///   - [`Low`] = The drive is prepared for reading/writing.
    ///     Some drives may lock the door/eject mechanism, but on others, this signal only makes
    ///     the drive light turn on.
    ///
    /// [`Low`]: PinLevel::Low
    #[allow(non_camel_case_types)]
    DiskChange_Ready = 34,

    /// Other pin.
    ///
    /// This is provided for future extensions of the Greaseweazle.
    #[num_enum(catch_all)]
    Other(u8),
}

/// Possible levels for a pin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, IntoPrimitive)]
#[repr(u8)]
pub enum PinLevel {
    /// Logic low, or 0.
    Low = 0,

    /// Logic high, or 1.
    #[num_enum(default)]
    High = 1,
}

/// Bandwidth statistics.
///
/// Returned by the [`get_bandwidth_stats`](Greaseweazle::get_bandwidth_stats) command.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct BandwidthStats {
    /// The minimum reported bandwidth.
    pub min: Bandwidth,

    /// The maximum reported bandwidth.
    pub max: Bandwidth,
}

impl BandwidthStats {
    pub(crate) fn read_from(mut read: impl Read) -> Result<Self, io::Error> {
        Ok(Self {
            min: Bandwidth::read_from(&mut read)?,
            max: Bandwidth::read_from(&mut read)?,
        })
    }
}

/// Bandwidth value.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct Bandwidth {
    /// Number of bytes transferred.
    pub bytes: u32,

    /// The number of microseconds it took to transfer `bytes` bytes.
    pub per_us: u32,
}

impl Bandwidth {
    fn read_from(mut read: impl Read) -> Result<Self, io::Error> {
        Ok(Self {
            bytes: read.read_u32::<LE>()?,
            per_us: read.read_u32::<LE>()?,
        })
    }

    /// Returns the bandwidth in bits per second.
    #[inline]
    pub const fn as_bits_per_sec(&self) -> f64 {
        self.bytes as f64 / self.per_us as f64 * 8_000_000.0
    }
}

#[derive(IntoPrimitive)]
#[repr(u32)]
pub(crate) enum BaudRate {
    Normal = 9600,
    ClearComms = 10000,
}

#[derive(Debug, Clone, Copy, IntoPrimitive)]
#[non_exhaustive]
#[repr(u8)]
pub(crate) enum Command {
    GetInfo = 0,
    #[allow(dead_code)]
    Update = 1,
    Seek = 2,
    Head = 3,
    SetParams = 4,
    GetParams = 5,
    Motor = 6,
    ReadFlux = 7,
    WriteFlux = 8,
    GetFluxStatus = 9,
    #[allow(dead_code)]
    SwitchFwMode = 11,
    Select = 12,
    Deselect = 13,
    SetBusType = 14,
    SetPin = 15,
    Reset = 16,
    EraseFlux = 17,
    SourceBytes = 18,
    SinkBytes = 19,
    GetPin = 20,
    #[allow(dead_code)]
    TestMode = 21,
    NoClickStep = 22,
}