Skip to content

Commit

Permalink
fixup examples and esp-now
Browse files Browse the repository at this point in the history
  • Loading branch information
MabezDev committed Oct 29, 2024
1 parent 0916d8a commit b126301
Show file tree
Hide file tree
Showing 24 changed files with 167 additions and 151 deletions.
35 changes: 3 additions & 32 deletions esp-wifi/src/ble/controller/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ impl Write for BleConnector<'_> {

/// Async Interface
#[cfg(feature = "async")]
pub mod asynch {
pub(crate) mod asynch {
use core::task::Poll;

use bt_hci::{
Expand All @@ -95,45 +95,16 @@ pub mod asynch {
WriteHci,
};
use embassy_sync::waitqueue::AtomicWaker;
use embedded_io::ErrorType;

use super::{read_hci, send_hci, BleConnectorError};
use crate::{
ble::ble::have_hci_read_data,
hal::peripheral::{Peripheral, PeripheralRef},
EspWifiInitialization,
};
use super::*;
use crate::ble::ble::have_hci_read_data;

static HCI_WAKER: AtomicWaker = AtomicWaker::new();

pub(crate) fn hci_read_data_available() {
HCI_WAKER.wake();
}

/// Async HCI connector
pub struct BleConnector<'d> {
_device: PeripheralRef<'d, crate::hal::peripherals::BT>,
}

impl<'d> BleConnector<'d> {
pub fn new(
init: &'d EspWifiController<'d>,
device: impl Peripheral<P = crate::hal::peripherals::BT> + 'd,
) -> BleConnector<'d> {
if !init.is_ble() {
panic!("Not initialized for BLE use");
}

Self {
_device: device.into_ref(),
}
}
}

impl ErrorType for BleConnector<'_> {
type Error = BleConnectorError;
}

impl embedded_io_async::Read for BleConnector<'_> {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, BleConnectorError> {
if !have_hci_read_data() {
Expand Down
1 change: 1 addition & 0 deletions esp-wifi/src/ble/npl.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use core::{
cell::RefCell,
ptr::{addr_of, addr_of_mut},
sync::atomic::Ordering,
};

use critical_section::Mutex;
Expand Down
28 changes: 23 additions & 5 deletions esp-wifi/src/esp_now/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::{
compat::queue::SimpleQueue,
hal::peripheral::{Peripheral, PeripheralRef},
wifi::{Protocol, RxControlInfo},
EspWifiInitialization,
EspWifiController,
};

/// Maximum payload length
Expand Down Expand Up @@ -465,6 +465,21 @@ impl<'d> EspNowManager<'d> {
}
}

impl<'d> Drop for EspNowManager<'d> {
fn drop(&mut self) {
if unwrap!(
crate::flags::WIFI.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
Some(x.saturating_sub(1))
})
) == 0
{
if let Err(e) = crate::wifi::wifi_deinit() {
warn!("Failed to cleanly deinit wifi: {:?}", e);
}
}
}
}

/// This is the sender part of ESP-NOW. You can get this sender by splitting
/// a `EspNow` instance.
///
Expand Down Expand Up @@ -603,10 +618,10 @@ impl<'d> Drop for EspNowRc<'d> {
/// Currently this implementation (when used together with traditional Wi-Fi)
/// ONLY support STA mode.
pub struct EspNow<'d> {
_device: Option<PeripheralRef<'d, crate::hal::peripherals::WIFI>>,
manager: EspNowManager<'d>,
sender: EspNowSender<'d>,
receiver: EspNowReceiver<'d>,
_phantom: PhantomData<&'d ()>,
}

impl<'d> EspNow<'d> {
Expand All @@ -633,20 +648,23 @@ impl<'d> EspNow<'d> {
inited: &'d EspWifiController<'d>,
device: Option<PeripheralRef<'d, crate::hal::peripherals::WIFI>>,
) -> Result<EspNow<'d>, EspNowError> {
if !inited.is_wifi() {
return Err(EspNowError::Error(Error::NotInitialized));
if !inited.wifi() {
// if wifi isn't already enabled, and we try to coexist - panic
assert!(device.is_some());
unwrap!(crate::wifi::wifi_init()); // TODO should we return an error
// here?
}

let espnow_rc = EspNowRc::new()?;
let esp_now = EspNow {
_device: device,
manager: EspNowManager {
_rc: espnow_rc.clone(),
},
sender: EspNowSender {
_rc: espnow_rc.clone(),
},
receiver: EspNowReceiver { _rc: espnow_rc },
_phantom: PhantomData,
};
check_error!({ esp_wifi_set_mode(wifi_mode_t_WIFI_MODE_STA) })?;
check_error!({ esp_wifi_start() })?;
Expand Down
8 changes: 4 additions & 4 deletions esp-wifi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,10 @@ const _: () = {
type TimeBase = PeriodicTimer<'static, AnyTimer>;

pub(crate) mod flags {
use portable_atomic::AtomicBool;
use portable_atomic::{AtomicBool, AtomicUsize};

pub(crate) static INITD: AtomicBool = AtomicBool::new(false);
pub(crate) static WIFI: AtomicBool = AtomicBool::new(false);
pub(crate) static WIFI: AtomicUsize = AtomicUsize::new(0);
pub(crate) static BLE: AtomicBool = AtomicBool::new(false);
}

Expand All @@ -255,7 +255,7 @@ pub struct EspWifiController<'d> {
impl<'d> EspWifiController<'d> {
/// Is the WiFi part of the radio running
pub fn wifi(&self) -> bool {
crate::flags::WIFI.load(Ordering::Acquire)
crate::flags::WIFI.load(Ordering::Acquire) > 0
}

/// Is the BLE part of the radio running
Expand Down Expand Up @@ -360,7 +360,7 @@ impl EspWifiTimerSource for TimeBase {
/// # }
/// ```
pub fn init<'d, T: EspWifiTimerSource>(
mut timer: impl Peripheral<P = T> + 'd,
timer: impl Peripheral<P = T> + 'd,
rng: hal::rng::Rng,
_radio_clocks: impl Peripheral<P = hal::peripherals::RADIO_CLK> + 'd,
) -> Result<EspWifiController<'d>, InitializationError> {
Expand Down
22 changes: 16 additions & 6 deletions esp-wifi/src/wifi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1593,6 +1593,8 @@ pub(crate) fn wifi_init() -> Result<(), WifiError> {
chip_specific::g_misc_nvs = addr_of!(NVS_STRUCT) as u32;
}

crate::flags::WIFI.fetch_add(1, Ordering::SeqCst);

Ok(())
}
}
Expand All @@ -1601,7 +1603,6 @@ pub(crate) fn wifi_deinit() -> Result<(), crate::InitializationError> {
esp_wifi_result!(unsafe { esp_wifi_stop() })?;
esp_wifi_result!(unsafe { esp_wifi_deinit_internal() })?;
esp_wifi_result!(unsafe { esp_supplicant_deinit() })?;
crate::flags::WIFI.store(false, Ordering::Release);
Ok(())
}

Expand Down Expand Up @@ -1901,7 +1902,7 @@ pub fn new_with_config<'d, MODE: WifiDeviceMode>(
/// If you want to use AP-STA mode, use `[new_ap_sta]`.
pub fn new_with_mode<'d, MODE: WifiDeviceMode>(
inited: &'d EspWifiController<'d>,
device: impl crate::hal::peripheral::Peripheral<P = crate::hal::peripherals::WIFI> + 'd,
device: impl Peripheral<P = crate::hal::peripherals::WIFI> + 'd,
_mode: MODE,
) -> Result<(WifiDevice<'d, MODE>, WifiController<'d>), WifiError> {
new_with_config(inited, device, <MODE as Sealed>::Config::default())
Expand Down Expand Up @@ -2509,19 +2510,28 @@ pub struct WifiController<'d> {

impl<'d> Drop for WifiController<'d> {
fn drop(&mut self) {
if let Err(e) = crate::wifi::wifi_deinit() {
warn!("Failed to cleanly deinit wifi: {:?}", e);
if unwrap!(
crate::flags::WIFI.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
Some(x.saturating_sub(1))
})
) == 0
{
if let Err(e) = crate::wifi::wifi_deinit() {
warn!("Failed to cleanly deinit wifi: {:?}", e);
}
}
}
}

impl<'d> WifiController<'d> {
pub(crate) fn new_with_config(
_inited: &'d EspWifiController<'d>,
inited: &'d EspWifiController<'d>,
_device: PeripheralRef<'d, crate::hal::peripherals::WIFI>,
config: Configuration,
) -> Result<Self, WifiError> {
wifi_init()?;
if !inited.wifi() {
crate::wifi::wifi_init()?;
}

// We set up the controller with the default config because we need to call
// `set_configuration` to apply the actual configuration, and it will update the
Expand Down
2 changes: 1 addition & 1 deletion esp-wifi/src/wifi/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use smoltcp::{
};

use super::{WifiApDevice, WifiController, WifiDevice, WifiDeviceMode, WifiError, WifiStaDevice};
use crate::{current_millis, EspWifiController};
use crate::{timestamp, EspWifiController};

fn setup_iface<'a, MODE: WifiDeviceMode>(
device: &mut WifiDevice<'_, MODE>,
Expand Down
14 changes: 3 additions & 11 deletions examples/src/bin/wifi_80211_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,8 @@ use core::marker::PhantomData;

use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::{
delay::Delay,
prelude::*,
rng::Rng,
timer::{timg::TimerGroup, AnyTimer, PeriodicTimer},
};
use esp_wifi::{init, wifi, EspWifiInitFor};
use esp_hal::{delay::Delay, prelude::*, rng::Rng, timer::timg::TimerGroup};
use esp_wifi::{init, wifi};
use ieee80211::{
common::{CapabilitiesInformation, FCFFlags},
element_chain,
Expand Down Expand Up @@ -47,12 +42,9 @@ fn main() -> ! {
let delay = Delay::new();

let timg0 = TimerGroup::new(peripherals.TIMG0);
let timer0: AnyTimer = timg0.timer0.into();
let timer = PeriodicTimer::new(timer0);

let init = init(
EspWifiInitFor::Wifi,
timer,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
)
Expand Down
2 changes: 0 additions & 2 deletions examples/src/bin/wifi_access_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ use esp_wifi::{
WifiApDevice,
},
wifi_interface::WifiStack,
EspWifiInitFor,
};
use smoltcp::iface::SocketStorage;

Expand All @@ -51,7 +50,6 @@ fn main() -> ! {
let timg0 = TimerGroup::new(peripherals.TIMG0);

let init = init(
EspWifiInitFor::Wifi,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
Expand Down
2 changes: 0 additions & 2 deletions examples/src/bin/wifi_access_point_with_sta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ use esp_wifi::{
Configuration,
},
wifi_interface::WifiStack,
EspWifiInitFor,
};
use smoltcp::{
iface::SocketStorage,
Expand All @@ -58,7 +57,6 @@ fn main() -> ! {
let timg0 = TimerGroup::new(peripherals.TIMG0);

let init = init(
EspWifiInitFor::Wifi,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
Expand Down
2 changes: 0 additions & 2 deletions examples/src/bin/wifi_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ use esp_wifi::{
WifiStaDevice,
},
wifi_interface::WifiStack,
EspWifiInitFor,
};
use smoltcp::{
iface::SocketStorage,
Expand Down Expand Up @@ -71,7 +70,6 @@ fn main() -> ! {
let timg0 = TimerGroup::new(peripherals.TIMG0);

let init = init(
EspWifiInitFor::Wifi,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
Expand Down
3 changes: 1 addition & 2 deletions examples/src/bin/wifi_ble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use esp_hal::{
timer::timg::TimerGroup,
};
use esp_println::println;
use esp_wifi::{ble::controller::BleConnector, init, EspWifiInitFor};
use esp_wifi::{ble::controller::BleConnector, init};

#[entry]
fn main() -> ! {
Expand All @@ -48,7 +48,6 @@ fn main() -> ! {
let timg0 = TimerGroup::new(peripherals.TIMG0);

let init = init(
EspWifiInitFor::Ble,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
Expand Down
2 changes: 0 additions & 2 deletions examples/src/bin/wifi_coex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ use esp_wifi::{
init,
wifi::{utils::create_network_interface, ClientConfiguration, Configuration, WifiStaDevice},
wifi_interface::WifiStack,
EspWifiInitFor,
};
use smoltcp::{
iface::SocketStorage,
Expand Down Expand Up @@ -82,7 +81,6 @@ fn main() -> ! {
let timg0 = TimerGroup::new(peripherals.TIMG0);

let init = init(
EspWifiInitFor::WifiBle,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
Expand Down
2 changes: 0 additions & 2 deletions examples/src/bin/wifi_dhcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ use esp_wifi::{
WifiStaDevice,
},
wifi_interface::WifiStack,
EspWifiInitFor,
};
use smoltcp::{
iface::SocketStorage,
Expand All @@ -59,7 +58,6 @@ fn main() -> ! {
let timg0 = TimerGroup::new(peripherals.TIMG0);

let init = init(
EspWifiInitFor::Wifi,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
Expand Down
18 changes: 10 additions & 8 deletions examples/src/bin/wifi_embassy_access_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use esp_wifi::{
WifiEvent,
WifiState,
},
EspWifiInitFor,
EspWifiController,
};

// When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html
Expand All @@ -67,13 +67,15 @@ async fn main(spawner: Spawner) -> ! {

let timg0 = TimerGroup::new(peripherals.TIMG0);

let init = init(
EspWifiInitFor::Wifi,
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
)
.unwrap();
let init = &*mk_static!(
EspWifiController<'static>,
init(
timg0.timer0,
Rng::new(peripherals.RNG),
peripherals.RADIO_CLK,
)
.unwrap()
);

let wifi = peripherals.WIFI;
let (wifi_interface, controller) =
Expand Down
Loading

0 comments on commit b126301

Please sign in to comment.