Skip to main content

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