gallo 0.4.1

Batch mode application to control a Pico de Gallo device
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
//! Command-line interface for the Pico de Gallo USB bridge.
//!
//! The `gallo` CLI provides direct access to I2C, SPI, and GPIO peripherals
//! connected through a Pico de Gallo device. It is built with
//! [clap](https://docs.rs/clap) and supports:
//!
//! - **I2C**: bus scanning, read, write, and write-then-read operations
//! - **SPI**: read, write, full-duplex transfer, and write-then-read
//! - **Configuration**: set I2C/SPI bus frequencies and SPI mode
//! - **Device management**: list connected devices, query firmware version
//!
//! # Examples
//!
//! ```console
//! $ gallo list
//! $ gallo version
//! $ gallo i2c scan
//! $ gallo i2c read -a 0x48 -c 2
//! $ gallo i2c write -a 0x50 -b 0xDE 0xAD
//! $ gallo spi transfer -b 0x01 0x02 0x03
//! $ gallo set-config --i2c-frequency 400000 --spi-frequency 1000000
//! ```
//!
//! # Output Formats
//!
//! Read data can be displayed in three formats via the `-f` / `--format` flag:
//! - `hex` (default): hexadecimal byte dump
//! - `binary`: raw bytes written to stdout
//! - `ascii`: printable characters shown, non-printable replaced with `.`

use clap::{Parser, Subcommand, ValueEnum};
use color_eyre::{Result, eyre::eyre};
use pico_de_gallo_lib::{I2cFrequency, PicoDeGallo, SpiPhase, SpiPolarity, list_devices};
use std::num::ParseIntError;
use tabled::builder::Builder;
use tabled::settings::object::Rows;
use tabled::settings::{Alignment, Style};

/// I2C bus clock frequency for CLI argument parsing.
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum I2cFrequencyArg {
    /// Standard mode — 100 kHz
    Standard,
    /// Fast mode — 400 kHz
    Fast,
    /// Fast+ mode — 1 MHz
    FastPlus,
}

impl From<I2cFrequencyArg> for I2cFrequency {
    fn from(arg: I2cFrequencyArg) -> Self {
        match arg {
            I2cFrequencyArg::Standard => I2cFrequency::Standard,
            I2cFrequencyArg::Fast => I2cFrequency::Fast,
            I2cFrequencyArg::FastPlus => I2cFrequency::FastPlus,
        }
    }
}

/// Output format for data display.
#[derive(clap::ValueEnum, Clone, Debug, Default)]
pub enum OutputFormat {
    /// Hexadecimal byte dump (default)
    #[default]
    Hex,
    /// Raw binary output (bytes written directly to stdout)
    Binary,
    /// ASCII representation (printable chars shown, others as '.')
    Ascii,
}

/// Top-level CLI argument parser.
///
/// Parse with [`clap::Parser::parse`] and execute with [`Cli::run`].
#[derive(Parser, Debug)]
#[command(
    name = "Pico De Gallo",
    author = "Felipe Balbi <febalbi@microsoft.com>",
    about = "Access I2C/SPI devices through Pico De Gallo",
    arg_required_else_help = true,
    version
)]
pub struct Cli {
    #[arg(short, long)]
    serial_number: Option<String>,

    /// Output format for read data
    #[arg(short, long, value_enum, default_value_t)]
    format: OutputFormat,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// List all connected Pico de Gallo devices
    List,

    /// Get firmware version
    Version,

    /// I2C access methods
    I2c {
        /// I2C commands
        #[command(subcommand)]
        command: I2cCommands,
    },

    /// SPI access methods
    Spi {
        /// SPI commands
        #[command(subcommand)]
        command: SpiCommands,
    },
}

#[derive(Subcommand, Debug)]
enum I2cCommands {
    /// Scan I2C bus for existing devices
    Scan {
        /// Attempt reserved addresses
        #[arg(short, long, default_value_t = false)]
        reserved: bool,
    },

    /// Read bytes through the I2C bus from device at given address
    Read {
        /// I2C slave address (7-bit, 0x00–0x7F)
        #[arg(short, long, value_parser(parse_i2c_address))]
        address: u8,

        /// Number of bytes to read
        #[arg(short, long)]
        count: usize,
    },

    /// Write bytes through I2C bus to device at given address
    Write {
        /// I2C slave address (7-bit, 0x00–0x7F)
        #[arg(short, long, value_parser(parse_i2c_address))]
        address: u8,

        /// Bytes to transfer
        #[arg(short, long, num_args(1..), value_parser(parse_byte))]
        bytes: Vec<u8>,
    },

    /// Write bytes follwed by read bytes
    WriteRead {
        /// I2C slave address (7-bit, 0x00–0x7F)
        #[arg(short, long, value_parser(parse_i2c_address))]
        address: u8,

        /// Bytes to transfer
        #[arg(short, long, num_args(1..), value_parser(parse_byte))]
        bytes: Vec<u8>,

        /// Number of bytes to read
        #[arg(short, long)]
        count: usize,
    },

    /// Set I2C bus parameters
    SetConfig {
        /// I2C frequency: standard (100 kHz), fast (400 kHz), fast-plus (1 MHz)
        #[arg(long)]
        frequency: I2cFrequencyArg,
    },
}

#[derive(Subcommand, Debug)]
enum SpiCommands {
    /// Read bytes through SPI bus
    Read {
        /// Number of bytes to read
        #[arg(short, long)]
        count: usize,
    },

    /// Write bytes through SPI bus
    Write {
        /// Bytes to transfer
        #[arg(short, long, num_args(1..), value_parser(parse_byte))]
        bytes: Vec<u8>,
    },

    /// Full-duplex SPI transfer (simultaneous write and read)
    Transfer {
        /// Bytes to send (received data will be the same length)
        #[arg(short, long, num_args(1..), value_parser(parse_byte))]
        bytes: Vec<u8>,
    },

    /// Write bytes followed by read bytes (half-duplex)
    WriteRead {
        /// Number of bytes to read
        #[arg(short, long)]
        count: usize,

        /// Bytes to transfer
        #[arg(short, long, num_args(1..), value_parser(parse_byte))]
        bytes: Vec<u8>,
    },

    /// Set SPI bus parameters
    SetConfig {
        /// SPI frequency in Hz
        #[arg(long)]
        frequency: u32,

        /// SPI phase first transition (CPHA=0)
        #[arg(long, default_value_t)]
        first_transition: bool,

        /// SPI polarity idle low (CPOL=0)
        #[arg(long, default_value_t)]
        idle_low: bool,
    },
}

fn print_data(data: &[u8], format: &OutputFormat) {
    match format {
        OutputFormat::Hex => {
            for (i, b) in data.iter().enumerate() {
                if i > 0 && i % 16 == 0 {
                    println!();
                }
                print!("{:02x} ", b);
            }
            println!();
        }
        OutputFormat::Binary => {
            use std::io::Write;
            std::io::stdout().write_all(data).unwrap();
        }
        OutputFormat::Ascii => {
            for (i, b) in data.iter().enumerate() {
                if i > 0 && i % 16 == 0 {
                    println!();
                }
                let ch = if b.is_ascii_graphic() || *b == b' ' {
                    *b as char
                } else {
                    '.'
                };
                print!("{ch}");
            }
            println!();
        }
    }
}

impl Cli {
    fn connect(&self) -> PicoDeGallo {
        if let Some(serial_number) = &self.serial_number {
            PicoDeGallo::new_with_serial_number(serial_number)
        } else {
            PicoDeGallo::new()
        }
    }

    /// Execute the CLI command.
    ///
    /// Dispatches to the appropriate handler based on the parsed subcommand.
    /// Returns `Ok(())` on success or an error via `color_eyre`.
    pub async fn run(&self) -> Result<()> {
        match &self.command {
            Commands::List => Self::list_devices(),
            Commands::Version => self.version().await,
            Commands::I2c { command } => match command {
                I2cCommands::Scan { reserved } => self.i2c_scan(*reserved).await,
                I2cCommands::Read { address, count } => self.i2c_read(address, count).await,
                I2cCommands::Write { address, bytes } => self.i2c_write(address, bytes).await,
                I2cCommands::WriteRead { address, bytes, count } => {
                    self.i2c_write_then_read(address, bytes, count).await
                }
                I2cCommands::SetConfig { frequency } => self.i2c_set_config((*frequency).into()).await,
            },
            Commands::Spi { command } => match command {
                SpiCommands::Read { count } => self.spi_read(count).await,
                SpiCommands::Write { bytes } => self.spi_write(bytes).await,
                SpiCommands::Transfer { bytes } => self.spi_transfer(bytes).await,
                SpiCommands::WriteRead { count, bytes } => self.spi_write_then_read(bytes, count).await,
                SpiCommands::SetConfig {
                    frequency,
                    first_transition,
                    idle_low,
                } => self.spi_set_config(*frequency, *first_transition, *idle_low).await,
            },
        }
    }

    fn list_devices() -> Result<()> {
        let devices = list_devices();
        if devices.is_empty() {
            println!("No Pico de Gallo devices found.");
            return Ok(());
        }

        for dev in &devices {
            let product = dev.product.as_deref().unwrap_or("(unknown product)");
            let serial = dev.serial_number.as_deref().unwrap_or("(unknown)");
            println!(" - {product} - {serial}");
        }
        Ok(())
    }

    async fn version(&self) -> Result<()> {
        let pg = self.connect();

        match pg.version().await {
            Ok(version) => {
                println!(
                    "Pico de Gallo FW v{}.{}.{}",
                    version.major, version.minor, version.patch
                );
                Ok(())
            }
            Err(_) => Err(eyre!("Failed to get version")),
        }
    }

    async fn i2c_scan(&self, reserved: bool) -> Result<()> {
        let pg = self.connect();

        let mut builder = Builder::with_capacity(17, 8);
        builder.push_record(
            (0..=16)
                .map(|i| if i == 0 { String::new() } else { format!("{:x}", i - 1) })
                .collect::<Vec<_>>(),
        );

        for hi in 0..=7 {
            let mut row = vec![format!("{:x} ", hi)];

            for lo in 0..=15 {
                let address = hi << 4 | lo;
                let stat = match address {
                    0x00..=0x07 | 0x78..=0x7f => {
                        if reserved {
                            match pg.i2c_read(address, 1).await {
                                Ok(_) => format!("{:02x}", address),
                                Err(_) => "--".to_string(),
                            }
                        } else {
                            "RR".to_string()
                        }
                    }
                    _ => match pg.i2c_read(address, 1).await {
                        Ok(_) => format!("{:02x}", address),
                        Err(_) => "--".to_string(),
                    },
                };

                row.push(stat);
            }

            builder.push_record(row);
        }

        let mut table = builder.build();
        table.modify(Rows::first(), Alignment::right());
        table.with(Style::rounded());

        println!("{}", table);

        Ok(())
    }

    async fn i2c_read(&self, address: &u8, count: &usize) -> Result<()> {
        let pg = self.connect();

        let buf = match pg.i2c_read(*address, *count as u16).await {
            Ok(data) => data,
            Err(e) => return Err(eyre!("{:?}", e).wrap_err("i2c_read failed")),
        };

        print_data(&buf, &self.format);

        Ok(())
    }

    async fn i2c_write(&self, address: &u8, bytes: &[u8]) -> Result<()> {
        let pg = self.connect();

        if pg.i2c_write(*address, bytes).await.is_ok() {
            Ok(())
        } else {
            Err(eyre!("i2c_write failed for address {:#04x}", address))
        }
    }

    async fn i2c_write_then_read(&self, address: &u8, bytes: &[u8], count: &usize) -> Result<()> {
        let pg = self.connect();

        let buf = match pg.i2c_write_read(*address, bytes, *count as u16).await {
            Ok(data) => data,
            Err(e) => return Err(eyre!("{:?}", e).wrap_err("i2c_write_read failed")),
        };

        print_data(&buf, &self.format);

        Ok(())
    }

    async fn spi_read(&self, count: &usize) -> Result<()> {
        let pg = self.connect();

        let buf = match pg.spi_read(*count as u16).await {
            Ok(data) => data,
            Err(e) => return Err(eyre!("{:?}", e).wrap_err("spi_read failed")),
        };

        print_data(&buf, &self.format);

        Ok(())
    }

    async fn spi_write(&self, bytes: &[u8]) -> Result<()> {
        let pg = self.connect();

        if pg.spi_write(bytes).await.is_ok() {
            Ok(())
        } else {
            Err(eyre!("spi_write failed"))
        }
    }

    async fn spi_transfer(&self, bytes: &[u8]) -> Result<()> {
        let pg = self.connect();

        let buf = pg
            .spi_transfer(bytes)
            .await
            .map_err(|e| eyre!("{:?}", e).wrap_err("spi_transfer failed"))?;

        print_data(&buf, &self.format);

        Ok(())
    }

    async fn spi_write_then_read(&self, bytes: &[u8], count: &usize) -> Result<()> {
        self.spi_write(bytes).await?;
        self.spi_read(count).await
    }

    async fn i2c_set_config(&self, frequency: I2cFrequency) -> Result<()> {
        let pg = self.connect();

        pg.i2c_set_config(frequency)
            .await
            .map_err(|e| eyre!("{:?}", e).wrap_err("i2c set-config failed"))
    }

    async fn spi_set_config(&self, frequency: u32, first_transition: bool, idle_low: bool) -> Result<()> {
        let pg = self.connect();

        let spi_polarity = if idle_low {
            SpiPolarity::IdleLow
        } else {
            SpiPolarity::IdleHigh
        };

        let spi_phase = if first_transition {
            SpiPhase::CaptureOnFirstTransition
        } else {
            SpiPhase::CaptureOnSecondTransition
        };

        pg.spi_set_config(frequency, spi_phase, spi_polarity)
            .await
            .map_err(|e| eyre!("{:?}", e).wrap_err("spi set-config failed"))
    }
}

fn parse_byte(s: &str) -> Result<u8, ParseIntError> {
    if let Some(hex) = s.strip_prefix("0x") {
        u8::from_str_radix(hex, 16)
    } else if let Some(bin) = s.strip_prefix("0b") {
        u8::from_str_radix(bin, 2)
    } else {
        s.parse::<u8>()
    }
}

/// Parse an I2C 7-bit address (0x00–0x7F).
fn parse_i2c_address(s: &str) -> Result<u8, String> {
    let byte = parse_byte(s).map_err(|e| e.to_string())?;
    if byte > 0x7F {
        return Err(format!("I2C address {s} exceeds 7-bit range (max 0x7F)"));
    }
    Ok(byte)
}

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

    // ----------------------------- parse_byte tests -----------------------------

    #[test]
    fn parse_byte_decimal() {
        assert_eq!(parse_byte("0").unwrap(), 0);
        assert_eq!(parse_byte("255").unwrap(), 255);
        assert_eq!(parse_byte("42").unwrap(), 42);
    }

    #[test]
    fn parse_byte_hex() {
        assert_eq!(parse_byte("0x00").unwrap(), 0x00);
        assert_eq!(parse_byte("0xFF").unwrap(), 0xFF);
        assert_eq!(parse_byte("0x48").unwrap(), 0x48);
        assert_eq!(parse_byte("0xab").unwrap(), 0xAB);
    }

    #[test]
    fn parse_byte_binary() {
        assert_eq!(parse_byte("0b00000000").unwrap(), 0);
        assert_eq!(parse_byte("0b11111111").unwrap(), 255);
        assert_eq!(parse_byte("0b10101010").unwrap(), 0xAA);
    }

    #[test]
    fn parse_byte_overflow_fails() {
        assert!(parse_byte("256").is_err());
        assert!(parse_byte("0x100").is_err());
        assert!(parse_byte("0b100000000").is_err());
    }

    #[test]
    fn parse_byte_invalid_fails() {
        assert!(parse_byte("xyz").is_err());
        assert!(parse_byte("0xGG").is_err());
        assert!(parse_byte("0b2").is_err());
        assert!(parse_byte("").is_err());
    }

    // ----------------------------- CLI parsing tests -----------------------------

    #[test]
    fn cli_no_args_requires_help() {
        // arg_required_else_help = true means no-args should fail
        let result = Cli::try_parse_from(["gallo"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_version_subcommand() {
        let cli = Cli::try_parse_from(["gallo", "version"]).unwrap();
        assert!(matches!(cli.command, Commands::Version));
        assert!(cli.serial_number.is_none());
    }

    #[test]
    fn cli_list_subcommand() {
        let cli = Cli::try_parse_from(["gallo", "list"]).unwrap();
        assert!(matches!(cli.command, Commands::List));
    }

    #[test]
    fn cli_version_with_serial() {
        let cli = Cli::try_parse_from(["gallo", "-s", "ABCD1234", "version"]).unwrap();
        assert_eq!(cli.serial_number.as_deref(), Some("ABCD1234"));
        assert!(matches!(cli.command, Commands::Version));
    }

    #[test]
    fn cli_i2c_read() {
        let cli = Cli::try_parse_from(["gallo", "i2c", "read", "-a", "0x48", "-c", "4"]).unwrap();
        match cli.command {
            Commands::I2c {
                command: I2cCommands::Read { address, count },
            } => {
                assert_eq!(address, 0x48);
                assert_eq!(count, 4);
            }
            _ => panic!("expected I2c Read command"),
        }
    }

    #[test]
    fn cli_i2c_write() {
        let cli = Cli::try_parse_from(["gallo", "i2c", "write", "-a", "0x50", "-b", "0xDE", "0xAD"]).unwrap();
        match cli.command {
            Commands::I2c {
                command: I2cCommands::Write { address, bytes },
            } => {
                assert_eq!(address, 0x50);
                assert_eq!(bytes, vec![0xDE, 0xAD]);
            }
            _ => panic!("expected I2c Write command"),
        }
    }

    #[test]
    fn cli_i2c_write_read() {
        let cli = Cli::try_parse_from(["gallo", "i2c", "write-read", "-a", "0x68", "-b", "0x01", "-c", "6"]).unwrap();
        match cli.command {
            Commands::I2c {
                command: I2cCommands::WriteRead { address, bytes, count },
            } => {
                assert_eq!(address, 0x68);
                assert_eq!(bytes, vec![0x01]);
                assert_eq!(count, 6);
            }
            _ => panic!("expected I2c WriteRead command"),
        }
    }

    #[test]
    fn cli_i2c_scan() {
        let cli = Cli::try_parse_from(["gallo", "i2c", "scan"]).unwrap();
        match cli.command {
            Commands::I2c {
                command: I2cCommands::Scan { reserved },
            } => {
                assert!(!reserved);
            }
            _ => panic!("expected I2c Scan command"),
        }
    }

    #[test]
    fn cli_i2c_scan_reserved() {
        let cli = Cli::try_parse_from(["gallo", "i2c", "scan", "-r"]).unwrap();
        match cli.command {
            Commands::I2c {
                command: I2cCommands::Scan { reserved },
            } => {
                assert!(reserved);
            }
            _ => panic!("expected I2c Scan command"),
        }
    }

    #[test]
    fn cli_spi_read() {
        let cli = Cli::try_parse_from(["gallo", "spi", "read", "-c", "16"]).unwrap();
        match cli.command {
            Commands::Spi {
                command: SpiCommands::Read { count },
            } => {
                assert_eq!(count, 16);
            }
            _ => panic!("expected Spi Read command"),
        }
    }

    #[test]
    fn cli_spi_write() {
        let cli = Cli::try_parse_from(["gallo", "spi", "write", "-b", "0xCA", "0xFE"]).unwrap();
        match cli.command {
            Commands::Spi {
                command: SpiCommands::Write { bytes },
            } => {
                assert_eq!(bytes, vec![0xCA, 0xFE]);
            }
            _ => panic!("expected Spi Write command"),
        }
    }

    #[test]
    fn cli_spi_transfer() {
        let cli = Cli::try_parse_from(["gallo", "spi", "transfer", "-b", "0x01", "0x02", "0x03"]).unwrap();
        match cli.command {
            Commands::Spi {
                command: SpiCommands::Transfer { bytes },
            } => {
                assert_eq!(bytes, vec![0x01, 0x02, 0x03]);
            }
            _ => panic!("expected Spi Transfer command"),
        }
    }

    #[test]
    fn cli_i2c_set_config() {
        let cli = Cli::try_parse_from(["gallo", "i2c", "set-config", "--frequency", "fast"]).unwrap();
        match cli.command {
            Commands::I2c {
                command: I2cCommands::SetConfig { frequency },
            } => {
                assert_eq!(frequency, I2cFrequencyArg::Fast);
            }
            _ => panic!("expected I2c SetConfig command"),
        }
    }

    #[test]
    fn cli_i2c_set_config_fast_plus() {
        let cli = Cli::try_parse_from(["gallo", "i2c", "set-config", "--frequency", "fast-plus"]).unwrap();
        match cli.command {
            Commands::I2c {
                command: I2cCommands::SetConfig { frequency },
            } => {
                assert_eq!(frequency, I2cFrequencyArg::FastPlus);
            }
            _ => panic!("expected I2c SetConfig command"),
        }
    }

    #[test]
    fn cli_i2c_set_config_invalid_frequency_fails() {
        let result = Cli::try_parse_from(["gallo", "i2c", "set-config", "--frequency", "ultra-fast"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_spi_set_config() {
        let cli = Cli::try_parse_from([
            "gallo",
            "spi",
            "set-config",
            "--frequency",
            "1000000",
            "--first-transition",
            "--idle-low",
        ])
        .unwrap();
        match cli.command {
            Commands::Spi {
                command:
                    SpiCommands::SetConfig {
                        frequency,
                        first_transition,
                        idle_low,
                    },
            } => {
                assert_eq!(frequency, 1_000_000);
                assert!(first_transition);
                assert!(idle_low);
            }
            _ => panic!("expected Spi SetConfig command"),
        }
    }

    #[test]
    fn cli_spi_set_config_defaults() {
        let cli = Cli::try_parse_from(["gallo", "spi", "set-config", "--frequency", "500000"]).unwrap();
        match cli.command {
            Commands::Spi {
                command:
                    SpiCommands::SetConfig {
                        first_transition,
                        idle_low,
                        ..
                    },
            } => {
                assert!(!first_transition);
                assert!(!idle_low);
            }
            _ => panic!("expected Spi SetConfig command"),
        }
    }

    #[test]
    fn cli_i2c_set_config_missing_frequency_fails() {
        let result = Cli::try_parse_from(["gallo", "i2c", "set-config"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_spi_set_config_missing_frequency_fails() {
        let result = Cli::try_parse_from(["gallo", "spi", "set-config"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_i2c_read_missing_address_fails() {
        let result = Cli::try_parse_from(["gallo", "i2c", "read", "-c", "4"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_unknown_subcommand_fails() {
        let result = Cli::try_parse_from(["gallo", "uart"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_i2c_without_subcommand_fails() {
        let result = Cli::try_parse_from(["gallo", "i2c"]);
        assert!(result.is_err());
    }

    #[test]
    fn cli_spi_without_subcommand_fails() {
        let result = Cli::try_parse_from(["gallo", "spi"]);
        assert!(result.is_err());
    }
}