pico-de-gallo-lib 0.5.0

High-level library to communicate with 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
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! Host-side library for communicating with a Pico de Gallo USB bridge.
//!
//! This crate provides [`PicoDeGallo`], an async client for interacting with
//! the Pico de Gallo firmware over USB. It supports I2C reads/writes, SPI
//! operations (including full-duplex transfers), UART reads/writes, GPIO
//! control, PWM output, ADC sampling, 1-Wire bus operations, and device
//! configuration — all via [postcard-rpc](https://docs.rs/postcard-rpc)
//! endpoints.
//!
//! # Quick Start
//!
//! ```no_run
//! use pico_de_gallo_lib::PicoDeGallo;
//!
//! #[tokio::main]
//! async fn main() {
//!     let gallo = PicoDeGallo::new();
//!     let version = gallo.version().await.unwrap();
//!     println!("Firmware v{}.{}.{}", version.major, version.minor, version.patch);
//! }
//! ```
//!
//! # Multiple Devices
//!
//! When multiple Pico de Gallo boards are connected, use [`list_devices`] to
//! enumerate them and [`PicoDeGallo::new_with_serial_number`] to connect to a
//! specific board:
//!
//! ```no_run
//! use pico_de_gallo_lib::{PicoDeGallo, list_devices};
//!
//! #[tokio::main]
//! async fn main() {
//!     for dev in list_devices() {
//!         println!("Found: {:?}", dev.serial_number);
//!     }
//!     let gallo = PicoDeGallo::new_with_serial_number("ABCD1234");
//! }
//! ```
//!
//! # Error Handling
//!
//! All methods return [`Result<T, PicoDeGalloError<E>>`](PicoDeGalloError)
//! where `E` is the endpoint-specific error type. Errors are either
//! communication failures ([`PicoDeGalloError::Comms`]) or endpoint-level
//! errors ([`PicoDeGalloError::Endpoint`]).

pub mod decode;

use nusb::DeviceInfo as NusbDeviceInfo;
use pico_de_gallo_internal::{
    AdcGetConfiguration, AdcRead, AdcReadRequest, GetDeviceInfo, GpioEventTopic, GpioGet, GpioGetRequest, GpioPut,
    GpioPutRequest, GpioSetConfiguration, GpioSetConfigurationRequest, GpioSubscribe, GpioSubscribeRequest,
    GpioUnsubscribe, GpioUnsubscribeRequest, GpioWaitForAny, GpioWaitForFalling, GpioWaitForHigh, GpioWaitForLow,
    GpioWaitForRising, GpioWaitRequest, I2cBatch, I2cBatchRequest, I2cGetConfiguration, I2cRead, I2cReadRequest,
    I2cScan, I2cScanRequest, I2cSetConfiguration, I2cSetConfigurationRequest, I2cWrite, I2cWriteRead,
    I2cWriteReadRequest, I2cWriteRequest, MICROSOFT_VID, OneWireRead, OneWireReadRequest, OneWireReset, OneWireSearch,
    OneWireSearchNext, OneWireWrite, OneWireWritePullup, OneWireWritePullupRequest, OneWireWriteRequest,
    PICO_DE_GALLO_PID, PwmDisable, PwmDisableRequest, PwmEnable, PwmEnableRequest, PwmGetConfiguration,
    PwmGetConfigurationRequest, PwmGetDutyCycle, PwmGetDutyCycleRequest, PwmSetConfiguration,
    PwmSetConfigurationRequest, PwmSetDutyCycle, PwmSetDutyCycleRequest, SCHEMA_VERSION_MINOR, SpiBatch,
    SpiBatchRequest, SpiFlush, SpiGetConfiguration, SpiRead, SpiReadRequest, SpiSetConfiguration,
    SpiSetConfigurationRequest, SpiTransfer, SpiTransferRequest, SpiWrite, SpiWriteRequest, UartFlush,
    UartGetConfiguration, UartRead, UartReadRequest, UartSetConfiguration, UartSetConfigurationRequest, UartWrite,
    UartWriteRequest, Version,
};

pub use pico_de_gallo_internal::{
    AdcChannel, AdcConfigurationInfo, Capabilities, DeviceInfo, GpioDirection, GpioEdge, GpioEvent, GpioPull,
    GpioState, I2cBatchOp, I2cFrequency, PwmConfigurationInfo, PwmDutyCycleInfo, SpiBatchOp, SpiConfigurationInfo,
    SpiPhase, SpiPolarity, UartConfigurationInfo, VersionInfo,
};
pub use pico_de_gallo_internal::{
    AdcError, GpioError, I2cBatchError, I2cError, OneWireError, PwmError, SpiBatchError, SpiError, UartError,
};
pub use pico_de_gallo_internal::{
    encode_i2c_batch_ops, encode_spi_batch_ops, i2c_batch_response_len, spi_batch_response_len,
};

pub use postcard_rpc::host_client::{IoClosed, MultiSubscription};
use postcard_rpc::{
    header::VarSeqKind,
    host_client::{HostClient, HostErr},
    standard_icd::{ERROR_PATH, PingEndpoint, WireError},
};
use std::convert::Infallible;

/// Description of a connected Pico de Gallo device.
#[derive(Debug, Clone)]
pub struct DeviceDescription {
    /// USB serial number (unique per board, derived from chip ID).
    pub serial_number: Option<String>,
    /// USB manufacturer string.
    pub manufacturer: Option<String>,
    /// USB product string.
    pub product: Option<String>,
}

/// List all connected Pico de Gallo devices.
///
/// Returns a description for each device found on the USB bus matching the
/// Pico de Gallo VID/PID. Use the serial number with
/// [`PicoDeGallo::new_with_serial_number`] to connect to a specific device.
pub fn list_devices() -> Vec<DeviceDescription> {
    let devices = match nusb::list_devices() {
        Ok(iter) => iter,
        Err(_) => return Vec::new(),
    };
    devices
        .filter(|dev| dev.vendor_id() == MICROSOFT_VID && dev.product_id() == PICO_DE_GALLO_PID)
        .map(|dev| DeviceDescription {
            serial_number: dev.serial_number().map(String::from),
            manufacturer: dev.manufacturer_string().map(String::from),
            product: dev.product_string().map(String::from),
        })
        .collect()
}

/// Error type for Pico de Gallo operations.
///
/// Every method on [`PicoDeGallo`] returns this error type, parameterized by the
/// endpoint-specific error `E`. In practice, `E` is a rich error enum like
/// [`I2cError`], [`SpiError`], or [`GpioError`].
#[derive(Debug)]
pub enum PicoDeGalloError<E> {
    /// A transport-level communication error (USB disconnect, timeout, wire format error).
    Comms(HostErr<WireError>),
    /// The firmware processed the request but returned an error.
    Endpoint(E),
}

impl<E: core::fmt::Display> core::fmt::Display for PicoDeGalloError<E> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Comms(e) => write!(f, "communication error: {e:?}"),
            Self::Endpoint(e) => write!(f, "endpoint error: {e}"),
        }
    }
}

impl<E: core::fmt::Debug + core::fmt::Display> std::error::Error for PicoDeGalloError<E> {}

impl<E> From<HostErr<WireError>> for PicoDeGalloError<E> {
    fn from(value: HostErr<WireError>) -> Self {
        Self::Comms(value)
    }
}

/// Error returned by [`PicoDeGallo::validate()`] when the connected firmware
/// is incompatible with this host library.
#[derive(Debug)]
pub enum ValidateError {
    /// Could not communicate with the device (USB disconnect, timeout, etc.).
    Comms(HostErr<WireError>),
    /// The firmware does not support the `device/info` endpoint (legacy firmware).
    LegacyFirmware,
    /// The schema (wire protocol) version does not match.
    ///
    /// The host and firmware were compiled against different versions of
    /// `pico-de-gallo-internal`. They must be upgraded together.
    SchemaMismatch {
        /// Schema minor version expected by this host library.
        expected_minor: u16,
        /// Schema minor version reported by the firmware.
        actual_minor: u16,
    },
}

impl core::fmt::Display for ValidateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Comms(e) => write!(f, "communication error: {e:?}"),
            Self::LegacyFirmware => write!(
                f,
                "firmware does not support the device/info endpoint — upgrade firmware"
            ),
            Self::SchemaMismatch {
                expected_minor,
                actual_minor,
            } => write!(
                f,
                "schema version mismatch: host expects 0.{expected_minor}.x \
                 but firmware reports 0.{actual_minor}.x — upgrade both together"
            ),
        }
    }
}

impl std::error::Error for ValidateError {}

/// Async client for a Pico de Gallo USB bridge device.
///
/// This is the primary type for interacting with the hardware. It wraps a
/// [`postcard_rpc::host_client::HostClient`] and provides typed async methods
/// for every firmware endpoint. The client is cheaply cloneable (the inner
/// transport is reference-counted) and safe to share across tasks.
///
/// Connection happens lazily in the background — constructing a `PicoDeGallo`
/// does not block or fail. If the device is not connected, methods will return
/// errors when called.
#[derive(Clone)]
pub struct PicoDeGallo {
    client: HostClient<WireError>,
}

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

impl PicoDeGallo {
    /// Create a new instance for the Pico de Gallo device.
    ///
    /// NOTICE:
    ///
    /// This constructor will return the first matching device in case
    /// there are more than one connected.
    ///
    /// If you want more control, please use `new_with_serial_number`
    /// instead.
    pub fn new() -> Self {
        Self::new_inner(|dev| dev.vendor_id() == MICROSOFT_VID && dev.product_id() == PICO_DE_GALLO_PID)
    }

    /// Create a new instance for the Pico de Gallo device with the
    /// given serial number.
    pub fn new_with_serial_number(serial_number: &str) -> Self {
        Self::new_inner(|dev| {
            dev.vendor_id() == MICROSOFT_VID
                && dev.product_id() == PICO_DE_GALLO_PID
                && dev.serial_number() == Some(serial_number)
        })
    }

    fn new_inner<F: FnMut(&NusbDeviceInfo) -> bool>(func: F) -> Self {
        let client = HostClient::new_raw_nusb(func, ERROR_PATH, 8, VarSeqKind::Seq2);
        Self { client }
    }

    /// Wait until the client has closed the connection.
    pub async fn wait_closed(&self) {
        self.client.wait_closed().await;
    }

    /// Ping endpoint.
    ///
    /// Only used for testing purposes. Send a `u32` and get the same
    /// `u32` as a response.
    pub async fn ping(&self, id: u32) -> Result<u32, PicoDeGalloError<Infallible>> {
        Ok(self.client.send_resp::<PingEndpoint>(&id).await?)
    }

    /// Read `count` bytes from the I2C device at `address`.
    ///
    /// The firmware buffer is limited to [`pico_de_gallo_internal::MAX_TRANSFER_SIZE`]
    /// (4096) bytes. Reads exceeding this limit will be truncated.
    pub async fn i2c_read(&self, address: u8, count: u16) -> Result<Vec<u8>, PicoDeGalloError<I2cError>> {
        self.client
            .send_resp::<I2cRead>(&I2cReadRequest { address, count })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Write `contents` to the I2C device at `address`.
    pub async fn i2c_write(&self, address: u8, contents: &[u8]) -> Result<(), PicoDeGalloError<I2cError>> {
        self.client
            .send_resp::<I2cWrite>(&I2cWriteRequest { address, contents })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Write `contents` to the I2C device at `address` and read back `count` bytes.
    ///
    /// The firmware buffer is limited to [`pico_de_gallo_internal::MAX_TRANSFER_SIZE`]
    /// (4096) bytes. Reads exceeding this limit will be truncated.
    pub async fn i2c_write_read(
        &self,
        address: u8,
        contents: &[u8],
        count: u16,
    ) -> Result<Vec<u8>, PicoDeGalloError<I2cError>> {
        self.client
            .send_resp::<I2cWriteRead>(&I2cWriteReadRequest {
                address,
                contents,
                count,
            })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Scan the I2C bus and return the addresses of all responding devices.
    ///
    /// The firmware probes each 7-bit address by attempting a 1-byte read.
    /// Addresses that ACK are returned in ascending order. When
    /// `include_reserved` is `false`, only the standard range (0x08–0x77) is
    /// probed; when `true`, the full range (0x00–0x7F) is scanned.
    pub async fn i2c_scan(&self, include_reserved: bool) -> Result<Vec<u8>, PicoDeGalloError<I2cError>> {
        self.client
            .send_resp::<I2cScan>(&I2cScanRequest { include_reserved })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Execute a batch of I2C operations in a single USB transfer.
    ///
    /// Pass a slice of [`I2cBatchOp`] values directly — they are encoded
    /// internally. On success, returns the concatenated read data from
    /// all Read operations in order.
    ///
    /// This is much faster than issuing individual I2C calls when
    /// performing multi-step sequences (e.g., EEPROM programming).
    pub async fn i2c_batch(
        &self,
        address: u8,
        ops: &[I2cBatchOp<'_>],
    ) -> Result<Vec<u8>, PicoDeGalloError<I2cBatchError>> {
        let encoded = encode_i2c_batch_ops(ops);
        self.client
            .send_resp::<I2cBatch>(&I2cBatchRequest {
                address,
                count: ops.len() as u16,
                ops: &encoded,
            })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Read `count` bytes from the SPI bus.
    ///
    /// The firmware buffer is limited to [`pico_de_gallo_internal::MAX_TRANSFER_SIZE`]
    /// (4096) bytes. Reads exceeding this limit will be truncated.
    pub async fn spi_read(&self, count: u16) -> Result<Vec<u8>, PicoDeGalloError<SpiError>> {
        self.client
            .send_resp::<SpiRead>(&SpiReadRequest { count })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Write `contents` to the SPI bus.
    pub async fn spi_write(&self, contents: &[u8]) -> Result<(), PicoDeGalloError<SpiError>> {
        self.client
            .send_resp::<SpiWrite>(&SpiWriteRequest { contents })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Flush the SPI interface.
    pub async fn spi_flush(&self) -> Result<(), PicoDeGalloError<SpiError>> {
        self.client
            .send_resp::<SpiFlush>(&())
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Perform a full-duplex SPI transfer.
    ///
    /// Simultaneously sends `write_data` and receives the same number of bytes.
    /// The firmware buffer is limited to [`pico_de_gallo_internal::MAX_TRANSFER_SIZE`]
    /// bytes. Transfers exceeding this limit will be rejected.
    pub async fn spi_transfer(&self, write_data: &[u8]) -> Result<Vec<u8>, PicoDeGalloError<SpiError>> {
        self.client
            .send_resp::<SpiTransfer>(&SpiTransferRequest { contents: write_data })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Execute a batch of SPI operations atomically under chip-select.
    ///
    /// Pass a slice of [`SpiBatchOp`] values directly — they are encoded
    /// internally. The firmware asserts CS on `cs_pin` before the first
    /// operation and deasserts it after the last (or on error). On success,
    /// returns concatenated data from all Read and Transfer operations
    /// in order.
    ///
    /// This is much faster than issuing individual SPI calls when
    /// performing multi-step sequences.
    pub async fn spi_batch(
        &self,
        cs_pin: u8,
        ops: &[SpiBatchOp<'_>],
    ) -> Result<Vec<u8>, PicoDeGalloError<SpiBatchError>> {
        let encoded = encode_spi_batch_ops(ops);
        self.client
            .send_resp::<SpiBatch>(&SpiBatchRequest {
                cs_pin,
                count: ops.len() as u16,
                ops: &encoded,
            })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Read up to `count` bytes from the UART bus.
    ///
    /// The firmware reads up to `count` bytes from the UART receive buffer.
    /// If no data is immediately available, it waits up to `timeout_ms`
    /// milliseconds for at least one byte. Returns whatever bytes are
    /// available (1 to `count`), or an empty `Vec` on timeout.
    ///
    /// The firmware buffer is limited to [`pico_de_gallo_internal::MAX_TRANSFER_SIZE`]
    /// (4096) bytes.
    pub async fn uart_read(&self, count: u16, timeout_ms: u32) -> Result<Vec<u8>, PicoDeGalloError<UartError>> {
        self.client
            .send_resp::<UartRead>(&UartReadRequest { count, timeout_ms })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Write `contents` to the UART bus.
    ///
    /// Bytes are queued to the firmware's UART transmit buffer. The call
    /// returns once all bytes have been accepted by the TX buffer (not
    /// necessarily transmitted on the wire). Use [`uart_flush`](Self::uart_flush)
    /// to wait for transmission to complete.
    pub async fn uart_write(&self, contents: &[u8]) -> Result<(), PicoDeGalloError<UartError>> {
        self.client
            .send_resp::<UartWrite>(&UartWriteRequest { contents })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Flush the UART transmit buffer.
    ///
    /// Blocks until all pending bytes have been transmitted on the wire.
    pub async fn uart_flush(&self) -> Result<(), PicoDeGalloError<UartError>> {
        self.client
            .send_resp::<UartFlush>(&())
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Get the current state of GPIO numbered by `pin`.
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_get(&self, pin: u8) -> Result<GpioState, PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioGet>(&GpioGetRequest { pin })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Set the GPIO numbered by `pin` to state `state`.
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_put(&self, pin: u8, state: GpioState) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioPut>(&GpioPutRequest { pin, state })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Wait for GPIO numbered by `pin` to reach `High` state.
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_wait_for_high(&self, pin: u8) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioWaitForHigh>(&GpioWaitRequest { pin })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Wait for GPIO numbered by `pin` to reach `Low` state.
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_wait_for_low(&self, pin: u8) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioWaitForLow>(&GpioWaitRequest { pin })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Wait for a rising edge on the GPIO numbered by `pin`.
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_wait_for_rising_edge(&self, pin: u8) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioWaitForRising>(&GpioWaitRequest { pin })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Wait for a falling edge on the GPIO numbered by `pin`.
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_wait_for_falling_edge(&self, pin: u8) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioWaitForFalling>(&GpioWaitRequest { pin })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Wait for either a rising edge or a falling edge on the GPIO
    /// numbered by `pin`.
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_wait_for_any_edge(&self, pin: u8) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioWaitForAny>(&GpioWaitRequest { pin })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Configure a GPIO pin's direction and internal pull resistor.
    ///
    /// After configuration, the pin enters explicit mode: `gpio_get` and
    /// `gpio_put` will no longer auto-switch direction. Calling `gpio_put`
    /// on an input pin (or `gpio_get`/wait on an output pin) will return
    /// [`GpioError::WrongDirection`].
    ///
    /// Pico de Gallo offers 4 total GPIOs, numbered 0 through 3.
    pub async fn gpio_set_config(
        &self,
        pin: u8,
        direction: GpioDirection,
        pull: GpioPull,
    ) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioSetConfiguration>(&GpioSetConfigurationRequest { pin, direction, pull })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Subscribe to GPIO edge events on a pin.
    ///
    /// Starts push-based monitoring for the specified edge type. While subscribed,
    /// the pin cannot be used by other GPIO operations (they will return
    /// [`GpioError::PinMonitored`]). Use [`gpio_unsubscribe`](Self::gpio_unsubscribe)
    /// to release the pin.
    ///
    /// Call [`subscribe_gpio_events`](Self::subscribe_gpio_events) to receive the
    /// event stream.
    pub async fn gpio_subscribe(&self, pin: u8, edge: GpioEdge) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioSubscribe>(&GpioSubscribeRequest { pin, edge })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Unsubscribe from GPIO edge events on a pin.
    ///
    /// Stops monitoring and returns the pin to normal operation. Returns
    /// [`GpioError::PinNotMonitored`] if the pin is not currently subscribed.
    pub async fn gpio_unsubscribe(&self, pin: u8) -> Result<(), PicoDeGalloError<GpioError>> {
        self.client
            .send_resp::<GpioUnsubscribe>(&GpioUnsubscribeRequest { pin })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Subscribe to the GPIO event topic stream.
    ///
    /// Returns a [`MultiSubscription`] that yields [`GpioEvent`] messages as edges
    /// are detected on any subscribed pin. Call this *before* or *after*
    /// [`gpio_subscribe`](Self::gpio_subscribe) — events are buffered up to
    /// `depth` messages.
    ///
    /// Edge detection is best-effort: if the pin changes faster than the
    /// firmware monitor loop cadence, intermediate transitions may be missed.
    pub async fn subscribe_gpio_events(
        &self,
        depth: usize,
    ) -> Result<MultiSubscription<GpioEvent>, PicoDeGalloError<Infallible>> {
        self.client
            .subscribe_multi::<GpioEventTopic>(depth)
            .await
            .map_err(|_| PicoDeGalloError::Comms(HostErr::Closed))
    }

    /// Set I2C bus configuration parameters.
    ///
    /// Changes the I2C bus clock frequency. Takes effect immediately before
    /// the next I2C operation.
    pub async fn i2c_set_config(&self, frequency: I2cFrequency) -> Result<(), PicoDeGalloError<I2cError>> {
        self.client
            .send_resp::<I2cSetConfiguration>(&I2cSetConfigurationRequest { frequency })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Set SPI bus configuration parameters.
    ///
    /// Changes the SPI bus clock frequency, phase, and polarity. Takes effect
    /// immediately before the next SPI operation.
    pub async fn spi_set_config(
        &self,
        spi_frequency: u32,
        spi_phase: SpiPhase,
        spi_polarity: SpiPolarity,
    ) -> Result<(), PicoDeGalloError<SpiError>> {
        self.client
            .send_resp::<SpiSetConfiguration>(&SpiSetConfigurationRequest {
                spi_frequency,
                spi_phase,
                spi_polarity,
            })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Get the firmware version from the Pico de Gallo device.
    pub async fn version(&self) -> Result<VersionInfo, PicoDeGalloError<Infallible>> {
        Ok(self.client.send_resp::<Version>(&()).await?)
    }

    /// Get extended device information including firmware version, schema
    /// (wire protocol) version, hardware revision, and peripheral capabilities.
    pub async fn device_info(&self) -> Result<DeviceInfo, PicoDeGalloError<Infallible>> {
        Ok(self.client.send_resp::<GetDeviceInfo>(&()).await?)
    }

    /// Validate that the connected firmware is wire-compatible with this
    /// host library.
    ///
    /// Queries the `device/info` endpoint and checks that the schema minor
    /// version matches (pre-1.0 semver: minor bumps are breaking). Returns
    /// the [`DeviceInfo`] on success so callers can inspect capabilities
    /// without an extra round-trip.
    ///
    /// # Errors
    ///
    /// - [`ValidateError::Comms`] — could not reach the device.
    /// - [`ValidateError::LegacyFirmware`] — firmware does not support
    ///   `device/info` (upgrade firmware).
    /// - [`ValidateError::SchemaMismatch`] — firmware and host disagree on
    ///   the wire protocol version.
    pub async fn validate(&self) -> Result<DeviceInfo, ValidateError> {
        let info = self
            .client
            .send_resp::<GetDeviceInfo>(&())
            .await
            .map_err(|e| match &e {
                HostErr::Closed => ValidateError::Comms(e),
                _ => ValidateError::LegacyFirmware,
            })?;

        // Pre-1.0: minor version must match (0.x bumps are breaking).
        // Post-1.0: switch to major version matching.
        if info.schema_minor != SCHEMA_VERSION_MINOR {
            return Err(ValidateError::SchemaMismatch {
                expected_minor: SCHEMA_VERSION_MINOR,
                actual_minor: info.schema_minor,
            });
        }

        Ok(info)
    }

    /// Query the current I2C bus configuration.
    ///
    /// Returns the [`I2cFrequency`] value that is currently active on the
    /// firmware. The default is [`I2cFrequency::Standard`] (100 kHz).
    pub async fn i2c_get_config(&self) -> Result<I2cFrequency, PicoDeGalloError<Infallible>> {
        Ok(self.client.send_resp::<I2cGetConfiguration>(&()).await?)
    }

    /// Query the current SPI bus configuration.
    ///
    /// Returns a [`SpiConfigurationInfo`] struct with the active SPI
    /// frequency, phase, and polarity. The defaults are 1 MHz,
    /// `CaptureOnFirstTransition`, and `IdleLow`.
    pub async fn spi_get_config(&self) -> Result<SpiConfigurationInfo, PicoDeGalloError<Infallible>> {
        Ok(self.client.send_resp::<SpiGetConfiguration>(&()).await?)
    }

    /// Set UART bus configuration parameters.
    ///
    /// Changes the UART baud rate. Takes effect immediately before the next
    /// UART operation. The default baud rate is 115200.
    pub async fn uart_set_config(&self, baud_rate: u32) -> Result<(), PicoDeGalloError<UartError>> {
        self.client
            .send_resp::<UartSetConfiguration>(&UartSetConfigurationRequest { baud_rate })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Query the current UART bus configuration.
    ///
    /// Returns a [`UartConfigurationInfo`] struct with the active baud rate.
    /// The default is 115200.
    ///
    /// Returns [`UartError::Unsupported`] if the firmware's hardware revision
    /// does not support UART.
    pub async fn uart_get_config(&self) -> Result<UartConfigurationInfo, PicoDeGalloError<UartError>> {
        self.client
            .send_resp::<UartGetConfiguration>(&())
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    // -----------------------------------------------------------------------
    // PWM
    // -----------------------------------------------------------------------

    /// Set the raw duty cycle of a PWM channel (0–3).
    ///
    /// `duty` is a raw compare value in the range `0..=top`. Use
    /// [`pwm_get_duty_cycle`](Self::pwm_get_duty_cycle) to discover `max_duty`
    /// (which equals the current `top` value).
    ///
    /// Channels 0–1 share PWM slice 6, channels 2–3 share PWM slice 7.
    pub async fn pwm_set_duty_cycle(&self, channel: u8, duty: u16) -> Result<(), PicoDeGalloError<PwmError>> {
        self.client
            .send_resp::<PwmSetDutyCycle>(&PwmSetDutyCycleRequest { channel, duty })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Query the current duty cycle of a PWM channel (0–3).
    ///
    /// Returns a [`PwmDutyCycleInfo`] with `current_duty` (the raw compare
    /// value) and `max_duty` (the `top` register + 1, i.e., the full-scale
    /// value).
    pub async fn pwm_get_duty_cycle(&self, channel: u8) -> Result<PwmDutyCycleInfo, PicoDeGalloError<PwmError>> {
        self.client
            .send_resp::<PwmGetDutyCycle>(&PwmGetDutyCycleRequest { channel })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Enable the PWM slice that owns `channel` (0–3).
    ///
    /// Because PWM slices drive two channels, enabling channel 0 also
    /// enables channel 1 (and vice versa). Same for channels 2/3.
    pub async fn pwm_enable(&self, channel: u8) -> Result<(), PicoDeGalloError<PwmError>> {
        self.client
            .send_resp::<PwmEnable>(&PwmEnableRequest { channel })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Disable the PWM slice that owns `channel` (0–3).
    ///
    /// Because PWM slices drive two channels, disabling channel 0 also
    /// disables channel 1 (and vice versa). Same for channels 2/3.
    pub async fn pwm_disable(&self, channel: u8) -> Result<(), PicoDeGalloError<PwmError>> {
        self.client
            .send_resp::<PwmDisable>(&PwmDisableRequest { channel })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Configure the PWM slice behind `channel` (0–3).
    ///
    /// Sets the output frequency and phase-correct mode. The firmware
    /// computes `top` and `divider` automatically. Existing duty-cycle
    /// compare values are scaled proportionally to the new `top`.
    ///
    /// Channels 0–1 share a slice, so configuring channel 0 also affects
    /// channel 1 (and vice versa). Same for channels 2/3.
    pub async fn pwm_set_config(
        &self,
        channel: u8,
        frequency_hz: u32,
        phase_correct: bool,
    ) -> Result<(), PicoDeGalloError<PwmError>> {
        self.client
            .send_resp::<PwmSetConfiguration>(&PwmSetConfigurationRequest {
                channel,
                frequency_hz,
                phase_correct,
            })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Query the current configuration of the PWM slice behind `channel` (0–3).
    ///
    /// Returns a [`PwmConfigurationInfo`] with the effective frequency,
    /// phase-correct flag, and enabled state.
    pub async fn pwm_get_config(&self, channel: u8) -> Result<PwmConfigurationInfo, PicoDeGalloError<PwmError>> {
        self.client
            .send_resp::<PwmGetConfiguration>(&PwmGetConfigurationRequest { channel })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    // ---- ADC methods ----

    /// Perform a single-shot ADC read on the specified channel.
    ///
    /// Returns a raw 12-bit value (0–4095). Convert to voltage with:
    /// `V ≈ raw × 3.3 / 4096` (approximate — depends on ADC_AVDD).
    pub async fn adc_read(&self, channel: AdcChannel) -> Result<u16, PicoDeGalloError<AdcError>> {
        self.client
            .send_resp::<AdcRead>(&AdcReadRequest { channel })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Query the ADC configuration (resolution, reference, channel count).
    ///
    /// Returns an [`AdcConfigurationInfo`] with fixed values for the RP2350
    /// ADC. Useful for host-side discovery.
    ///
    /// Returns [`AdcError::Unsupported`] if the firmware's hardware revision
    /// does not support ADC.
    pub async fn adc_get_config(&self) -> Result<AdcConfigurationInfo, PicoDeGalloError<AdcError>> {
        self.client
            .send_resp::<AdcGetConfiguration>(&())
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    // ---- 1-Wire ----

    /// Perform a 1-Wire bus reset and detect device presence.
    ///
    /// Returns `true` if one or more devices responded with a presence pulse.
    pub async fn onewire_reset(&self) -> Result<bool, PicoDeGalloError<OneWireError>> {
        self.client
            .send_resp::<OneWireReset>(&())
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Read `len` bytes from the 1-Wire bus.
    ///
    /// The firmware sends `0xFF` read slots and captures the device's response bits.
    pub async fn onewire_read(&self, len: u16) -> Result<Vec<u8>, PicoDeGalloError<OneWireError>> {
        self.client
            .send_resp::<OneWireRead>(&OneWireReadRequest { len })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Write raw bytes to the 1-Wire bus.
    pub async fn onewire_write(&self, data: &[u8]) -> Result<(), PicoDeGalloError<OneWireError>> {
        self.client
            .send_resp::<OneWireWrite>(&OneWireWriteRequest { data })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Write bytes to the 1-Wire bus, then apply a strong pullup for the given duration.
    ///
    /// This is needed for parasitic-power devices like the DS18B20 during temperature
    /// conversion. The bus is held high for `pullup_duration_ms` milliseconds after
    /// the last bit is sent.
    pub async fn onewire_write_pullup(
        &self,
        data: &[u8],
        pullup_duration_ms: u16,
    ) -> Result<(), PicoDeGalloError<OneWireError>> {
        self.client
            .send_resp::<OneWireWritePullup>(&OneWireWritePullupRequest {
                data,
                pullup_duration_ms,
            })
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Start a new 1-Wire ROM search and return the first device address.
    ///
    /// Returns `Some(rom_id)` for the first device found, or `None` if no devices
    /// are on the bus. Call [`onewire_search_next`](Self::onewire_search_next) to
    /// continue enumerating.
    pub async fn onewire_search(&self) -> Result<Option<u64>, PicoDeGalloError<OneWireError>> {
        self.client
            .send_resp::<OneWireSearch>(&())
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }

    /// Continue the current 1-Wire ROM search.
    ///
    /// Returns the next device's 64-bit ROM ID, or `None` when all devices have
    /// been enumerated.
    pub async fn onewire_search_next(&self) -> Result<Option<u64>, PicoDeGalloError<OneWireError>> {
        self.client
            .send_resp::<OneWireSearchNext>(&())
            .await?
            .map_err(PicoDeGalloError::Endpoint)
    }
}

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

    // --- PicoDeGalloError tests ---

    #[test]
    fn endpoint_error_wraps_inner() {
        let err: PicoDeGalloError<&str> = PicoDeGalloError::Endpoint("endpoint failed");
        match err {
            PicoDeGalloError::Endpoint(e) => assert_eq!(e, "endpoint failed"),
            PicoDeGalloError::Comms(_) => panic!("expected Endpoint, got Comms"),
        }
    }

    #[test]
    fn map_err_converts_ok() {
        let result: Result<u32, &str> = Ok(42);
        let mapped: Result<u32, PicoDeGalloError<&str>> = result.map_err(PicoDeGalloError::Endpoint);
        assert_eq!(mapped.unwrap(), 42);
    }

    #[test]
    fn map_err_converts_err() {
        let result: Result<(), I2cError> = Err(I2cError::NoAcknowledge);
        let mapped = result.map_err(PicoDeGalloError::Endpoint);
        match mapped {
            Err(PicoDeGalloError::Endpoint(I2cError::NoAcknowledge)) => {}
            _ => panic!("expected Endpoint(I2cError::NoAcknowledge)"),
        }
    }

    // --- PicoDeGalloError From impl ---

    #[test]
    fn host_err_converts_to_comms_error() {
        let host_err: HostErr<WireError> = HostErr::Closed;
        let err: PicoDeGalloError<Infallible> = PicoDeGalloError::from(host_err);
        match err {
            PicoDeGalloError::Comms(HostErr::Closed) => {}
            _ => panic!("expected Comms(Closed)"),
        }
    }

    // --- PicoDeGalloError Debug ---

    #[test]
    fn error_debug_format_is_readable() {
        let err: PicoDeGalloError<I2cError> = PicoDeGalloError::Endpoint(I2cError::Bus);
        let debug = format!("{:?}", err);
        assert!(debug.contains("Endpoint"));
        assert!(debug.contains("Bus"));

        let comms_err: PicoDeGalloError<Infallible> = PicoDeGalloError::Comms(HostErr::Closed);
        let debug = format!("{:?}", comms_err);
        assert!(debug.contains("Comms"));
    }

    // --- PicoDeGalloError Display ---

    #[test]
    fn error_display_endpoint() {
        // Use a simple Display-implementing type
        let err: PicoDeGalloError<&str> = PicoDeGalloError::Endpoint("sensor timeout");
        let msg = format!("{err}");
        assert!(msg.contains("endpoint error"));
        assert!(msg.contains("sensor timeout"));
    }

    #[test]
    fn error_display_comms() {
        let err: PicoDeGalloError<&str> = PicoDeGalloError::Comms(HostErr::Closed);
        let msg = format!("{err}");
        assert!(msg.contains("communication error"));
    }

    #[test]
    fn error_is_std_error() {
        fn assert_error<E: std::error::Error>() {}
        assert_error::<PicoDeGalloError<&str>>();
    }

    // --- Device enumeration ---

    #[test]
    fn list_devices_returns_vec() {
        // Without hardware this returns an empty vec, but should not panic
        let devices = list_devices();
        // Each returned device must have the correct VID/PID (already filtered)
        for dev in &devices {
            assert!(dev.serial_number.is_some() || dev.serial_number.is_none());
        }
        // Mainly verifying the function doesn't panic
        let _ = devices;
    }

    #[test]
    fn device_description_is_clone_and_debug() {
        let desc = DeviceDescription {
            serial_number: Some("ABC123".to_string()),
            manufacturer: Some("Microsoft".to_string()),
            product: Some("Pico de Gallo".to_string()),
        };
        let cloned = desc.clone();
        assert_eq!(format!("{:?}", desc), format!("{:?}", cloned));
    }
}