// Copyright Open Logistics Foundation // // Licensed under the Open Logistics Foundation License 1.3. // For details on the licensing terms, see the LICENSE file. // SPDX-License-Identifier: OLFL-1.3 //! Multiple sockets example with RAII demonstration //! //! This example requests all possible 12 sockets from the modem driver and asserts that requesting //! the 13th socket fails. It opens two sockets simultaneously afterwards and drops/closes one of //! them explicitly, the other one implicitly by returning from the function, demonstrating the //! RAII resource management. //! //! This example will print some output over serial uart and RTT. #![no_std] #![no_main] pub use hal::stm32 as pac; pub use stm32l4xx_hal as hal; use panic_probe as _; mod boards; #[cortex_m_rt::entry] fn main() -> ! { let mut driver = boards::board_setup(); let bg77 = quectel_bg77::Bg77ClientStack::new(&mut driver); if let Err(e) = multiple_sockets_example(bg77) { log::error!("Example failed: {:?}", e); } else { log::info!("Example successful"); } #[allow(clippy::empty_loop)] loop {} } fn multiple_sockets_example(mut bg77: BG77) -> Result<(), MseErr> where E: core::fmt::Debug, BG77: embedded_nal::TcpClientStack, { let mut sockets: [_; 12] = Default::default(); // -> [None; 12]; for socket in &mut sockets { // This only fails if all sockets are currently in use *socket = Some(bg77.socket()?); } if bg77.socket().is_ok() { return Err(MseErr::Other( "Requesting the 13th socket should fail because the BG77 only supports 12 sockets", )); } let socket_addr0: embedded_nal::SocketAddr = "40.114.177.156:80".parse().unwrap(); let socket_addr1: embedded_nal::SocketAddr = "142.250.185.110:80".parse().unwrap(); log::info!("Connect first socket to {}", socket_addr0); nb::block!(bg77.connect(sockets[0].as_mut().unwrap(), socket_addr0))?; log::info!("Connect second socket to {}", socket_addr1); nb::block!(bg77.connect(sockets[1].as_mut().unwrap(), socket_addr1))?; log::info!("Drop and close first socket"); drop(sockets[0].take()); log::info!("Assert that a new socket is available again"); bg77.socket()?; log::info!("Return which drops and closes second socket"); Ok(()) } #[derive(Debug)] enum MseErr { Bg77(E), Other(&'static str), } impl From for MseErr { fn from(e: E) -> Self { MseErr::Bg77(e) } }