use crate::command::Command; use std::thread; 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}; const MAX_TCP_MANUAL_REPLY_SIZE: usize = 300; pub type Result = std::result::Result; pub struct Modem { rx: RxIter, tx: Tx, } #[derive(Debug)] pub enum ModemError { CommandError(String), SetupError(String), SendDataError, ReadError, 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) } } pub struct RxIter { inner: Rx, timeout: Duration, } impl RxIter { fn reset(&mut self, timeout: Duration) -> &mut Self { self.timeout = timeout; self } fn clear(&mut self) -> () { println!("clearing serial rx"); self.reset(Duration::from_millis(500)).for_each(drop); } /// Reads a whole line (that ends with \\n) within the given `timeout` passed on input. fn read_line(&mut self, timeout: Duration) -> Result { let mut line: String = self.reset(timeout) .map(|b| char::from(b)) .take_while(|c| *c != '\n') .collect(); // \r must come right before \n on read; take_while excludes the matched element. if line.ends_with('\r') { line.push('\n'); Ok(line) } else if self.timeout.as_millis() == 0 { Err(ModemError::TimeoutError) } else { Err(ModemError::ReadError) } } } impl Iterator for RxIter { type Item = u8; /// `nb` returns Ok(byte), or one of Err(WouldBlock) and Err(Other) which isn't of anyone's /// interest, so the retry mechanism is triggered on _any_ error every 200ms until a byte is /// received, or the timeout is reached. fn next(&mut self) -> Option { let start = Instant::now(); loop { match self.inner.read() { Ok(b) => { self.timeout = self.timeout.saturating_sub(start.elapsed()); break Some(b) }, Err(_) => { if start.elapsed() > self.timeout { self.timeout = Duration::ZERO; break None } thread::sleep(Duration::from_millis(200)); } } } } } impl Modem { pub fn new(tx: Tx, rx: Rx) -> Self { Self { rx: RxIter { inner: rx, timeout: Duration::from_millis(0) }, tx, } } /// 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 self, 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 for sim module to come online ..."); loop { match self.send_command(Command::probe()) { Ok(_) => break, _ => continue, } } Ok(()) } /// Reads the serial RX until a \\n char is encoutered, or a timeout is reached. The timeout is /// provided on input via the `timeout` argument. The first argument `contains` is checked /// against a line in the response, if it's there the reading stops. /// /// If `contains` is `None`, the first line only is returned in the response. If it's /// `Some(match_txt)`, then the end of the response is matched against `match_txt`. fn read_response(&mut self, contains: Option, timeout: Duration) -> Result { let mut response = String::new(); let start = Instant::now(); let match_text: String = contains.unwrap_or("\n".to_string()); loop { let timeout = timeout.saturating_sub(start.elapsed()); let line = self.rx.read_line(timeout)?; print!("Read {} bytes from serial: {}", line.len(), line); response.push_str(&line); if line.contains("ERROR") || line.contains(&match_text) { println!("Found match {} for line {} ; exiting response reader now ...", match_text, line); println!("-----------------------------------------------------------"); break Ok(response.to_string()) } } } #[inline(always)] fn send_bytes(&mut self, payload: &[u8], eos: char) -> Result<()> { for b in payload.iter() { nb::block!(self.tx.write(*b)) .map_err(|_| ModemError::CommandError(format!("error writing {} to serial", b)))?; } nb::block!(self.tx.write(eos as u8)) .map_err(|_| ModemError::CommandError(format!("error writing {} to serial", eos)))?; Ok(()) } fn send_command(&mut self, cmd: Command) -> Result { println!("-----------------------------------------------------------"); println!("Sending {} ...", cmd.text); let _ = self.send_bytes(cmd.text.as_bytes(), '\r')?; self.read_response(cmd.contains, cmd.timeout) } fn send_data(&mut self, buf: &[u8]) -> Result { self.rx.clear(); let _ = self.send_bytes("AT+CIPSEND".as_bytes(), '\r')?; let send_request: String = self.rx.reset(Duration::from_millis(3000)) .map(char::from) .take_while(|c| *c != '>').collect(); if send_request == "" { return Err(ModemError::SendDataError); } self.send_bytes(buf, 26 as char)?; // 26_u8 = Ctrl+z - to end sending data let _ = self.read_response(Some("DATA ACCEPT".to_string()), Duration::from_millis(3000)); self.rx.clear(); let res = self.send_command(Command { text: "AT+CIPACK".to_string(), contains: Some("OK".to_string()), timeout: Duration::from_millis(3000), })?; Ok(res) } pub fn get_ip_addr(&mut self) -> Result { self.send_command(Command::getbear()) } pub fn connect_to_gprs_ap(&mut self, apn: &str, username: &str, password: &str)-> Result<()> { println!("init gprs ..."); let _ = self.send_command(Command::gprs_init())?; println!("setting up gprs credentials for apn {}, {}:{})", apn, username, password); let _ = self.send_command(Command::gprs_set_apn(apn))?; let _ = self.send_command(Command::gprs_set_user(username))?; let _ = self.send_command(Command::gprs_set_pwd(password))?; println!("open gprs ..."); let _ = self.send_command(Command::gprs_open())?; Ok(()) } pub fn is_gprs_attached(&mut self)-> Result { let res = self.send_command(Command::is_gprs_attached())?; Ok(res.contains("+CGATT: 1")) } pub fn tcp_is_ssl_enabled(&mut self) -> Result { let res = self.send_command(Command::tcp_ssl_check())?; Ok(res.contains("+CIPSSL: (1)")) } pub fn tcp_ssl_disable(&mut self) -> Result<()> { let _ = self.send_command(Command::tcp_ssl_set(false))?; Ok(()) } pub fn tcp_ssl_enable(&mut self) -> Result<()> { let _ = self.send_command(Command::tcp_ssl_set(true))?; Ok(()) } pub fn tcp_connect(&mut self, addr: &str, port: u16) -> Result<()> { self.send_command(Command::tcp_connect(addr, port))?; Ok(()) } pub fn tcp_set_quick_mode(&mut self, mode: bool) -> Result<()> { self.send_command(Command::tcp_set_quick_mode(mode))?; Ok(()) } pub fn tcp_set_manual_receive(&mut self) -> Result<()> { self.send_command(Command::tcp_set_manual_receive())?; Ok(()) } pub fn tcp_send(&mut self, buf: &[u8]) -> Result<()> { self.send_data(buf)?; Ok(()) } fn tcp_parse_response_size(&mut self, reply_line: &str) -> Result { reply_line.split(',') .into_iter() .last() .unwrap_or("x") .parse::() .map_err(|_| ModemError::CommandError(format!("response size should be a number, got {}", reply_line))) } pub fn tcp_receive_reply_len(&mut self) -> Result { let reply = self.send_command(Command::tcp_receive_reply_len())?; reply.lines() .filter(|line| line.contains("+CIPRXGET: 4")) .next() .ok_or(ModemError::CommandError("reply not found :/".to_string())) .map(|line| self.tcp_parse_response_size(line)) .unwrap_or(Err(ModemError::CommandError(format!("received 0 elements from parsing")))) } pub fn tcp_receive(&mut self, buf: &mut [u8]) -> Result { let mut size = 0; loop { let reply: usize = self.send_command(Command::tcp_receive(MAX_TCP_MANUAL_REPLY_SIZE)) .map(|reply: String| { reply.lines() .map(|line| { if !line.starts_with("\r") && !line.contains("+CIPRXGET: 2,") && !line.contains("OK") { line.chars().enumerate().map(|(idx, c)| { buf[size + idx] = c as u8; }).count() } else { 0 } }) .sum() })?; if reply == 0 { break Ok(size) } else { size += reply; continue } } } pub fn tcp_close_connection(&mut self) -> Result { self.send_command(Command::tcp_close()) } }