From 02c86bca5275328a15376176ff44487ab7655866 Mon Sep 17 00:00:00 2001 From: ceekdee Date: Fri, 21 Apr 2023 01:20:46 -0500 Subject: [PATCH] Add external LoRa physical layer functionality. --- embassy-lora/Cargo.toml | 8 +- embassy-lora/src/iv.rs | 325 ++++++++++++++++++ embassy-lora/src/lib.rs | 3 + embassy-stm32/src/spi/mod.rs | 2 +- embassy-stm32/src/subghz/mod.rs | 2 +- examples/nrf52840/Cargo.toml | 10 +- examples/nrf52840/src/bin/lora_cad.rs | 92 +++++ .../src/bin/lora_p2p_receive_duty_cycle.rs | 124 +++++++ examples/nrf52840/src/bin/lora_p2p_report.rs | 81 ----- examples/rp/Cargo.toml | 6 +- examples/stm32l0/Cargo.toml | 10 +- examples/stm32l0/src/bin/lora_p2p_receive.rs | 120 +++++++ examples/stm32wl/Cargo.toml | 13 +- examples/stm32wl/src/bin/lora_lorawan.rs | 88 +++++ examples/stm32wl/src/bin/lora_p2p_send.rs | 103 ++++++ 15 files changed, 884 insertions(+), 103 deletions(-) create mode 100644 embassy-lora/src/iv.rs create mode 100644 examples/nrf52840/src/bin/lora_cad.rs create mode 100644 examples/nrf52840/src/bin/lora_p2p_receive_duty_cycle.rs delete mode 100644 examples/nrf52840/src/bin/lora_p2p_report.rs create mode 100644 examples/stm32l0/src/bin/lora_p2p_receive.rs create mode 100644 examples/stm32wl/src/bin/lora_lorawan.rs create mode 100644 examples/stm32wl/src/bin/lora_p2p_send.rs diff --git a/embassy-lora/Cargo.toml b/embassy-lora/Cargo.toml index 50449dd4..20cfaf1b 100644 --- a/embassy-lora/Cargo.toml +++ b/embassy-lora/Cargo.toml @@ -22,6 +22,7 @@ sx127x = [] stm32wl = ["dep:embassy-stm32"] time = [] defmt = ["dep:defmt", "lorawan/defmt", "lorawan-device/defmt"] +external-lora-phy = ["dep:lora-phy"] [dependencies] @@ -35,8 +36,9 @@ embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-alpha.10" } embedded-hal-async = { version = "=0.2.0-alpha.1" } embassy-hal-common = { version = "0.1.0", path = "../embassy-hal-common", default-features = false } futures = { version = "0.3.17", default-features = false, features = [ "async-await" ] } -embedded-hal = { version = "0.2", features = ["unproven"] } +embedded-hal = { version = "0.2.6" } bit_field = { version = "0.10" } -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"] } -lorawan = { version = "0.7.2", default-features = false } +lora-phy = { version = "1", path = "../../lora-phy", optional = true } +lorawan-device = { version = "0.9.0", path = "../../rust-lorawan/device", default-features = false, features = ["async"] } +lorawan = { version = "0.7.2", path = "../../rust-lorawan/encoding", default-features = false } diff --git a/embassy-lora/src/iv.rs b/embassy-lora/src/iv.rs new file mode 100644 index 00000000..f8113440 --- /dev/null +++ b/embassy-lora/src/iv.rs @@ -0,0 +1,325 @@ +#[cfg(feature = "stm32wl")] +use embassy_stm32::interrupt::*; +#[cfg(feature = "stm32wl")] +use embassy_stm32::{pac, PeripheralRef}; +#[cfg(feature = "stm32wl")] +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +#[cfg(feature = "stm32wl")] +use embassy_sync::signal::Signal; +use embedded_hal::digital::v2::OutputPin; +use embedded_hal_async::delay::DelayUs; +use embedded_hal_async::digital::Wait; +use lora_phy::mod_params::RadioError::*; +use lora_phy::mod_params::{BoardType, RadioError}; +use lora_phy::mod_traits::InterfaceVariant; + +#[cfg(feature = "stm32wl")] +static IRQ_SIGNAL: Signal = Signal::new(); + +#[cfg(feature = "stm32wl")] +/// Base for the InterfaceVariant implementation for an stm32wl/sx1262 combination +pub struct Stm32wlInterfaceVariant<'a, CTRL> { + board_type: BoardType, + irq: PeripheralRef<'a, SUBGHZ_RADIO>, + rf_switch_rx: Option, + rf_switch_tx: Option, +} + +#[cfg(feature = "stm32wl")] +impl<'a, CTRL> Stm32wlInterfaceVariant<'a, CTRL> +where + CTRL: OutputPin, +{ + /// Create an InterfaceVariant instance for an stm32wl/sx1262 combination + pub fn new( + irq: PeripheralRef<'a, SUBGHZ_RADIO>, + rf_switch_rx: Option, + rf_switch_tx: Option, + ) -> Result { + irq.disable(); + irq.set_handler(Self::on_interrupt); + Ok(Self { + board_type: BoardType::Stm32wlSx1262, // updated when associated with a specific LoRa board + irq, + rf_switch_rx, + rf_switch_tx, + }) + } + + fn on_interrupt(_: *mut ()) { + unsafe { SUBGHZ_RADIO::steal() }.disable(); + IRQ_SIGNAL.signal(()); + } +} + +#[cfg(feature = "stm32wl")] +impl InterfaceVariant for Stm32wlInterfaceVariant<'_, CTRL> +where + CTRL: OutputPin, +{ + fn set_board_type(&mut self, board_type: BoardType) { + self.board_type = board_type; + } + async fn set_nss_low(&mut self) -> Result<(), RadioError> { + let pwr = pac::PWR; + unsafe { + pwr.subghzspicr().modify(|w| w.set_nss(pac::pwr::vals::Nss::LOW)); + } + Ok(()) + } + async fn set_nss_high(&mut self) -> Result<(), RadioError> { + let pwr = pac::PWR; + unsafe { + pwr.subghzspicr().modify(|w| w.set_nss(pac::pwr::vals::Nss::HIGH)); + } + Ok(()) + } + async fn reset(&mut self, _delay: &mut impl DelayUs) -> Result<(), RadioError> { + let rcc = pac::RCC; + unsafe { + rcc.csr().modify(|w| w.set_rfrst(true)); + rcc.csr().modify(|w| w.set_rfrst(false)); + } + Ok(()) + } + async fn wait_on_busy(&mut self) -> Result<(), RadioError> { + let pwr = pac::PWR; + while unsafe { pwr.sr2().read().rfbusys() == pac::pwr::vals::Rfbusys::BUSY } {} + Ok(()) + } + + async fn await_irq(&mut self) -> Result<(), RadioError> { + self.irq.enable(); + IRQ_SIGNAL.wait().await; + Ok(()) + } + + async fn enable_rf_switch_rx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx)?, + None => (), + }; + match &mut self.rf_switch_rx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchRx), + None => Ok(()), + } + } + async fn enable_rf_switch_tx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } + async fn disable_rf_switch(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } +} + +/// Base for the InterfaceVariant implementation for an stm32l0/sx1276 combination +pub struct Stm32l0InterfaceVariant { + board_type: BoardType, + nss: CTRL, + reset: CTRL, + irq: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, +} + +impl Stm32l0InterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + /// Create an InterfaceVariant instance for an stm32l0/sx1276 combination + pub fn new( + nss: CTRL, + reset: CTRL, + irq: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, + ) -> Result { + Ok(Self { + board_type: BoardType::Stm32l0Sx1276, // updated when associated with a specific LoRa board + nss, + reset, + irq, + rf_switch_rx, + rf_switch_tx, + }) + } +} + +impl InterfaceVariant for Stm32l0InterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + fn set_board_type(&mut self, board_type: BoardType) { + self.board_type = board_type; + } + async fn set_nss_low(&mut self) -> Result<(), RadioError> { + self.nss.set_low().map_err(|_| NSS) + } + async fn set_nss_high(&mut self) -> Result<(), RadioError> { + self.nss.set_high().map_err(|_| NSS) + } + async fn reset(&mut self, delay: &mut impl DelayUs) -> Result<(), RadioError> { + delay.delay_ms(10).await; + self.reset.set_low().map_err(|_| Reset)?; + delay.delay_ms(10).await; + self.reset.set_high().map_err(|_| Reset)?; + delay.delay_ms(10).await; + Ok(()) + } + async fn wait_on_busy(&mut self) -> Result<(), RadioError> { + Ok(()) + } + async fn await_irq(&mut self) -> Result<(), RadioError> { + self.irq.wait_for_high().await.map_err(|_| Irq) + } + + async fn enable_rf_switch_rx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx)?, + None => (), + }; + match &mut self.rf_switch_rx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchRx), + None => Ok(()), + } + } + async fn enable_rf_switch_tx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } + async fn disable_rf_switch(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } +} + +/// Base for the InterfaceVariant implementation for a generic Sx126x LoRa board +pub struct GenericSx126xInterfaceVariant { + board_type: BoardType, + nss: CTRL, + reset: CTRL, + dio1: WAIT, + busy: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, +} + +impl GenericSx126xInterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + /// Create an InterfaceVariant instance for an nrf52840/sx1262 combination + pub fn new( + nss: CTRL, + reset: CTRL, + dio1: WAIT, + busy: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, + ) -> Result { + Ok(Self { + board_type: BoardType::Rak4631Sx1262, // updated when associated with a specific LoRa board + nss, + reset, + dio1, + busy, + rf_switch_rx, + rf_switch_tx, + }) + } +} + +impl InterfaceVariant for GenericSx126xInterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + fn set_board_type(&mut self, board_type: BoardType) { + self.board_type = board_type; + } + async fn set_nss_low(&mut self) -> Result<(), RadioError> { + self.nss.set_low().map_err(|_| NSS) + } + async fn set_nss_high(&mut self) -> Result<(), RadioError> { + self.nss.set_high().map_err(|_| NSS) + } + async fn reset(&mut self, delay: &mut impl DelayUs) -> Result<(), RadioError> { + delay.delay_ms(10).await; + self.reset.set_low().map_err(|_| Reset)?; + delay.delay_ms(20).await; + self.reset.set_high().map_err(|_| Reset)?; + delay.delay_ms(10).await; + Ok(()) + } + async fn wait_on_busy(&mut self) -> Result<(), RadioError> { + self.busy.wait_for_low().await.map_err(|_| Busy) + } + async fn await_irq(&mut self) -> Result<(), RadioError> { + if self.board_type != BoardType::RpPicoWaveshareSx1262 { + self.dio1.wait_for_high().await.map_err(|_| DIO1)?; + } else { + self.dio1.wait_for_rising_edge().await.map_err(|_| DIO1)?; + } + Ok(()) + } + + async fn enable_rf_switch_rx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx)?, + None => (), + }; + match &mut self.rf_switch_rx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchRx), + None => Ok(()), + } + } + async fn enable_rf_switch_tx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } + async fn disable_rf_switch(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } +} diff --git a/embassy-lora/src/lib.rs b/embassy-lora/src/lib.rs index 5c919cbb..d8bc3cd9 100644 --- a/embassy-lora/src/lib.rs +++ b/embassy-lora/src/lib.rs @@ -5,6 +5,9 @@ //! crate's async LoRaWAN MAC implementation. pub(crate) mod fmt; +#[cfg(feature = "external-lora-phy")] +/// interface variants required by the external lora crate +pub mod iv; #[cfg(feature = "stm32wl")] pub mod stm32wl; diff --git a/embassy-stm32/src/spi/mod.rs b/embassy-stm32/src/spi/mod.rs index 492d0649..aefa4243 100644 --- a/embassy-stm32/src/spi/mod.rs +++ b/embassy-stm32/src/spi/mod.rs @@ -197,7 +197,7 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { /// Useful for on chip peripherals like SUBGHZ which are hardwired. /// The bus can optionally be exposed externally with `Spi::new()` still. #[allow(dead_code)] - pub(crate) fn new_internal( + pub fn new_subghz( peri: impl Peripheral

+ 'd, txdma: impl Peripheral

+ 'd, rxdma: impl Peripheral

+ 'd, diff --git a/embassy-stm32/src/subghz/mod.rs b/embassy-stm32/src/subghz/mod.rs index 33398fa1..cd566ba2 100644 --- a/embassy-stm32/src/subghz/mod.rs +++ b/embassy-stm32/src/subghz/mod.rs @@ -224,7 +224,7 @@ impl<'d, Tx, Rx> SubGhz<'d, Tx, Rx> { let mut config = SpiConfig::default(); config.mode = MODE_0; config.bit_order = BitOrder::MsbFirst; - let spi = Spi::new_internal(peri, txdma, rxdma, clk, config); + let spi = Spi::new_subghz(peri, txdma, rxdma, clk, config); unsafe { wakeup() }; diff --git a/examples/nrf52840/Cargo.toml b/examples/nrf52840/Cargo.toml index 10c269a7..7a1fe281 100644 --- a/examples/nrf52840/Cargo.toml +++ b/examples/nrf52840/Cargo.toml @@ -13,15 +13,15 @@ nightly = ["embassy-executor/nightly", "embassy-nrf/nightly", "embassy-net/night embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime"] } embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet"], optional = true } embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt", "msos-descriptor",], optional = true } embedded-io = "0.4.0" -embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx126x", "time", "defmt"], optional = true } - -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"], optional = true } -lorawan = { version = "0.7.2", default-features = false, features = ["default-crypto"], optional = true } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx126x", "time", "defmt", "external-lora-phy"], optional = true } +lora-phy = { version = "1", path = "../../../lora-phy" } +lorawan-device = { version = "0.9.0", path = "../../../rust-lorawan/device", default-features = false, features = ["async", "external-lora-phy"], optional = true } +lorawan = { version = "0.7.2", path = "../../../rust-lorawan/encoding", default-features = false, features = ["default-crypto"], optional = true } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/nrf52840/src/bin/lora_cad.rs b/examples/nrf52840/src/bin/lora_cad.rs new file mode 100644 index 00000000..8899c1b2 --- /dev/null +++ b/examples/nrf52840/src/bin/lora_cad.rs @@ -0,0 +1,92 @@ +//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. +//! Other nrf/sx126x combinations may work with appropriate pin modifications. +//! It demonstates LORA CAD functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; +use embassy_nrf::{bind_interrupts, peripherals, spim}; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut spi_config = spim::Config::default(); + spi_config.frequency = spim::Frequency::M16; + + let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); + + let nss = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); + let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); + let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); + let busy = Input::new(p.P1_14.degrade(), Pull::Down); + let rf_switch_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); + let rf_switch_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); + + let iv = + GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, Some(rf_switch_rx), Some(rf_switch_tx)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Rak4631Sx1262, spim, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.P1_03, Level::Low, OutputDrive::Standard); + let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mdltn_params = { + match lora.create_modulation_params(SpreadingFactor::_10, Bandwidth::_250KHz, CodingRate::_4_8, 903900000) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_cad(&mdltn_params, true).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.cad().await { + Ok(cad_activity_detected) => { + if cad_activity_detected { + info!("cad successful with activity detected") + } else { + info!("cad successful without activity detected") + } + debug_indicator.set_high(); + Timer::after(Duration::from_secs(15)).await; + debug_indicator.set_low(); + } + Err(err) => info!("cad unsuccessful = {}", err), + } +} diff --git a/examples/nrf52840/src/bin/lora_p2p_receive_duty_cycle.rs b/examples/nrf52840/src/bin/lora_p2p_receive_duty_cycle.rs new file mode 100644 index 00000000..d8470174 --- /dev/null +++ b/examples/nrf52840/src/bin/lora_p2p_receive_duty_cycle.rs @@ -0,0 +1,124 @@ +//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. +//! Other nrf/sx126x combinations may work with appropriate pin modifications. +//! It demonstates LoRa Rx duty cycle functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; +use embassy_nrf::{bind_interrupts, peripherals, spim}; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut spi_config = spim::Config::default(); + spi_config.frequency = spim::Frequency::M16; + + let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); + + let nss = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); + let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); + let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); + let busy = Input::new(p.P1_14.degrade(), Pull::Down); + let rf_switch_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); + let rf_switch_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); + + let iv = + GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, Some(rf_switch_rx), Some(rf_switch_tx)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Rak4631Sx1262, spim, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.P1_03, Level::Low, OutputDrive::Standard); + let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mut receiving_buffer = [00u8; 100]; + + let mdltn_params = { + match lora.create_modulation_params(SpreadingFactor::_10, Bandwidth::_250KHz, CodingRate::_4_8, 903900000) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let rx_pkt_params = { + match lora.create_rx_packet_params(4, false, receiving_buffer.len() as u8, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + // See "RM0453 Reference manual STM32WL5x advanced ArmĀ®-based 32-bit MCUs with sub-GHz radio solution" for the best explanation of Rx duty cycle processing. + match lora + .prepare_for_rx( + &mdltn_params, + &rx_pkt_params, + Some(&DutyCycleParams { + rx_time: 300_000, // 300_000 units * 15.625 us/unit = 4.69 s + sleep_time: 200_000, // 200_000 units * 15.625 us/unit = 3.13 s + }), + false, + false, + 0, + 0, + ) + .await + { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + receiving_buffer = [00u8; 100]; + match lora.rx(&rx_pkt_params, &mut receiving_buffer).await { + Ok((received_len, _rx_pkt_status)) => { + if (received_len == 3) + && (receiving_buffer[0] == 0x01u8) + && (receiving_buffer[1] == 0x02u8) + && (receiving_buffer[2] == 0x03u8) + { + info!("rx successful"); + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } else { + info!("rx unknown packet") + } + } + Err(err) => info!("rx unsuccessful = {}", err), + } +} diff --git a/examples/nrf52840/src/bin/lora_p2p_report.rs b/examples/nrf52840/src/bin/lora_p2p_report.rs deleted file mode 100644 index e24f0db0..00000000 --- a/examples/nrf52840/src/bin/lora_p2p_report.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. -//! Other nrf/sx126x combinations may work with appropriate pin modifications. -//! It demonstates LORA P2P functionality in conjunction with example lora_p2p_sense.rs. -#![no_std] -#![no_main] -#![macro_use] -#![allow(dead_code)] -#![feature(type_alias_impl_trait)] - -use defmt::*; -use embassy_executor::Spawner; -use embassy_lora::sx126x::*; -use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; -use embassy_nrf::{bind_interrupts, peripherals, spim}; -use embassy_time::{Duration, Timer}; -use lorawan_device::async_device::radio::{Bandwidth, CodingRate, PhyRxTx, RfConfig, SpreadingFactor}; -use {defmt_rtt as _, panic_probe as _}; - -bind_interrupts!(struct Irqs { - SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; -}); - -#[embassy_executor::main] -async fn main(_spawner: Spawner) { - let p = embassy_nrf::init(Default::default()); - let mut spi_config = spim::Config::default(); - spi_config.frequency = spim::Frequency::M16; - - let mut radio = { - let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); - - let cs = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); - let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); - let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); - let busy = Input::new(p.P1_14.degrade(), Pull::Down); - let antenna_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); - let antenna_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); - - match Sx126xRadio::new(spim, cs, reset, antenna_rx, antenna_tx, dio1, busy, false).await { - Ok(r) => r, - Err(err) => { - info!("Sx126xRadio error = {}", err); - return; - } - } - }; - - let mut debug_indicator = Output::new(p.P1_03, Level::Low, OutputDrive::Standard); - let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); - - start_indicator.set_high(); - Timer::after(Duration::from_secs(5)).await; - start_indicator.set_low(); - - loop { - let rf_config = RfConfig { - frequency: 903900000, // channel in Hz - bandwidth: Bandwidth::_250KHz, - spreading_factor: SpreadingFactor::_10, - coding_rate: CodingRate::_4_8, - }; - - let mut buffer = [00u8; 100]; - - // P2P receive - match radio.rx(rf_config, &mut buffer).await { - Ok((buffer_len, rx_quality)) => info!( - "RX received = {:?} with length = {} rssi = {} snr = {}", - &buffer[0..buffer_len], - buffer_len, - rx_quality.rssi(), - rx_quality.snr() - ), - Err(err) => info!("RX error = {}", err), - } - - debug_indicator.set_high(); - Timer::after(Duration::from_secs(2)).await; - debug_indicator.set_low(); - } -} diff --git a/examples/rp/Cargo.toml b/examples/rp/Cargo.toml index 8067f7ba..1787e4f8 100644 --- a/examples/rp/Cargo.toml +++ b/examples/rp/Cargo.toml @@ -9,12 +9,16 @@ license = "MIT OR Apache-2.0" embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal", features = ["defmt"] } embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime"] } embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-traits", "nightly", "unstable-pac", "time-driver", "pio", "critical-section-impl"] } embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "dhcpv4", "medium-ethernet"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } embassy-usb-logger = { version = "0.1.0", path = "../../embassy-usb-logger" } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["time", "defmt", "external-lora-phy"] } +lora-phy = { version = "1", path = "../../../lora-phy" } +lorawan-device = { version = "0.9.0", path = "../../../rust-lorawan/device", default-features = false, features = ["async", "external-lora-phy"] } +lorawan = { version = "0.7.2", path = "../../../rust-lorawan/encoding", default-features = false, features = ["default-crypto"] } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/stm32l0/Cargo.toml b/examples/stm32l0/Cargo.toml index d08e2b61..7e9827a8 100644 --- a/examples/stm32l0/Cargo.toml +++ b/examples/stm32l0/Cargo.toml @@ -11,12 +11,12 @@ nightly = ["embassy-stm32/nightly", "embassy-lora", "lorawan-device", "lorawan", [dependencies] embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32l072cz", "time-driver-any", "exti", "unstable-traits", "memory-x"] } -embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx127x", "time", "defmt"], optional = true} - -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"], optional = true } -lorawan = { version = "0.7.2", default-features = false, features = ["default-crypto"], optional = true } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx127x", "time", "defmt", "external-lora-phy"], optional = true } +lora-phy = { version = "1", path = "../../../lora-phy" } +lorawan-device = { version = "0.9.0", path = "../../../rust-lorawan/device", default-features = false, features = ["async", "external-lora-phy"], optional = true } +lorawan = { version = "0.7.2", path = "../../../rust-lorawan/encoding", default-features = false, features = ["default-crypto"], optional = true } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/stm32l0/src/bin/lora_p2p_receive.rs b/examples/stm32l0/src/bin/lora_p2p_receive.rs new file mode 100644 index 00000000..a5c5f75e --- /dev/null +++ b/examples/stm32l0/src/bin/lora_p2p_receive.rs @@ -0,0 +1,120 @@ +//! This example runs on the STM32 LoRa Discovery board, which has a builtin Semtech Sx1276 radio. +//! It demonstrates LORA P2P receive functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32l0InterfaceVariant; +use embassy_stm32::exti::{Channel, ExtiInput}; +use embassy_stm32::gpio::{Input, Level, Output, Pin, Pull, Speed}; +use embassy_stm32::spi; +use embassy_stm32::time::khz; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1276_7_8_9::SX1276_7_8_9; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; + config.rcc.enable_hsi48 = true; + let p = embassy_stm32::init(config); + + // SPI for sx1276 + let spi = spi::Spi::new( + p.SPI1, + p.PB3, + p.PA7, + p.PA6, + p.DMA1_CH3, + p.DMA1_CH2, + khz(200), + spi::Config::default(), + ); + + let nss = Output::new(p.PA15.degrade(), Level::High, Speed::Low); + let reset = Output::new(p.PC0.degrade(), Level::High, Speed::Low); + + let irq_pin = Input::new(p.PB4.degrade(), Pull::Up); + let irq = ExtiInput::new(irq_pin, p.EXTI4.degrade()); + + let iv = Stm32l0InterfaceVariant::new(nss, reset, irq, None, None).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1276_7_8_9::new(BoardType::Stm32l0Sx1276, spi, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.PB5, Level::Low, Speed::Low); + let mut start_indicator = Output::new(p.PB6, Level::Low, Speed::Low); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mut receiving_buffer = [00u8; 100]; + + let mdltn_params = { + match lora.create_modulation_params(SpreadingFactor::_10, Bandwidth::_250KHz, CodingRate::_4_8, 903900000) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let rx_pkt_params = { + match lora.create_rx_packet_params(4, false, receiving_buffer.len() as u8, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora + .prepare_for_rx(&mdltn_params, &rx_pkt_params, None, true, false, 0, 0x00ffffffu32) + .await + { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + loop { + receiving_buffer = [00u8; 100]; + match lora.rx(&rx_pkt_params, &mut receiving_buffer).await { + Ok((received_len, _rx_pkt_status)) => { + if (received_len == 3) + && (receiving_buffer[0] == 0x01u8) + && (receiving_buffer[1] == 0x02u8) + && (receiving_buffer[2] == 0x03u8) + { + info!("rx successful"); + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } else { + info!("rx unknown packet"); + } + } + Err(err) => info!("rx unsuccessful = {}", err), + } + } +} diff --git a/examples/stm32wl/Cargo.toml b/examples/stm32wl/Cargo.toml index 07f136b4..80c7bccd 100644 --- a/examples/stm32wl/Cargo.toml +++ b/examples/stm32wl/Cargo.toml @@ -7,12 +7,13 @@ license = "MIT OR Apache-2.0" [dependencies] embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32wl55jc-cm4", "time-driver-any", "memory-x", "unstable-pac", "exti"] } -embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["stm32wl", "time", "defmt"] } - -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"] } -lorawan = { version = "0.7.2", default-features = false, features = ["default-crypto"] } +embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "unstable-traits", "defmt", "stm32wl55jc-cm4", "time-driver-any", "memory-x", "unstable-pac", "exti"] } +embassy-embedded-hal = {version = "0.1.0", path = "../../embassy-embedded-hal" } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["stm32wl", "time", "defmt", "external-lora-phy"] } +lora-phy = { version = "1", path = "../../../lora-phy" } +lorawan-device = { version = "0.9.0", path = "../../../rust-lorawan/device", default-features = false, features = ["async", "external-lora-phy"] } +lorawan = { version = "0.7.2", path = "../../../rust-lorawan/encoding", default-features = false, features = ["default-crypto"] } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/stm32wl/src/bin/lora_lorawan.rs b/examples/stm32wl/src/bin/lora_lorawan.rs new file mode 100644 index 00000000..f7cf0359 --- /dev/null +++ b/examples/stm32wl/src/bin/lora_lorawan.rs @@ -0,0 +1,88 @@ +//! This example runs on a STM32WL board, which has a builtin Semtech Sx1262 radio. +//! It demonstrates LoRaWAN functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait, async_fn_in_trait)] +#![allow(incomplete_features)] + +use defmt::info; +use embassy_embedded_hal::adapter::BlockingAsync; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32wlInterfaceVariant; +use embassy_lora::LoraTimer; +use embassy_stm32::dma::NoDma; +use embassy_stm32::gpio::{Level, Output, Pin, Speed}; +use embassy_stm32::peripherals::SUBGHZSPI; +use embassy_stm32::rcc::low_level::RccPeripheral; +use embassy_stm32::rng::Rng; +use embassy_stm32::spi::{BitOrder, Config as SpiConfig, Spi, MODE_0}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{interrupt, into_ref, pac, Peripheral}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use lorawan::default_crypto::DefaultFactory as Crypto; +use lorawan_device::async_device::lora_radio::LoRaRadio; +use lorawan_device::async_device::{region, Device, JoinMode}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; + config.rcc.enable_lsi = true; + let p = embassy_stm32::init(config); + + unsafe { pac::RCC.ccipr().modify(|w| w.set_rngsel(0b01)) } + + let clk = Hertz(core::cmp::min(SUBGHZSPI::frequency().0 / 2, 16_000_000)); + let mut spi_config = SpiConfig::default(); + spi_config.mode = MODE_0; + spi_config.bit_order = BitOrder::MsbFirst; + let spi = Spi::new_subghz(p.SUBGHZSPI, NoDma, NoDma, clk, spi_config); + + let spi = BlockingAsync::new(spi); + + let irq = interrupt::take!(SUBGHZ_RADIO); + into_ref!(irq); + // Set CTRL1 and CTRL3 for high-power transmission, while CTRL2 acts as an RF switch between tx and rx + let _ctrl1 = Output::new(p.PC4.degrade(), Level::Low, Speed::High); + let ctrl2 = Output::new(p.PC5.degrade(), Level::High, Speed::High); + let _ctrl3 = Output::new(p.PC3.degrade(), Level::High, Speed::High); + let iv = Stm32wlInterfaceVariant::new(irq, None, Some(ctrl2)).unwrap(); + + let mut delay = Delay; + + let lora = { + match LoRa::new(SX1261_2::new(BoardType::Stm32wlSx1262, spi, iv), true, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + let radio = LoRaRadio::new(lora); + let region: region::Configuration = region::Configuration::new(region::Region::EU868); + let mut device: Device<_, Crypto, _, _> = Device::new(region, radio, LoraTimer::new(), Rng::new(p.RNG)); + + defmt::info!("Joining LoRaWAN network"); + + // TODO: Adjust the EUI and Keys according to your network credentials + match device + .join(&JoinMode::OTAA { + deveui: [0, 0, 0, 0, 0, 0, 0, 0], + appeui: [0, 0, 0, 0, 0, 0, 0, 0], + appkey: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + }) + .await + { + Ok(()) => defmt::info!("LoRaWAN network joined"), + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; +} diff --git a/examples/stm32wl/src/bin/lora_p2p_send.rs b/examples/stm32wl/src/bin/lora_p2p_send.rs new file mode 100644 index 00000000..11c35a8f --- /dev/null +++ b/examples/stm32wl/src/bin/lora_p2p_send.rs @@ -0,0 +1,103 @@ +//! This example runs on a STM32WL board, which has a builtin Semtech Sx1262 radio. +//! It demonstrates LORA P2P send functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait, async_fn_in_trait)] +#![allow(incomplete_features)] + +use defmt::info; +use embassy_embedded_hal::adapter::BlockingAsync; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32wlInterfaceVariant; +use embassy_stm32::dma::NoDma; +use embassy_stm32::gpio::{Level, Output, Pin, Speed}; +use embassy_stm32::peripherals::SUBGHZSPI; +use embassy_stm32::rcc::low_level::RccPeripheral; +use embassy_stm32::spi::{BitOrder, Config as SpiConfig, Spi, MODE_0}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{interrupt, into_ref, Peripheral}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSE32; + let p = embassy_stm32::init(config); + + let clk = Hertz(core::cmp::min(SUBGHZSPI::frequency().0 / 2, 16_000_000)); + let mut spi_config = SpiConfig::default(); + spi_config.mode = MODE_0; + spi_config.bit_order = BitOrder::MsbFirst; + let spi = Spi::new_subghz(p.SUBGHZSPI, NoDma, NoDma, clk, spi_config); + + let spi = BlockingAsync::new(spi); + + let irq = interrupt::take!(SUBGHZ_RADIO); + into_ref!(irq); + // Set CTRL1 and CTRL3 for high-power transmission, while CTRL2 acts as an RF switch between tx and rx + let _ctrl1 = Output::new(p.PC4.degrade(), Level::Low, Speed::High); + let ctrl2 = Output::new(p.PC5.degrade(), Level::High, Speed::High); + let _ctrl3 = Output::new(p.PC3.degrade(), Level::High, Speed::High); + let iv = Stm32wlInterfaceVariant::new(irq, None, Some(ctrl2)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Stm32wlSx1262, spi, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mdltn_params = { + match lora.create_modulation_params(SpreadingFactor::_10, Bandwidth::_250KHz, CodingRate::_4_8, 903900000) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut tx_pkt_params = { + match lora.create_tx_packet_params(4, false, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_tx(&mdltn_params, 20, false).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + let buffer = [0x01u8, 0x02u8, 0x03u8]; + match lora.tx(&mdltn_params, &mut tx_pkt_params, &buffer, 0xffffff).await { + Ok(()) => { + info!("TX DONE"); + } + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.sleep(&mut delay).await { + Ok(()) => info!("Sleep successful"), + Err(err) => info!("Sleep unsuccessful = {}", err), + } +}