Skip to main content

usb_stack/class/
i2c_tiny_usb.rs

1//! i2c-tiny-usb — a vendor-specific USB to I2C bridge.
2//!
3//! Implements the protocol of Till Harbaum's *i2c-tiny-usb* adapter, spoken by
4//! the Linux `i2c-tiny-usb` driver (`drivers/i2c/busses/i2c-tiny-usb.c`) and by
5//! the `i2c_usb` test tool shipped with the original firmware.  Every transfer
6//! travels over the control pipe, so the function declares one vendor-specific
7//! interface and no endpoints at all.
8//!
9//! # Protocol
10//!
11//! | `bRequest` | `wValue` | `wIndex` | Data | Answer |
12//! |------------|----------|----------|------|--------|
13//! | [`cmd::ECHO`] | value | — | — | the value bytes, for link testing |
14//! | [`cmd::GET_FUNC`] | — | — | — | functionality as a little-endian `u32` |
15//! | [`cmd::SET_DELAY`] | bit delay in µs | — | — | — |
16//! | [`cmd::GET_STATUS`] | — | — | — | status of the last transfer |
17//! | [`cmd::I2C_IO`] with flags | `i2c_msg` flags | 7-bit address | message bytes | read data on reads |
18//!
19//! The host marks the first message of a transaction with
20//! [`cmd::I2C_IO_BEGIN`] and the last one with [`cmd::I2C_IO_END`]; a message
21//! without `BEGIN` continues the previous one with a repeated START, one
22//! without `END` leaves the bus busy.  After every message the host reads
23//! `GET_STATUS` and gives up with `-EREMOTEIO` when it is
24//! [`status::ADDRESS_NAK`].
25//!
26//! The I2C address travels in `wIndex`, which normally holds the interface
27//! number, so requests are answered for any interface index.  That matches the
28//! reference firmware, which is a single-function device.  Vendor requests the
29//! adapter does not recognise are left alone, so it can coexist with another
30//! vendor-specific function.
31//!
32//! # Supported transactions
33//!
34//! * one message — address, optional data, START and STOP
35//! * write followed by read — the repeated-start pattern that SMBus emulation
36//!   uses, and therefore what `i2cdetect`, `i2cget` and `i2cdump` produce
37//! * several writes — concatenated into a single message
38//!
39//! A hardware I2C peripheral cannot pause in the middle of a transaction, so
40//! the bytes of a message that does not end the transaction are buffered (up to
41//! [`PENDING_WRITE_MAX`] of them) and replayed together with the message that
42//! ends it.  Reads must be the last message of a transaction, 10-bit addresses
43//! are not supported, SMBus block reads need the read phase to continue after
44//! the first byte ([`flags::RECV_LEN`], so
45//! [`func::SMBUS_READ_BLOCK_DATA`] is not advertised either), and a transfer has
46//! to fit the 256-byte control buffer.  Such requests are stalled instead of
47//! being silently mistranslated.
48//!
49//! # Example
50//!
51//! ```ignore
52//! use my_hal_usb::{UsbBusAllocator, UsbDeviceBuilder};
53//! use my_hal_usb::class::i2c_tiny_usb::I2cTinyUsb;
54//! use my_hal_usb::MyBus;
55//!
56//! let alloc = UsbBusAllocator::new(MyBus::new(/* peripheral */));
57//! let mut adapter = I2cTinyUsb::new(&alloc, MyI2cBus::new());
58//! let mut dev = UsbDeviceBuilder::new(&alloc, 0x0403, 0xC631)
59//!     .device_release(0x0100)
60//!     .manufacturer("harbaum.org")
61//!     .product("i2c-tiny-usb")
62//!     .build();
63//!
64//! dev.bus().connect();
65//! loop {
66//!     dev.poll(&mut [&mut adapter]);
67//! }
68//! ```
69
70use crate::bus::{InterfaceNumber, UsbBus, UsbBusAllocator};
71use crate::class::UsbClass;
72use crate::control::{ControlIn, ControlOut, Recipient, Request, RequestType};
73use crate::descriptor::{DescriptorWriter, class_code};
74use crate::error::UsbResult;
75
76// ─── Protocol constants ──────────────────────────────────────────────────────
77
78/// Vendor control requests (`bRequest`).
79pub mod cmd {
80    /// Echo `wValue` back; used to check that the link is alive.
81    pub const ECHO: u8 = 0;
82    /// Report the adapter's functionality as a little-endian `u32`.
83    pub const GET_FUNC: u8 = 1;
84    /// Set the bit delay in microseconds (`wValue`).
85    pub const SET_DELAY: u8 = 2;
86    /// Report the status of the last transfer.
87    pub const GET_STATUS: u8 = 3;
88    /// Perform one I2C message; ORed with the flags below.
89    pub const I2C_IO: u8 = 4;
90    /// This message starts a transaction (START).
91    pub const I2C_IO_BEGIN: u8 = 1 << 0;
92    /// This message ends a transaction (STOP).
93    pub const I2C_IO_END: u8 = 1 << 1;
94}
95
96/// Values returned by [`cmd::GET_STATUS`].
97pub mod status {
98    /// Nothing transferred yet, or a buffered write whose result is not known
99    /// yet.  The host treats anything but [`ADDRESS_NAK`] as success.
100    pub const IDLE: u8 = 0;
101    /// The address was acknowledged.
102    pub const ADDRESS_ACK: u8 = 1;
103    /// The address or a data byte was not acknowledged.
104    pub const ADDRESS_NAK: u8 = 2;
105}
106
107/// Functionality bits reported by [`cmd::GET_FUNC`] (`I2C_FUNC_*` from
108/// `include/uapi/linux/i2c.h`).
109pub mod func {
110    /// Full `I2C_RDWR` support: arbitrary messages with START/STOP control.
111    pub const I2C: u32 = 0x0000_0001;
112    /// 10-bit addresses.
113    pub const TEN_BIT_ADDR: u32 = 0x0000_0002;
114    /// `I2C_M_*` flags that bend the protocol (`I2C_M_NOSTART`, `I2C_M_REV_DIR_ADDR`, …).
115    pub const PROTOCOL_MANGLING: u32 = 0x0000_0004;
116    /// Packet error checking.
117    pub const SMBUS_PEC: u32 = 0x0000_0008;
118    /// SMBus quick command, the shortest bus probe.
119    pub const SMBUS_QUICK: u32 = 0x0001_0000;
120    /// SMBus read byte.
121    pub const SMBUS_READ_BYTE: u32 = 0x0002_0000;
122    /// SMBus write byte.
123    pub const SMBUS_WRITE_BYTE: u32 = 0x0004_0000;
124    /// SMBus read byte with a command byte.
125    pub const SMBUS_READ_BYTE_DATA: u32 = 0x0008_0000;
126    /// SMBus write byte with a command byte.
127    pub const SMBUS_WRITE_BYTE_DATA: u32 = 0x0010_0000;
128    /// SMBus read word with a command byte.
129    pub const SMBUS_READ_WORD_DATA: u32 = 0x0020_0000;
130    /// SMBus write word with a command byte.
131    pub const SMBUS_WRITE_WORD_DATA: u32 = 0x0040_0000;
132    /// SMBus process call.
133    pub const SMBUS_PROC_CALL: u32 = 0x0080_0000;
134    /// SMBus read block with a command byte.
135    pub const SMBUS_READ_BLOCK_DATA: u32 = 0x0100_0000;
136    /// SMBus write block with a command byte.
137    pub const SMBUS_WRITE_BLOCK_DATA: u32 = 0x0200_0000;
138    /// SMBus read I2C block.
139    pub const SMBUS_READ_I2C_BLOCK: u32 = 0x0400_0000;
140    /// SMBus write I2C block.
141    pub const SMBUS_WRITE_I2C_BLOCK: u32 = 0x0800_0000;
142
143    /// SMBus operations the kernel can emulate on top of plain I2C transfers.
144    pub const SMBUS_EMUL: u32 = SMBUS_QUICK
145        | SMBUS_READ_BYTE
146        | SMBUS_WRITE_BYTE
147        | SMBUS_READ_BYTE_DATA
148        | SMBUS_WRITE_BYTE_DATA
149        | SMBUS_READ_WORD_DATA
150        | SMBUS_WRITE_WORD_DATA
151        | SMBUS_PROC_CALL
152        | SMBUS_WRITE_BLOCK_DATA
153        | SMBUS_READ_I2C_BLOCK
154        | SMBUS_WRITE_I2C_BLOCK
155        | SMBUS_PEC;
156
157    /// What a plain I2C master offers: I2C transfers plus emulated SMBus.
158    pub const DEFAULT: u32 = I2C | SMBUS_EMUL;
159}
160
161/// Message flags the host passes in `wValue` (`I2C_M_*` from
162/// `include/uapi/linux/i2c.h`).
163pub mod flags {
164    /// Read message; mirrors the transfer direction.
165    pub const RD: u16 = 0x0001;
166    /// 10-bit address (not supported).
167    pub const TEN: u16 = 0x0010;
168    /// Do not emit a START — continue with a repeated START.
169    pub const NOSTART: u16 = 0x4000;
170    /// Reverse the direction bit (protocol mangling, not supported).
171    pub const REV_DIR_ADDR: u16 = 0x2000;
172    /// Ignore a NAK (protocol mangling, not supported).
173    pub const IGNORE_NAK: u16 = 0x1000;
174    /// Do not acknowledge the last read byte (protocol mangling, not supported).
175    pub const NO_RD_ACK: u16 = 0x0800;
176    /// SMBus block read: read a length byte, then that many more bytes.
177    ///
178    /// Not supported — it needs the read phase to continue after the first
179    /// byte, which the adapter cannot express.  Functionality therefore omits
180    /// [`super::func::SMBUS_READ_BLOCK_DATA`].
181    pub const RECV_LEN: u16 = 0x0400;
182}
183
184/// Default bit delay, matching the driver's default of 100 kHz.
185const DEFAULT_DELAY_US: u16 = 10;
186
187/// Bytes of a not-yet-finished write that may precede a repeated-start read.
188pub const PENDING_WRITE_MAX: usize = 16;
189
190// ─── Request decoding ────────────────────────────────────────────────────────
191
192/// What a vendor request asks for.
193///
194/// [`cmd::ECHO`] … [`cmd::GET_STATUS`] are 0…3 and carry no flags, while
195/// [`cmd::I2C_IO`] is 4 with [`cmd::I2C_IO_BEGIN`] (1) and [`cmd::I2C_IO_END`]
196/// (2) ORed in, so its flags live in the low two bits of 4…7.  Decoding has to
197/// look at the whole byte: masking those two bits off would fold `GET_FUNC`,
198/// `SET_DELAY` and `GET_STATUS` onto `ECHO`.
199#[derive(Clone, Copy, PartialEq, Eq, Debug)]
200enum Opcode {
201    /// Echo `wValue` back.
202    Echo,
203    /// Report the functionality.
204    GetFunc,
205    /// Set the bit delay.
206    SetDelay,
207    /// Report the last transfer's status.
208    GetStatus,
209    /// An I2C message, with the transaction markers it carried.
210    I2cIo { begin: bool, end: bool },
211    /// A request this adapter does not implement.
212    Unknown,
213}
214
215impl Opcode {
216    /// Decode `bRequest`.
217    const fn decode(request: u8) -> Self {
218        // The flags only ever appear on top of `I2C_IO` (4), which is what this
219        // comparison checks before stripping them.
220        const FLAGS: u8 = cmd::I2C_IO_BEGIN | cmd::I2C_IO_END;
221
222        if request & !FLAGS == cmd::I2C_IO {
223            Opcode::I2cIo {
224                begin: request & cmd::I2C_IO_BEGIN != 0,
225                end: request & cmd::I2C_IO_END != 0,
226            }
227        } else {
228            match request {
229                cmd::ECHO => Opcode::Echo,
230                cmd::GET_FUNC => Opcode::GetFunc,
231                cmd::SET_DELAY => Opcode::SetDelay,
232                cmd::GET_STATUS => Opcode::GetStatus,
233                _ => Opcode::Unknown,
234            }
235        }
236    }
237}
238
239// The decoder is the protocol contract, so pin the whole command space here:
240// a mistake would only show up against a real host otherwise.
241const _: () = {
242    assert!(matches!(Opcode::decode(cmd::ECHO), Opcode::Echo));
243    assert!(matches!(Opcode::decode(cmd::GET_FUNC), Opcode::GetFunc));
244    assert!(matches!(Opcode::decode(cmd::SET_DELAY), Opcode::SetDelay));
245    assert!(matches!(Opcode::decode(cmd::GET_STATUS), Opcode::GetStatus));
246    // `I2C_IO` with each combination of the two transaction flags.
247    assert!(matches!(
248        Opcode::decode(cmd::I2C_IO),
249        Opcode::I2cIo {
250            begin: false,
251            end: false
252        }
253    ));
254    assert!(matches!(
255        Opcode::decode(cmd::I2C_IO | cmd::I2C_IO_BEGIN),
256        Opcode::I2cIo {
257            begin: true,
258            end: false
259        }
260    ));
261    assert!(matches!(
262        Opcode::decode(cmd::I2C_IO | cmd::I2C_IO_END),
263        Opcode::I2cIo {
264            begin: false,
265            end: true
266        }
267    ));
268    assert!(matches!(
269        Opcode::decode(cmd::I2C_IO | cmd::I2C_IO_BEGIN | cmd::I2C_IO_END),
270        Opcode::I2cIo {
271            begin: true,
272            end: true
273        }
274    ));
275    assert!(matches!(Opcode::decode(5), Opcode::I2cIo { .. }));
276    assert!(matches!(Opcode::decode(0x80), Opcode::Unknown));
277};
278
279// ─── I2C bus ─────────────────────────────────────────────────────────────────
280
281/// Failure of an [`I2cBus`] operation.
282///
283/// The protocol can only tell the host "not acknowledged", which the driver
284/// turns into `-EREMOTEIO`; the distinction is kept for the application.
285#[derive(Clone, Copy, PartialEq, Eq, Debug)]
286#[cfg_attr(feature = "defmt", derive(defmt::Format))]
287pub enum I2cError {
288    /// A device did not acknowledge its address or a data byte.
289    NoAcknowledge,
290    /// Arbitration lost, bus timeout, or a peripheral fault.
291    BusFault,
292}
293
294/// I2C master the adapter drives.
295///
296/// Implement it around the bus driver at hand — see the `usb_i2c_tiny` example
297/// for one wrapping a hardware I2C peripheral.  The class translates the host's
298/// `i2c_msg` flags: a lone message becomes a [`write`](Self::write) or
299/// [`read`](Self::read), a write followed by a read becomes a
300/// [`write_read`](Self::write_read) with a repeated START between the phases.
301pub trait I2cBus {
302    /// Write `data` to the 7-bit `address`, START to STOP.
303    ///
304    /// An empty slice only probes the address, which is how bus scanning works.
305    fn write(&mut self, address: u8, data: &[u8]) -> Result<(), I2cError>;
306
307    /// Read from the 7-bit `address`, START to STOP.
308    fn read(&mut self, address: u8, data: &mut [u8]) -> Result<(), I2cError>;
309
310    /// Write `data`, then read `buffer` from the same address with a repeated
311    /// START between the phases.
312    fn write_read(&mut self, address: u8, data: &[u8], buffer: &mut [u8]) -> Result<(), I2cError>;
313
314    /// Bit delay requested by `Set Delay`.
315    ///
316    /// 100 kHz corresponds to 10 µs, so a peripheral with a configurable baud
317    /// rate can use `1_000_000 / microseconds`.  Bit-banged buses use it as the
318    /// half-period; hardware that cannot change speed may ignore it.
319    fn set_delay(&mut self, microseconds: u16) {
320        let _ = microseconds;
321    }
322}
323
324// ─── Message decoding ────────────────────────────────────────────────────────
325
326/// One `i2c_msg` from the host, as far as the adapter cares.
327#[derive(Clone, Copy)]
328struct Message {
329    /// 7-bit address (`wIndex`).
330    address: u8,
331    /// `i2c_msg` flags (`wValue`).
332    flags: u16,
333    /// First message of the transaction (`I2C_IO_BEGIN`).
334    start: bool,
335    /// Last message of the transaction (`I2C_IO_END`).
336    end: bool,
337}
338
339impl Message {
340    fn decode(request: &Request) -> Self {
341        Self {
342            address: request.index as u8,
343            flags: request.value,
344            start: request.request & cmd::I2C_IO_BEGIN != 0,
345            end: request.request & cmd::I2C_IO_END != 0,
346        }
347    }
348
349    /// The host asked for data (`I2C_M_RD`).
350    fn is_read(&self) -> bool {
351        self.flags & flags::RD != 0
352    }
353
354    /// The host used a 10-bit address.
355    fn is_ten_bit(&self) -> bool {
356        self.flags & flags::TEN != 0
357    }
358}
359
360// ─── I2cTinyUsb ──────────────────────────────────────────────────────────────
361
362/// i2c-tiny-usb adapter: wraps an [`I2cBus`] and serves the vendor protocol.
363///
364/// The adapter needs no endpoints of its own — everything travels over the
365/// control pipe — so the type is only parameterised by the bus it drives.
366pub struct I2cTinyUsb<I: I2cBus> {
367    interface: InterfaceNumber,
368    bus: I,
369    functionality: u32,
370    delay_us: u16,
371    status: u8,
372    pending_len: usize,
373    pending: [u8; PENDING_WRITE_MAX],
374    transfers: u32,
375    failures: u32,
376}
377
378impl<I: I2cBus> I2cTinyUsb<I> {
379    /// Create an adapter that reports [`func::DEFAULT`] functionality.
380    ///
381    /// Call it before building the device, like any other class.
382    pub fn new<B: UsbBus>(alloc: &UsbBusAllocator<B>, bus: I) -> Self {
383        Self::with_functionality(alloc, bus, func::DEFAULT)
384    }
385
386    /// Create an adapter that reports `functionality` for `Get Functionality`.
387    ///
388    /// Report what the bus really supports: bits for features that are not
389    /// implemented make the kernel issue transfers the adapter has to stall.
390    pub fn with_functionality<B: UsbBus>(
391        alloc: &UsbBusAllocator<B>,
392        bus: I,
393        functionality: u32,
394    ) -> Self {
395        Self {
396            interface: alloc.interface(),
397            bus,
398            functionality,
399            delay_us: DEFAULT_DELAY_US,
400            status: status::IDLE,
401            pending_len: 0,
402            pending: [0; PENDING_WRITE_MAX],
403            transfers: 0,
404            failures: 0,
405        }
406    }
407
408    // ── Bus access ────────────────────────────────────────────────────────────
409
410    /// The wrapped I2C bus.
411    pub fn bus(&self) -> &I {
412        &self.bus
413    }
414
415    /// The wrapped I2C bus, e.g. to use it from the application as well.
416    pub fn bus_mut(&mut self) -> &mut I {
417        &mut self.bus
418    }
419
420    // ── State ─────────────────────────────────────────────────────────────────
421
422    /// Functionality reported to the host.
423    pub fn functionality(&self) -> u32 {
424        self.functionality
425    }
426
427    /// Change the reported functionality.
428    pub fn set_functionality(&mut self, functionality: u32) {
429        self.functionality = functionality;
430    }
431
432    /// Bit delay requested by the host, in microseconds.
433    pub fn delay_us(&self) -> u16 {
434        self.delay_us
435    }
436
437    /// Status reported by `Get Status`.
438    pub fn status(&self) -> u8 {
439        self.status
440    }
441
442    /// Transfers performed for the host.
443    pub fn transfers(&self) -> u32 {
444        self.transfers
445    }
446
447    /// Transfers that failed and were reported to the host as a NAK.
448    pub fn failures(&self) -> u32 {
449        self.failures
450    }
451
452    // ── Internals ─────────────────────────────────────────────────────────────
453
454    /// Record the outcome of one bus operation.
455    fn finish(&mut self, result: Result<(), I2cError>) {
456        self.transfers = self.transfers.wrapping_add(1);
457        match result {
458            Ok(()) => self.status = status::ADDRESS_ACK,
459            Err(_) => {
460                self.failures = self.failures.wrapping_add(1);
461                self.status = status::ADDRESS_NAK;
462            }
463        }
464    }
465
466    /// Give up on a request that the protocol cannot express: clear the
467    /// transaction and stall so the host sees an error instead of wrong data.
468    fn abandon(&mut self) {
469        self.pending_len = 0;
470        self.failures = self.failures.wrapping_add(1);
471        self.status = status::ADDRESS_NAK;
472    }
473
474    /// Append `data` to the bytes of the transaction in progress, if they fit.
475    fn append_pending(&mut self, data: &[u8]) -> bool {
476        let end = self.pending_len + data.len();
477        if end > PENDING_WRITE_MAX {
478            return false;
479        }
480        self.pending[self.pending_len..end].copy_from_slice(data);
481        self.pending_len = end;
482        true
483    }
484
485    /// A write message: either a complete write, or the start of one that a
486    /// later message finishes.
487    fn write_message<B: UsbBus>(&mut self, msg: Message, xfer: ControlOut<'_, B>) {
488        let data = xfer.data();
489
490        if msg.is_ten_bit() {
491            self.abandon();
492            let _ = xfer.reject();
493            return;
494        }
495
496        if msg.start {
497            // A new transaction starts here, so nothing carries over.
498            self.pending_len = 0;
499        }
500
501        if msg.start && msg.end {
502            // Complete write in one message, including the address-only probe.
503            let result = self.bus.write(msg.address, data);
504            self.finish(result);
505        } else if msg.end {
506            // The buffered bytes and this message form one write: a peripheral
507            // cannot pause between the two control transfers.
508            if !self.append_pending(data) {
509                self.abandon();
510                let _ = xfer.reject();
511                return;
512            }
513            let length = self.pending_len;
514            let result = self.bus.write(msg.address, &self.pending[..length]);
515            self.pending_len = 0;
516            self.finish(result);
517        } else if self.append_pending(data) {
518            // Nothing on the bus yet: the write happens once the message that
519            // ends the transaction arrives.
520            self.status = status::IDLE;
521        } else {
522            self.abandon();
523            let _ = xfer.reject();
524            return;
525        }
526
527        let _ = xfer.accept();
528    }
529
530    /// A read message, which has to be the last one of a transaction.
531    fn read_message<B: UsbBus>(&mut self, msg: Message, length: u16, xfer: ControlIn<'_, B>) {
532        if msg.is_ten_bit() || !msg.end || msg.flags & flags::RECV_LEN != 0 {
533            // A read in the middle of a transaction would need the bus to stay
534            // open across control transfers, which a peripheral cannot do, and
535            // an SMBus block read would need it to stay open within one.
536            self.abandon();
537            let _ = xfer.reject();
538            return;
539        }
540
541        if msg.start {
542            self.pending_len = 0;
543        }
544
545        let address = msg.address;
546        let requested = length as usize;
547
548        // With a buffered write in front this is the repeated-start pattern,
549        // otherwise a plain read.  A failed read answers with zeros and reports
550        // a NAK, so the host discards the data — the same trade the reference
551        // firmware makes.
552        let _ = xfer.accept(|buf| {
553            let count = requested.min(buf.len());
554            let result = if self.pending_len > 0 {
555                let written = self.pending_len;
556                let result =
557                    self.bus
558                        .write_read(address, &self.pending[..written], &mut buf[..count]);
559                self.pending_len = 0;
560                result
561            } else if count == 0 {
562                // A zero-length read (SMBus quick read) still probes the
563                // address, which the bus driver only does for a write.
564                self.bus.write(address, &[])
565            } else {
566                self.bus.read(address, &mut buf[..count])
567            };
568
569            match result {
570                Ok(()) => {
571                    self.finish(Ok(()));
572                    Ok(count)
573                }
574                Err(error) => {
575                    self.finish(Err(error));
576                    buf[..count].fill(0);
577                    Ok(count)
578                }
579            }
580        });
581    }
582}
583
584// ─── UsbClass<B> implementation ───────────────────────────────────────────────
585
586impl<B: UsbBus, I: I2cBus> UsbClass<B> for I2cTinyUsb<I> {
587    fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
588        // Control transfers only: the interface carries no endpoints.
589        w.interface(self.interface, 0, class_code::VENDOR, 0x00, 0x00)
590    }
591
592    fn control_in(&mut self, xfer: ControlIn<'_, B>) {
593        let req = *xfer.request();
594
595        if req.request_type != RequestType::Vendor || req.recipient != Recipient::Interface {
596            return;
597        }
598
599        // The I2C address travels in `wIndex`, so the interface number cannot be
600        // compared here.
601        match Opcode::decode(req.request) {
602            Opcode::Echo => {
603                let _ = xfer.accept_with(&req.value.to_le_bytes());
604            }
605            Opcode::GetFunc => {
606                let _ = xfer.accept_with(&self.functionality.to_le_bytes());
607            }
608            Opcode::GetStatus => {
609                let _ = xfer.accept_with(&[self.status]);
610            }
611            Opcode::I2cIo { .. } => self.read_message(Message::decode(&req), req.length, xfer),
612            // Set Delay is an OUT request and the rest is not ours: leave the
613            // request for another class, or let the device layer stall it.
614            _ => {}
615        }
616    }
617
618    fn control_out(&mut self, xfer: ControlOut<'_, B>) {
619        let req = *xfer.request();
620
621        if req.request_type != RequestType::Vendor || req.recipient != Recipient::Interface {
622            return;
623        }
624
625        match Opcode::decode(req.request) {
626            Opcode::SetDelay => {
627                // The reference firmware never lets the delay become zero.
628                let delay = req.value.max(1);
629                self.delay_us = delay;
630                self.bus.set_delay(delay);
631                let _ = xfer.accept();
632            }
633            Opcode::I2cIo { .. } => {
634                let msg = Message::decode(&req);
635                if msg.is_read() {
636                    // Reads arrive as control IN transfers.
637                    let _ = xfer.reject();
638                } else {
639                    self.write_message(msg, xfer);
640                }
641            }
642            // The remaining commands are IN requests; anything else is not ours.
643            _ => {}
644        }
645    }
646
647    fn configure(&mut self) {
648        self.pending_len = 0;
649        self.status = status::IDLE;
650    }
651
652    fn reset(&mut self) {
653        // Same as `configure`, plus the counters.
654        self.pending_len = 0;
655        self.status = status::IDLE;
656        self.transfers = 0;
657        self.failures = 0;
658    }
659}