Skip to main content

esp_hal/i2c/slave/
mod.rs

1//! # Inter-Integrated Circuit (I2C) - Slave mode
2//!
3//! ## Overview
4//!
5//! Receives writes and responds to read requests at a 7-bit I2C address.
6//! The driver uses SCL clock stretching for flow control in [`Blocking`] and [`Async`] modes.
7//! Writes stretch SCL at each data byte's ACK until the driver consumes that byte.
8//!
9//! ## Timeouts
10//!
11//! Operations have no software time limit and can wait indefinitely.
12//! [`Error::Timeout`] reports a detected hardware bus timeout.
13//! A later request's clock stretch can hide an earlier bus timeout.
14//!
15//! Operations reset the controller before returning [`Error::Timeout`] or
16//! [`Error::ArbitrationLost`]. This releases the slave's outputs and discards pending requests.
17//! The master must retry these requests.
18
19use core::{
20    future::Future,
21    marker::PhantomData,
22    pin::Pin,
23    sync::atomic::{AtomicBool, Ordering},
24    task::{Context, Poll},
25};
26
27use enumset::{EnumSet, EnumSetType};
28
29use crate::{
30    Async,
31    Blocking,
32    DriverMode,
33    asynch::AtomicWaker,
34    clock::ll::{ClockTree, I2cFunctionClockConfig, I2cInstance},
35    gpio::{
36        DriveMode,
37        InputSignal,
38        OutputConfig,
39        OutputSignal,
40        PinGuard,
41        Pull,
42        interconnect::{self, PeripheralInput, PeripheralOutput},
43    },
44    handler,
45    i2c::master::I2cAddress,
46    interrupt::InterruptHandler,
47    pac::i2c0::RegisterBlock,
48    private::{self, DropGuard},
49    ram,
50    rtc_cntl::WakeLock,
51    system::PeripheralGuard,
52};
53
54/// FIFO size of the I2C peripheral.
55pub const FIFO_SIZE: usize = property!("i2c_master.fifo_size");
56
57/// I2C slave errors.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59#[cfg_attr(feature = "defmt", derive(defmt::Format))]
60#[non_exhaustive]
61pub enum Error {
62    /// A hardware bus timeout is detected.
63    Timeout,
64    /// Bus arbitration is lost.
65    ArbitrationLost,
66    /// The receive buffer is too small, or the RX FIFO overflows.
67    Overflow,
68    /// The unread response exceeds 65,535 bytes and cannot fit in [`ReadStatus::LeftoverBytes`].
69    ResponseTooLong,
70    /// The master ends a read without a NACK.
71    ReadAborted,
72}
73
74impl core::error::Error for Error {}
75
76impl core::fmt::Display for Error {
77    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78        f.write_str(match self {
79            Self::Timeout => "Hardware bus timeout",
80            Self::ArbitrationLost => "Bus arbitration lost",
81            Self::Overflow => "Receive buffer or RX FIFO overflow",
82            Self::ResponseTooLong => "Unread response length exceeds 65,535 bytes",
83            Self::ReadAborted => "Read ended without a NACK",
84        })
85    }
86}
87
88impl embedded_hal::i2c::Error for Error {
89    fn kind(&self) -> embedded_hal::i2c::ErrorKind {
90        match self {
91            Self::ArbitrationLost => embedded_hal::i2c::ErrorKind::ArbitrationLoss,
92            Self::Overflow => embedded_hal::i2c::ErrorKind::Overrun,
93            Self::ReadAborted => embedded_hal::i2c::ErrorKind::Bus,
94            _ => embedded_hal::i2c::ErrorKind::Other,
95        }
96    }
97}
98
99/// I2C slave configuration.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)]
101#[cfg_attr(feature = "defmt", derive(defmt::Format))]
102#[non_exhaustive]
103pub struct Config {
104    /// The I2C slave address. Only 7-bit addresses are supported.
105    address: I2cAddress,
106}
107
108impl Config {
109    /// Creates a new I2C slave configuration with the specified address.
110    ///
111    /// The driver validates the address during construction or reconfiguration.
112    pub fn new(address: impl Into<I2cAddress>) -> Self {
113        Config {
114            address: address.into(),
115        }
116    }
117}
118
119/// I2C slave configuration errors.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121#[cfg_attr(feature = "defmt", derive(defmt::Format))]
122#[non_exhaustive]
123pub enum ConfigError {
124    /// The address is not a valid 7-bit address.
125    AddressInvalid,
126}
127
128impl core::error::Error for ConfigError {}
129
130impl core::fmt::Display for ConfigError {
131    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
132        match self {
133            ConfigError::AddressInvalid => write!(f, "Provided address is invalid"),
134        }
135    }
136}
137
138/// Request received from the master.
139#[derive(Debug, Copy, Clone, Eq, PartialEq)]
140#[cfg_attr(feature = "defmt", derive(defmt::Format))]
141pub enum Command {
142    /// The master requests data from the slave.
143    Read,
144    /// A write request with the number of received bytes.
145    Write(usize),
146}
147
148/// Result of a response to a master read request.
149#[derive(Debug, Copy, Clone, Eq, PartialEq)]
150#[cfg_attr(feature = "defmt", derive(defmt::Format))]
151pub enum ReadStatus {
152    /// The master reads exactly the provided number of bytes.
153    Done,
154    /// The master reads beyond the provided data and receives `0xff` padding.
155    NeedMoreBytes,
156    /// The number of provided bytes left unread.
157    LeftoverBytes(u16),
158}
159
160/// I2C slave driver.
161#[derive(Debug)]
162#[cfg_attr(feature = "defmt", derive(defmt::Format))]
163pub struct I2cSlave<'d, Dm: DriverMode> {
164    i2c: AnyI2c<'d>,
165    phantom: PhantomData<Dm>,
166    // Release the function clock before disabling peripheral register access.
167    clock_guard: I2cClockGuard,
168    guard: PeripheralGuard,
169    sda_pin: PinGuard,
170    scl_pin: PinGuard,
171}
172
173#[derive(Debug)]
174#[cfg_attr(feature = "defmt", derive(defmt::Format))]
175struct I2cClockGuard {
176    clock: I2cInstance,
177}
178
179impl I2cClockGuard {
180    fn new(clock: I2cInstance) -> Self {
181        ClockTree::with(|clocks| {
182            let config = I2cFunctionClockConfig::new(
183                Default::default(),
184                #[cfg(any(i2c_master_version = "3", i2c_master_version = "4"))]
185                0,
186            );
187            clock.configure_function_clock(clocks, config);
188            clock.request_function_clock(clocks);
189        });
190        Self { clock }
191    }
192}
193
194impl Drop for I2cClockGuard {
195    fn drop(&mut self) {
196        ClockTree::with(|clocks| self.clock.release_function_clock(clocks));
197    }
198}
199
200impl<Dm: DriverMode> embedded_hal::i2c::ErrorType for I2cSlave<'_, Dm> {
201    type Error = Error;
202}
203
204impl<'d> I2cSlave<'d, Blocking> {
205    /// Creates a new I2C slave instance in [`Blocking`] mode.
206    ///
207    /// # Errors
208    ///
209    /// [`ConfigError::AddressInvalid`] when the address is not a valid 7-bit address.
210    pub fn new(i2c: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
211        let guard = PeripheralGuard::new(i2c.info().peripheral);
212        let clock_guard = I2cClockGuard::new(i2c.info().clock_instance);
213
214        let sda_pin = PinGuard::new_unconnected();
215        let scl_pin = PinGuard::new_unconnected();
216
217        let mut slave = I2cSlave {
218            i2c: i2c.degrade(),
219            phantom: PhantomData,
220            clock_guard,
221            guard,
222            sda_pin,
223            scl_pin,
224        };
225
226        slave.apply_config(&config)?;
227        Ok(slave)
228    }
229
230    /// Reconfigures the driver to operate in [`Async`] mode.
231    ///
232    /// Pending requests are preserved.
233    pub fn into_async(self) -> I2cSlave<'d, Async> {
234        self.i2c
235            .set_interrupt_handler(self.driver().info.async_handler);
236
237        I2cSlave {
238            i2c: self.i2c,
239            phantom: PhantomData,
240            clock_guard: self.clock_guard,
241            guard: self.guard,
242            sda_pin: self.sda_pin,
243            scl_pin: self.scl_pin,
244        }
245    }
246}
247
248impl<'d> I2cSlave<'d, Async> {
249    /// Reconfigures the driver to operate in [`Blocking`] mode.
250    ///
251    /// Pending requests are preserved.
252    pub fn into_blocking(self) -> I2cSlave<'d, Blocking> {
253        self.i2c.disable_peri_interrupt();
254
255        I2cSlave {
256            i2c: self.i2c,
257            phantom: PhantomData,
258            clock_guard: self.clock_guard,
259            guard: self.guard,
260            sda_pin: self.sda_pin,
261            scl_pin: self.scl_pin,
262        }
263    }
264
265    /// Listens for a request from the master asynchronously.
266    ///
267    /// See [`Self::listen`] for the receive behavior and errors.
268    ///
269    /// # Cancellation Safety
270    ///
271    /// Canceling after this operation consumes receive data resets the controller
272    /// and discards pending requests. Otherwise, cancellation does not reset the controller.
273    /// The master must retry discarded requests.
274    /// The receive buffer can contain partial data.
275    pub async fn listen_async(&mut self, buffer: &mut [u8]) -> Result<Command, Error> {
276        let driver = self.driver();
277        let regs = driver.regs();
278        let state = self.i2c.state();
279
280        driver.start_listen();
281
282        let mut bytes_read = DropGuard::new(0, |bytes_read| {
283            if bytes_read > 0 {
284                driver.recover();
285            }
286        });
287        let result = async {
288            loop {
289                I2cSlaveFuture::new(
290                    regs,
291                    state,
292                    Event::SlaveStretch
293                        | Event::TransComplete
294                        | Event::StartDetected
295                        | Event::ReceiveBoundary,
296                )
297                .await;
298                if let Some(res) = driver.listen_step(buffer, &mut bytes_read) {
299                    return res;
300                }
301            }
302        }
303        .await;
304        bytes_read.defuse();
305        result
306    }
307
308    /// Responds to a master read request asynchronously.
309    ///
310    /// See [`Self::respond_to_read`] for the response behavior and errors.
311    ///
312    /// # Cancellation Safety
313    ///
314    /// Dropping an unpolled future does not change the controller.
315    /// Canceling a pending operation after its first poll resets the controller
316    /// and discards pending requests. The master must retry these requests.
317    pub async fn respond_to_read_async(&mut self, buffer: &[u8]) -> Result<ReadStatus, Error> {
318        let driver = self.driver();
319        let regs = driver.regs();
320        let state = self.i2c.state();
321
322        let mut bytes_written = 1;
323        driver.start_read(buffer);
324
325        let cancel_on_drop = DropGuard::new(&driver, Driver::recover);
326        let result = async {
327            loop {
328                I2cSlaveFuture::new(
329                    regs,
330                    state,
331                    Event::SlaveStretch | Event::Nack | Event::TransComplete | Event::StartDetected,
332                )
333                .await;
334
335                if let Some(status) = driver.respond_to_read_step(buffer, &mut bytes_written) {
336                    return status;
337                }
338            }
339        }
340        .await;
341        cancel_on_drop.defuse();
342        result
343    }
344}
345
346impl<'d, Dm: DriverMode> I2cSlave<'d, Dm> {
347    fn driver(&self) -> Driver<'_> {
348        let (info, state) = self.i2c.parts();
349        Driver { info, state }
350    }
351
352    /// Connects a pin to the I2C SDA signal.
353    pub fn with_sda(mut self, sda: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self {
354        let info = self.driver().info;
355        let input = info.sda_input;
356        let output = info.sda_output;
357        Driver::connect_pin(sda.into(), input, output, &mut self.sda_pin);
358        self
359    }
360
361    /// Connects a pin to the I2C SCL signal.
362    pub fn with_scl(mut self, scl: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self {
363        let info = self.driver().info;
364        let input = info.scl_input;
365        let output = info.scl_output;
366        Driver::connect_pin(scl.into(), input, output, &mut self.scl_pin);
367        self
368    }
369
370    /// Applies a new configuration.
371    ///
372    /// A valid configuration resets the controller and discards pending requests.
373    /// The master must retry these requests.
374    /// Invalid configurations preserve the current settings and FIFO contents.
375    ///
376    /// # Errors
377    ///
378    /// [`ConfigError::AddressInvalid`] when the address is not a valid 7-bit address.
379    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
380        self.driver().setup(config)
381    }
382
383    /// Listens for a request from the master.
384    ///
385    /// Receives writes into `buffer` and returns [`Command::Write`] with the number
386    /// of received bytes at STOP or repeated START. Address-only write probes are ignored.
387    /// Extra bytes are discarded if `buffer` is too small.
388    ///
389    /// Returns [`Command::Read`] for a read request and holds SCL low until
390    /// [`Self::respond_to_read`] supplies the response.
391    /// Pending receive data is preserved between calls.
392    /// The controller stretches SCL at each write byte's ACK until this method consumes the byte.
393    ///
394    /// If a bus error is detected when this method starts, it resets the controller
395    /// and discards pending data.
396    ///
397    /// # Errors
398    ///
399    /// [`Error::Overflow`] when the receive buffer is too small or the RX FIFO overflows.
400    /// The error is reported after STOP or repeated START.
401    ///
402    /// [`Error::Timeout`] when a hardware bus timeout is detected.
403    /// [`Error::ArbitrationLost`] when arbitration is lost.
404    pub fn listen(&mut self, buffer: &mut [u8]) -> Result<Command, Error> {
405        let driver = self.driver();
406        driver.start_listen();
407
408        let mut bytes_read = 0;
409        loop {
410            if let Some(res) = driver.listen_step(buffer, &mut bytes_read) {
411                return res;
412            }
413        }
414    }
415
416    /// Responds to a master read request.
417    ///
418    /// A listen operation must first return [`Command::Read`].
419    /// Sends data from `buffer` and releases SCL clock stretching.
420    /// Completes when the master sends a NACK.
421    /// Data is padded with `0xff` if the master reads past the end of `buffer`.
422    ///
423    /// # Errors
424    ///
425    /// [`Error::ResponseTooLong`] when more than 65,535 provided bytes remain unread.
426    /// The response completes, but the remaining count cannot fit in [`ReadStatus::LeftoverBytes`].
427    ///
428    /// [`Error::ReadAborted`] when the master ends the read without a NACK.
429    /// The controller resets and discards pending requests.
430    /// The master must retry these requests.
431    ///
432    /// [`Error::Timeout`] when a hardware bus timeout is detected.
433    /// [`Error::ArbitrationLost`] when arbitration is lost.
434    pub fn respond_to_read(&mut self, buffer: &[u8]) -> Result<ReadStatus, Error> {
435        let driver = self.driver();
436        let mut bytes_written = 1;
437        driver.start_read(buffer);
438
439        loop {
440            if let Some(status) = driver.respond_to_read_step(buffer, &mut bytes_written) {
441                return status;
442            }
443        }
444    }
445}
446
447impl<Dm: DriverMode> private::Sealed for I2cSlave<'_, Dm> {}
448
449#[derive(Debug, EnumSetType)]
450#[cfg_attr(feature = "defmt", derive(defmt::Format))]
451#[non_exhaustive]
452pub(crate) enum Event {
453    SlaveStretch,
454    TransComplete,
455    Nack,
456    StartDetected,
457    ReceiveBoundary,
458}
459
460#[must_use = "futures do nothing unless you `.await` or poll them"]
461struct I2cSlaveFuture<'a> {
462    regs: &'a RegisterBlock,
463    state: &'a State,
464    events: EnumSet<Event>,
465    _wake_lock: WakeLock,
466}
467
468impl<'a> I2cSlaveFuture<'a> {
469    fn new(regs: &'a RegisterBlock, state: &'a State, events: EnumSet<Event>) -> Self {
470        Self {
471            regs,
472            state,
473            events,
474            _wake_lock: WakeLock::new(),
475        }
476    }
477}
478
479impl Future for I2cSlaveFuture<'_> {
480    type Output = ();
481
482    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
483        self.state.waker.register(cx.waker());
484
485        let raw = self.regs.int_raw().read();
486        let triggered = (self.events.contains(Event::SlaveStretch)
487            && raw.slave_stretch().bit_is_set())
488            || (self.events.contains(Event::TransComplete) && raw.trans_complete().bit_is_set())
489            || (self.events.contains(Event::Nack) && raw.nack().bit_is_set())
490            || (self.events.contains(Event::StartDetected) && raw.det_start().bit_is_set());
491
492        let boundary_pending = self.events.contains(Event::ReceiveBoundary)
493            && self.state.receive_boundary().is_pending()
494            && {
495                let status = self.regs.sr().read();
496                status.slave_addressed().bit_is_clear()
497                    || status.slave_rw().bit_is_set()
498                    || Driver::address_pending(&status)
499            };
500
501        if triggered || boundary_pending || Driver::check_errors(self.regs).is_err() {
502            Poll::Ready(())
503        } else {
504            self.regs.int_ena().modify(|_, w| {
505                if self.events.contains(Event::SlaveStretch) {
506                    w.slave_stretch().set_bit();
507                }
508                if self.events.contains(Event::TransComplete) {
509                    w.trans_complete().set_bit();
510                }
511                if self.events.contains(Event::Nack) {
512                    w.nack().set_bit();
513                }
514                if self.events.contains(Event::StartDetected) {
515                    w.det_start().set_bit();
516                }
517                w.arbitration_lost().set_bit();
518                w.time_out().set_bit();
519                w.scl_st_to().set_bit();
520                w.scl_main_st_to().set_bit();
521                w
522            });
523            Poll::Pending
524        }
525    }
526}
527
528impl Drop for I2cSlaveFuture<'_> {
529    fn drop(&mut self) {
530        self.regs.int_ena().write(|w| unsafe { w.bits(0) });
531    }
532}
533
534#[ram]
535fn async_handler(info: &Info, state: &State) {
536    info.regs().int_ena().write(|w| unsafe { w.bits(0) });
537    state.waker.wake();
538}
539
540#[derive(Debug, Default, Clone, Copy)]
541struct ReceiveBoundary {
542    start: bool,
543    stop: bool,
544}
545
546impl ReceiveBoundary {
547    fn is_pending(self) -> bool {
548        self.start || self.stop
549    }
550}
551
552// Public for the sealed instance interface.
553#[doc(hidden)]
554#[non_exhaustive]
555pub struct State {
556    pub(crate) waker: AtomicWaker,
557    rx_start_pending: AtomicBool,
558    rx_stop_pending: AtomicBool,
559}
560
561impl State {
562    fn receive_boundary(&self) -> ReceiveBoundary {
563        ReceiveBoundary {
564            start: self.rx_start_pending.load(Ordering::Relaxed),
565            stop: self.rx_stop_pending.load(Ordering::Relaxed),
566        }
567    }
568
569    fn set_receive_boundary(&self, boundary: ReceiveBoundary) {
570        self.rx_start_pending
571            .store(boundary.start, Ordering::Relaxed);
572        self.rx_stop_pending.store(boundary.stop, Ordering::Relaxed);
573    }
574}
575
576impl core::fmt::Debug for State {
577    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
578        f.debug_struct("State")
579            .field("waker", &"<AtomicWaker>")
580            .field("receive_boundary", &self.receive_boundary())
581            .finish()
582    }
583}
584
585// Public for the sealed instance interface.
586#[doc(hidden)]
587#[derive(Debug)]
588#[non_exhaustive]
589pub struct Info {
590    pub(crate) register_block: *const RegisterBlock,
591    pub(crate) peripheral: crate::system::Peripheral,
592    pub(crate) async_handler: InterruptHandler,
593    pub(crate) clock_instance: I2cInstance,
594    pub(crate) scl_output: OutputSignal,
595    pub(crate) scl_input: InputSignal,
596    pub(crate) sda_output: OutputSignal,
597    pub(crate) sda_input: InputSignal,
598}
599
600impl Info {
601    pub(crate) fn regs(&self) -> &RegisterBlock {
602        unsafe { &*self.register_block }
603    }
604}
605
606unsafe impl Sync for Info {}
607
608// Public constructor bound; implementations are sealed.
609#[doc(hidden)]
610pub trait Instance: crate::private::Sealed + any::Degrade {
611    #[doc(hidden)]
612    fn parts(&self) -> (&Info, &State);
613
614    #[doc(hidden)]
615    #[inline(always)]
616    fn info(&self) -> &Info {
617        self.parts().0
618    }
619
620    #[doc(hidden)]
621    #[inline(always)]
622    fn state(&self) -> &State {
623        self.parts().1
624    }
625}
626
627struct Driver<'a> {
628    info: &'a Info,
629    state: &'a State,
630}
631
632impl Driver<'_> {
633    // Stretch-cause encodings for ESP32-C3 and ESP32-C6:
634    // https://github.com/espressif/esp-idf/blob/d445e947156f276dfe0db5804e4edf6ae90fe6fb/components/esp_hal_i2c/esp32c3/include/hal/i2c_ll.h#L363-L377
635    const STRETCH_ADDRESS_MATCH: u8 = 0;
636    const STRETCH_TX_EMPTY: u8 = 1;
637    const STRETCH_RX_FULL: u8 = 2;
638
639    fn regs(&self) -> &RegisterBlock {
640        self.info.regs()
641    }
642
643    fn connect_pin(
644        pin: crate::gpio::interconnect::OutputSignal<'_>,
645        input: InputSignal,
646        output: OutputSignal,
647        guard: &mut PinGuard,
648    ) {
649        pin.set_output_high(true);
650        pin.apply_output_config(
651            &OutputConfig::default()
652                .with_drive_mode(DriveMode::OpenDrain)
653                .with_pull(Pull::Up),
654        );
655        pin.set_output_enable(true);
656        pin.set_input_enable(true);
657        input.connect_to(&pin);
658        *guard = interconnect::OutputSignal::connect_with_guard(pin, output);
659    }
660
661    fn init_slave(&self) {
662        self.regs().ctr().write(|w| {
663            w.ms_mode().clear_bit();
664            w.rx_full_ack_level().clear_bit();
665            w.sda_force_out().set_bit();
666            w.scl_force_out().set_bit();
667            #[cfg(i2c_master_has_arbitration_en)]
668            w.arbitration_en().clear_bit();
669            w.tx_lsb_first().clear_bit();
670            w.rx_lsb_first().clear_bit();
671            w
672        });
673
674        self.reset_fifo();
675
676        self.regs().fifo_conf().modify(|_, w| {
677            w.nonfifo_en().clear_bit();
678            w
679        });
680    }
681
682    fn update_registers(&self) {
683        #[cfg(i2c_master_has_conf_update)]
684        self.regs().ctr().modify(|_, w| w.conf_upgate().set_bit());
685    }
686
687    fn setup(&self, config: &Config) -> Result<(), ConfigError> {
688        let address = match config.address {
689            I2cAddress::SevenBit(addr) if addr <= 0x7F => addr,
690            _ => return Err(ConfigError::AddressInvalid),
691        };
692
693        self.state.set_receive_boundary(ReceiveBoundary::default());
694        // FIFO resets do not clear an active transaction.
695        crate::system::PeripheralClockControl::reset(self.info.peripheral);
696        self.init_slave();
697
698        let regs = self.regs();
699        regs.slave_addr().write(|w| unsafe {
700            w.slave_addr().bits(address as u16);
701            w.addr_10bit_en().clear_bit()
702        });
703        regs.to().modify(|_, w| unsafe {
704            w.time_out_en().set_bit();
705            w.time_out_value().bits(14);
706            w
707        });
708
709        regs.clk_conf().modify(|_, w| w.sclk_sel().clear_bit());
710
711        regs.ctr()
712            .modify(|_, w| w.addr_broadcasting_en().clear_bit());
713
714        regs.fifo_conf().modify(|_, w| {
715            w.fifo_prt_en().set_bit();
716            unsafe { w.txfifo_wm_thrhd().bits(0) }
717        });
718
719        regs.fifo_conf()
720            .modify(|_, w| unsafe { w.rxfifo_wm_thrhd().bits(0x1F) });
721
722        // SDA hold/sample periods match ESP-IDF.
723        // https://github.com/espressif/esp-idf/blob/d445e947156f276dfe0db5804e4edf6ae90fe6fb/components/esp_driver_i2c/i2c_slave.c#L303
724        regs.sda_hold().write(|w| unsafe { w.time().bits(10u16) });
725        regs.sda_sample().write(|w| unsafe { w.time().bits(10u16) });
726
727        regs.int_ena().write(|w| unsafe { w.bits(0) });
728        regs.int_clr().write(|w| unsafe { w.bits(0x3fff) });
729
730        regs.scl_stretch_conf().modify(|_, w| unsafe {
731            w.stretch_protect_num().bits(0x3ff);
732            // Service each byte before the master can cross a transaction boundary.
733            w.slave_byte_ack_ctl_en().set_bit();
734            w.slave_byte_ack_lvl().clear_bit();
735            w.slave_scl_stretch_en().set_bit()
736        });
737
738        regs.scl_stretch_conf()
739            .modify(|_, w| w.slave_scl_stretch_clr().set_bit());
740        self.update_registers();
741
742        Ok(())
743    }
744
745    fn reset_tx_fifo(&self) {
746        let regs = self.regs();
747        regs.fifo_conf().modify(|_, w| w.tx_fifo_rst().set_bit());
748        regs.fifo_conf().modify(|_, w| w.tx_fifo_rst().clear_bit());
749    }
750
751    fn reset_fifo(&self) {
752        self.reset_tx_fifo();
753        let regs = self.regs();
754        regs.fifo_conf().modify(|_, w| w.rx_fifo_rst().set_bit());
755        regs.fifo_conf().modify(|_, w| w.rx_fifo_rst().clear_bit());
756    }
757
758    fn check_errors(regs: &RegisterBlock) -> Result<(), Error> {
759        let r = regs.int_raw().read();
760
761        if r.arbitration_lost().bit_is_set() {
762            return Err(Error::ArbitrationLost);
763        }
764        // The timeout counter also runs while the slave holds SCL low.
765        // A later stretch can hide an earlier timeout; preserve the pending request.
766        if r.time_out().bit_is_set()
767            || r.scl_st_to().bit_is_set()
768            || r.scl_main_st_to().bit_is_set()
769        {
770            let status = regs.sr().read();
771            // ACK stretching can retain the previous TX stretch cause.
772            let tx_finished = status.slave_rw().bit_is_set()
773                && status.stretch_cause().bits() == Self::STRETCH_TX_EMPTY
774                && r.nack().bit_is_set();
775            if r.slave_stretch().bit_is_clear() || tx_finished {
776                return Err(Error::Timeout);
777            }
778        }
779        Ok(())
780    }
781
782    fn release_stretch(&self) {
783        use esp_sync::raw::{RawLock, SingleCoreInterruptLock};
784
785        let regs = self.regs();
786        // A preemption between the stretch release and the timeout restart stops timeout detection.
787        let token = unsafe { SingleCoreInterruptLock.enter() };
788        // Restart timeout counting when the master regains control of SCL.
789        regs.to().modify(|_, w| w.time_out_en().clear_bit());
790        self.update_registers();
791        regs.int_clr().write(|w| {
792            w.slave_stretch().clear_bit_by_one();
793            w.scl_st_to().clear_bit_by_one();
794            w.scl_main_st_to().clear_bit_by_one();
795            w.time_out().clear_bit_by_one()
796        });
797        regs.scl_stretch_conf()
798            .modify(|_, w| w.slave_scl_stretch_clr().set_bit());
799        regs.to().modify(|_, w| w.time_out_en().set_bit());
800        self.update_registers();
801        unsafe { SingleCoreInterruptLock.exit(token) };
802    }
803
804    fn recover(&self) {
805        let address = self.regs().slave_addr().read().slave_addr().bits() as u8;
806        self.setup(&Config::new(address)).ok();
807    }
808
809    fn start_listen(&self) {
810        if Self::check_errors(self.regs()).is_err() {
811            self.recover();
812        } else {
813            self.reset_tx_fifo();
814        }
815    }
816
817    fn address_pending(status: &crate::pac::i2c0::sr::R) -> bool {
818        // SLAVE_ADDRESSED retains the preceding match during address shift/ACK.
819        matches!(status.scl_main_state_last().bits(), 1 | 2)
820    }
821
822    fn take_receive_events(&self, boundary: &mut ReceiveBoundary) -> crate::pac::i2c0::int_raw::R {
823        let regs = self.regs();
824        let ints = regs.int_raw().read();
825        boundary.start |= ints.det_start().bit_is_set();
826        boundary.stop |= ints.trans_complete().bit_is_set();
827        // Acknowledge boundaries before sampling the FIFO they delimit.
828        regs.int_clr().write(|w| {
829            w.trans_complete().bit(ints.trans_complete().bit());
830            w.det_start().bit(ints.det_start().bit())
831        });
832        ints
833    }
834
835    fn listen_step(
836        &self,
837        buffer: &mut [u8],
838        bytes_read: &mut usize,
839    ) -> Option<Result<Command, Error>> {
840        let regs = self.regs();
841        let error = Self::check_errors(regs).err();
842        let mut boundary = self.state.receive_boundary();
843        let mut ints = self.take_receive_events(&mut boundary);
844        let mut status = regs.sr().read();
845        // An ACK stretch can start between the interrupt and FIFO snapshots.
846        if ints.slave_stretch().bit_is_clear() && regs.int_raw().read().slave_stretch().bit_is_set()
847        {
848            ints = self.take_receive_events(&mut boundary);
849            status = regs.sr().read();
850        }
851
852        let fifo_overflow = ints.rxfifo_ovf().bit_is_set();
853        let stretched = ints.slave_stretch().bit_is_set();
854        let read_pending = stretched
855            && status.stretch_cause().bits() == Self::STRETCH_ADDRESS_MATCH
856            && status.slave_rw().bit_is_set();
857        let fifo_count = status.rxfifo_cnt().bits() as usize;
858        let addressed = status.slave_addressed().bit_is_set() && !Self::address_pending(&status);
859        let active_write = addressed && status.slave_rw().bit_is_clear();
860        let next_write_byte = stretched
861            && active_write
862            // Byte-ACK stretching can retain an earlier RX-full cause.
863            && (fifo_count < FIFO_SIZE || status.stretch_cause().bits() != Self::STRETCH_RX_FULL);
864        // FIFO insertion precedes ACK stretching. Until ACK, a buffered byte
865        // may belong to either side of a previously observed boundary.
866        let wait_for_ack = boundary.is_pending() && fifo_count > 0 && active_write && !stretched;
867        let previous_bytes = fifo_count.saturating_sub(usize::from(next_write_byte));
868        let write_ended = !wait_for_ack
869            && ((boundary.stop && (*bytes_read > 0 || previous_bytes > 0 || fifo_overflow))
870                || (boundary.start
871                    && (*bytes_read > 0
872                        || (previous_bytes > 0 && (next_write_byte || !addressed)))));
873
874        // A following request's timeout must not discard a completed write.
875        if let Some(error) = error
876            && (error != Error::Timeout || !write_ended)
877        {
878            self.recover();
879            return Some(Err(error));
880        }
881
882        if wait_for_ack {
883            self.state.set_receive_boundary(boundary);
884            return None;
885        }
886        self.state.set_receive_boundary(ReceiveBoundary::default());
887
888        if stretched || write_ended || fifo_overflow {
889            let count = if write_ended {
890                previous_bytes
891            } else {
892                fifo_count
893            };
894            for _ in 0..count {
895                let byte = regs.data().read().fifo_rdata().bits();
896                if let Some(dest) = buffer.get_mut(*bytes_read) {
897                    *dest = byte;
898                }
899                *bytes_read = bytes_read.saturating_add(1);
900            }
901        }
902
903        let overflow = *bytes_read > buffer.len() || fifo_overflow;
904        let write_pending = *bytes_read > 0 || overflow;
905        let write_complete = read_pending || write_ended;
906        // Keep the next request stretched until the next listen call.
907        if write_pending && write_complete {
908            regs.int_clr().write(|w| w.rxfifo_ovf().clear_bit_by_one());
909            if fifo_overflow && status.stretch_cause().bits() == Self::STRETCH_RX_FULL {
910                self.release_stretch();
911            }
912            return Some(if overflow {
913                Err(Error::Overflow)
914            } else {
915                Ok(Command::Write(*bytes_read))
916            });
917        }
918
919        if stretched {
920            if read_pending {
921                regs.int_clr()
922                    .write(|w| w.slave_stretch().clear_bit_by_one());
923                return Some(Ok(Command::Read));
924            }
925            self.release_stretch();
926        }
927
928        None
929    }
930
931    fn start_read(&self, buffer: &[u8]) {
932        let regs = self.regs();
933        // Queue one byte at a time to count short reads correctly.
934        regs.data()
935            .write(|w| unsafe { w.fifo_rdata().bits(buffer.first().copied().unwrap_or(0xff)) });
936
937        // Clear the current START before releasing the address stretch.
938        regs.int_clr().write(|w| unsafe {
939            w.bits(0x3fff);
940            w.det_start().clear_bit_by_one()
941        });
942        self.release_stretch();
943    }
944
945    fn respond_to_read_step(
946        &self,
947        buffer: &[u8],
948        bytes_written: &mut usize,
949    ) -> Option<Result<ReadStatus, Error>> {
950        let regs = self.regs();
951        let error = Self::check_errors(regs).err();
952        let ints = regs.int_raw().read();
953
954        // A later timeout must not replace a completed read.
955        if let Some(error) = error
956            && (error != Error::Timeout || ints.nack().bit_is_clear())
957        {
958            self.recover();
959            return Some(Err(error));
960        }
961
962        if ints.nack().bit_is_set()
963            || ints.trans_complete().bit_is_set()
964            || ints.det_start().bit_is_set()
965        {
966            if ints.nack().bit_is_clear() {
967                self.recover();
968                return Some(Err(Error::ReadAborted));
969            }
970            let bytes_read =
971                bytes_written.saturating_sub(regs.sr().read().txfifo_cnt().bits() as usize);
972            // START and STOP can already belong to the next request.
973            regs.int_clr().write(|w| w.nack().clear_bit_by_one());
974            self.reset_tx_fifo();
975            let status = if bytes_read > buffer.len() {
976                Ok(ReadStatus::NeedMoreBytes)
977            } else if bytes_read < buffer.len() {
978                u16::try_from(buffer.len() - bytes_read)
979                    .map(ReadStatus::LeftoverBytes)
980                    .map_err(|_| Error::ResponseTooLong)
981            } else {
982                Ok(ReadStatus::Done)
983            };
984            return Some(status);
985        }
986
987        if ints.slave_stretch().bit_is_set() {
988            if regs.sr().read().stretch_cause().bits() == Self::STRETCH_TX_EMPTY {
989                let byte = buffer.get(*bytes_written).copied().unwrap_or(0xff);
990                regs.data().write(|w| unsafe { w.fifo_rdata().bits(byte) });
991                *bytes_written = bytes_written.saturating_add(1);
992            }
993            self.release_stretch();
994        }
995
996        None
997    }
998}
999
1000#[cfg(i2c_slave_i2c0)]
1001impl crate::i2c::slave::Instance for crate::peripherals::I2C0<'_> {
1002    fn parts(&self) -> (&Info, &State) {
1003        #[handler]
1004        #[ram]
1005        pub(super) fn irq_handler() {
1006            async_handler(&PERIPHERAL, &STATE);
1007        }
1008
1009        static STATE: State = State {
1010            waker: AtomicWaker::new(),
1011            rx_start_pending: AtomicBool::new(false),
1012            rx_stop_pending: AtomicBool::new(false),
1013        };
1014
1015        static PERIPHERAL: Info = Info {
1016            register_block: crate::peripherals::I2C0::ptr(),
1017            peripheral: crate::system::Peripheral::I2cExt0,
1018            async_handler: irq_handler,
1019            clock_instance: I2cInstance::I2c0,
1020            scl_output: OutputSignal::I2CEXT0_SCL,
1021            scl_input: InputSignal::I2CEXT0_SCL,
1022            sda_output: OutputSignal::I2CEXT0_SDA,
1023            sda_input: InputSignal::I2CEXT0_SDA,
1024        };
1025        (&PERIPHERAL, &STATE)
1026    }
1027}
1028
1029#[cfg(i2c_slave_i2c1)]
1030impl crate::i2c::slave::Instance for crate::peripherals::I2C1<'_> {
1031    fn parts(&self) -> (&Info, &State) {
1032        #[handler]
1033        #[ram]
1034        pub(super) fn irq_handler() {
1035            async_handler(&PERIPHERAL, &STATE);
1036        }
1037
1038        static STATE: State = State {
1039            waker: AtomicWaker::new(),
1040            rx_start_pending: AtomicBool::new(false),
1041            rx_stop_pending: AtomicBool::new(false),
1042        };
1043
1044        static PERIPHERAL: Info = Info {
1045            register_block: crate::peripherals::I2C1::ptr(),
1046            peripheral: crate::system::Peripheral::I2cExt1,
1047            async_handler: irq_handler,
1048            clock_instance: I2cInstance::I2c1,
1049            scl_output: OutputSignal::I2CEXT1_SCL,
1050            scl_input: InputSignal::I2CEXT1_SCL,
1051            sda_output: OutputSignal::I2CEXT1_SDA,
1052            sda_input: InputSignal::I2CEXT1_SDA,
1053        };
1054        (&PERIPHERAL, &STATE)
1055    }
1056}
1057
1058crate::any_peripheral! {
1059    /// Any I2C peripheral in slave mode.
1060    pub peripheral AnyI2c<'d> {
1061        #[cfg(i2c_slave_i2c0)]
1062        I2c0(crate::peripherals::I2C0<'d>),
1063        #[cfg(i2c_slave_i2c1)]
1064        I2c1(crate::peripherals::I2C1<'d>),
1065    }
1066}
1067
1068impl crate::i2c::slave::Instance for AnyI2c<'_> {
1069    fn parts(&self) -> (&Info, &State) {
1070        any::delegate!(self, i2c => { crate::i2c::slave::Instance::parts(i2c) })
1071    }
1072}
1073
1074impl AnyI2c<'_> {
1075    fn bind_peri_interrupt(&self, handler: InterruptHandler) {
1076        any::delegate!(self, i2c => { i2c.bind_peri_interrupt(handler) })
1077    }
1078
1079    fn disable_peri_interrupt(&self) {
1080        any::delegate!(self, i2c => { i2c.disable_peri_interrupt() })
1081    }
1082
1083    fn enable_peri_interrupt(&self, priority: crate::interrupt::Priority) {
1084        any::delegate!(self, i2c => { i2c.enable_peri_interrupt(priority) })
1085    }
1086
1087    fn set_interrupt_handler(&self, handler: InterruptHandler) {
1088        self.disable_peri_interrupt();
1089
1090        self.info().regs().int_ena().write(|w| unsafe { w.bits(0) });
1091
1092        self.bind_peri_interrupt(handler);
1093        self.enable_peri_interrupt(handler.priority());
1094    }
1095}