Skip to main content

m5stack_core/io/
shared_i2c.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2use embassy_sync::mutex::Mutex;
3use esp_hal::{Async, i2c::master::I2c};
4use esp_sync::RawMutex;
5
6/// Shared I2C bus for cooperative tasks on one core.
7///
8/// NOT `Send`/`Sync`, deliberately. `I2c<'static, Async>` is `!Send` in esp-hal
9/// (`PhantomData<*const ()>`) because an async peripheral's wakers and interrupt
10/// state belong to the core that armed it with `into_async()`.
11///
12/// This type used to carry `unsafe impl Send`/`Sync` justified by two claims:
13/// that AW9523B init runs on PRO before APP starts, and that the PPS/AXP2101
14/// tasks are cooperative. The first stopped being true once consumers moved I2C
15/// bring-up onto the APP core (so the IRQ binds there instead of beside the BLE
16/// controller's level-1 IRQ on PRO). The second is an argument about *access*,
17/// while `Send` is a claim about *moving the value between threads* — a
18/// different property that cooperative scheduling does not establish.
19///
20/// Neither claim can be supported, so the impls are gone. `!Send` is now the
21/// compiler's to enforce: a consumer that tries to move the bus to another core
22/// gets a build error instead of silent, unchecked breakage.
23///
24/// The lock's own flag check takes `esp_sync::RawMutex`: safe against
25/// preemption from any context, and per-instance rather than the global critical
26/// section. It is not held across the I2C transaction (the guard is released at
27/// the next `.await`).
28pub struct SharedI2cBus(Mutex<RawMutex, I2c<'static, Async>>);
29
30impl SharedI2cBus {
31    pub const fn new(i2c: I2c<'static, Async>) -> Self {
32        Self(Mutex::new(i2c))
33    }
34
35    pub fn lock(
36        &self,
37    ) -> impl core::future::Future<
38        Output = embassy_sync::mutex::MutexGuard<'_, RawMutex, I2c<'static, Async>>,
39    > {
40        self.0.lock()
41    }
42}