use crate::command::Command; use std::thread; use std::io::{Error as IoError, ErrorKind, BufRead}; use std::error::Error; use std::time::{Duration, Instant}; use embedded_hal::serial::{Read, Write}; use embedded_hal::digital::v2::OutputPin; use esp_idf_hal::serial::{self, Rx, Tx, SerialError}; pub type Result = std::result::Result; pub struct Modem { is_connected: bool, rx: MyRx, tx: Tx, } #[derive(Debug)] pub enum ModemError { CommandError(String), SetupError(String), TimeoutError, } impl Error for ModemError {} impl std::fmt::Display for ModemError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{:?}", self) } } struct MyRx(Rx); impl MyRx { fn read(&mut self) -> nb::Result { self.0.read() } fn read_blocking(&mut self) -> std::result::Result { nb::block!(self.read()) } } impl std::io::Read for MyRx { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let mut read_bytes: usize = 0; loop { let b = self.read_blocking() .map_err(|err| IoError::new(ErrorKind::Other, format!("Serial error {:?}", err)))?; buf[read_bytes] = b; read_bytes += 1; if b == '\0' as u8 || b == '\n' as u8 { break; } }; Ok(read_bytes) } } impl Modem { pub fn new(tx: Tx, rx: Rx) -> Self { Self { is_connected: false, rx: MyRx(rx), tx, } } /// Reads the serial RX until it has bytes, or until a timeout is reached. The timeout is /// provided on input via the `timeout` argument. The first argument `expected` is the expected /// end of the buffer. If it's `None`, the whole response is returned as is. If it's /// `Some(expected_end)`, then the end of the response is matched against `expected_end`. If /// they match, great! The response is returned from the function, but if not, then a /// [ModemError::CommandError](crate::modem::ModemError::CommandError) is returned. /// /// It's ok to use this function like this for now because the write/read cycle is blocking, /// hence the case where multiple writes happen asynchronously isn't handled. See /// [send_command](crate::modem::Modem::send_command) for more info on the blocking part. fn read_response(&mut self, contains: Option, timeout: Duration) -> Result { let mut response = String::new(); let now = Instant::now(); let match_text: String = contains.unwrap_or("".to_string()); let mut reader = std::io::BufReader::new(&mut self.rx); loop { let mut line = String::new(); reader.read_line(&mut line) .map_err(|err| ModemError::CommandError(format!("read line failed: {}", err)))?; println!("Read {} from serial ...", line.trim()); // check if empty first because it's much simpler and more frequent if line == "" { if now + timeout > Instant::now() { return Err(ModemError::TimeoutError); } thread::sleep(Duration::from_millis(1000)); continue; } else { response.push_str(&line); if line.contains(&match_text) { println!("Found match {} for line {} ... exiting response reader now!", match_text, line); println!("-----------------------------------------------------------"); break; } } } Ok(response.to_string()) } fn send_command(&mut self, cmd: Command) -> Result { for b in cmd.text.as_bytes().iter() { nb::block!(self.tx.write(*b)).map_err(|_| ModemError::CommandError("error writing to serial".to_string()))?; } nb::block!(self.tx.write('\r' as u8)).map_err(|_| ModemError::CommandError("error writing to serial".to_string()))?; self.read_response(cmd.contains.clone(), cmd.timeout.clone()) } pub fn get_ip_addr(&mut self) -> Result { println!("getting ip addres ..."); let res = self.send_command(Command::getbear())?; println!("{}", res); Ok(res) } pub fn connect_to_gprs_ap(&mut self, apn: &str, username: &str, password: &str)-> Result<()> { println!("init gprs ..."); let _ = self.send_command(Command::initgprs())?; println!("connecting to {} with {}:{}", apn, username, password); let _ = self.send_command(Command::setapn(apn))?; let _ = self.send_command(Command::setuser(username))?; let _ = self.send_command(Command::setpwd(password))?; println!("open gprs ..."); let _ = self.send_command(Command::initgprs())?; self.is_connected = true; Ok(()) } pub fn info(&mut self)-> Result { println!("getting modem info with API command"); self.send_command(Command::modeminfo()) } pub fn probe(&mut self)-> Result { println!("probing modem with AP command"); self.send_command(Command::probe()) } pub fn is_gprs_attached(&mut self)-> Result { println!("testing gprs connection ..."); let res = self.send_command(Command::is_gprs_attached())?; Ok(res.contains("+CGATT: 1")) } } /// Initialize the modem (sim800l in this case). The initialization process sets all pins in the /// required state so that the modem is turned on, then resets it a couple of times (beats me) and /// sleeps for 3 seconds, which is enough for the modem to come online. /// /// Below is an example for sim800l pins on a LilyGo TTGO T-Call. /// /// # Examples /// /// ``` /// let modem_pwrkey = dp.pins.gpio4.into_output().unwrap(); /// let modem_rst = dp.pins.gpio5.into_output().unwrap(); /// let modem_power = dp.pins.gpio23.into_output().unwrap(); /// /// modem::init(modem_pwrkey, modem_rst, modem_power); /// ``` pub fn init(mut pwrkey: impl OutputPin, mut rst: impl OutputPin, mut power: impl OutputPin) -> Result<()> { println!("Turning SIM800L on ..."); power.set_high().map_err(|_| ModemError::SetupError("Error setting POWER to high.".to_string()))?; rst.set_high().map_err(|_| ModemError::SetupError("Error setting RST to high.".to_string()))?; // Pull down PWRKEY for more than 1 second according to manual requirements pwrkey.set_high().map_err(|_| ModemError::SetupError("Error setting PWRKEY to high.".to_string()))?; thread::sleep(Duration::from_millis(100)); pwrkey.set_low().map_err(|_| ModemError::SetupError("Error setting PWRKEY to low.".to_string()))?; thread::sleep(Duration::from_millis(1000)); pwrkey.set_high().map_err(|_| ModemError::SetupError("Error setting PWRKEY to high.".to_string()))?; println!("Waiting 3s for sim module to come online ..."); thread::sleep(Duration::from_millis(3000)); Ok(()) }