1use 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
54pub const FIFO_SIZE: usize = property!("i2c_master.fifo_size");
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59#[cfg_attr(feature = "defmt", derive(defmt::Format))]
60#[non_exhaustive]
61pub enum Error {
62 Timeout,
64 ArbitrationLost,
66 Overflow,
68 ResponseTooLong,
70 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)]
101#[cfg_attr(feature = "defmt", derive(defmt::Format))]
102#[non_exhaustive]
103pub struct Config {
104 address: I2cAddress,
106}
107
108impl Config {
109 pub fn new(address: impl Into<I2cAddress>) -> Self {
113 Config {
114 address: address.into(),
115 }
116 }
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121#[cfg_attr(feature = "defmt", derive(defmt::Format))]
122#[non_exhaustive]
123pub enum ConfigError {
124 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#[derive(Debug, Copy, Clone, Eq, PartialEq)]
140#[cfg_attr(feature = "defmt", derive(defmt::Format))]
141pub enum Command {
142 Read,
144 Write(usize),
146}
147
148#[derive(Debug, Copy, Clone, Eq, PartialEq)]
150#[cfg_attr(feature = "defmt", derive(defmt::Format))]
151pub enum ReadStatus {
152 Done,
154 NeedMoreBytes,
156 LeftoverBytes(u16),
158}
159
160#[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 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 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 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 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 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 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 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 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 pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
380 self.driver().setup(config)
381 }
382
383 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 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#[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#[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#[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 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 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 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 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 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 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 let token = unsafe { SingleCoreInterruptLock.enter() };
788 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 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 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 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 && (fifo_count < FIFO_SIZE || status.stretch_cause().bits() != Self::STRETCH_RX_FULL);
864 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 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 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 regs.data()
935 .write(|w| unsafe { w.fifo_rdata().bits(buffer.first().copied().unwrap_or(0xff)) });
936
937 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 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 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 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}