e-bike-tracker-device/src/modem.rs

193 lines
7.1 KiB
Rust
Raw Normal View History

use crate::command::Command;
2022-06-13 00:55:08 +02:00
use std::thread;
2022-06-18 01:39:38 +02:00
use std::io::{Error as IoError, ErrorKind, BufRead};
2022-06-16 01:39:16 +02:00
use std::error::Error;
use std::time::{Duration, Instant};
2022-06-11 16:49:16 +02:00
use embedded_hal::serial::{Read, Write};
2022-06-13 00:55:08 +02:00
use embedded_hal::digital::v2::OutputPin;
2022-06-18 01:39:38 +02:00
use esp_idf_hal::serial::{self, Rx, Tx, SerialError};
2022-06-13 00:55:08 +02:00
2022-06-18 01:39:38 +02:00
pub type Result<T> = std::result::Result<T, ModemError>;
2022-06-13 00:55:08 +02:00
pub struct Modem<UART: serial::Uart> {
2022-06-11 16:49:16 +02:00
is_connected: bool,
2022-06-18 01:39:38 +02:00
rx: MyRx<UART>,
2022-06-13 00:55:08 +02:00
tx: Tx<UART>,
2022-06-11 16:49:16 +02:00
}
2022-06-13 00:55:08 +02:00
#[derive(Debug)]
pub enum ModemError {
CommandError(String),
2022-06-13 00:55:08 +02:00
SetupError(String),
2022-06-18 01:39:38 +02:00
TimeoutError,
}
2022-06-11 16:49:16 +02:00
2022-06-16 01:39:16 +02:00
impl Error for ModemError {}
impl std::fmt::Display for ModemError {
2022-06-11 16:49:16 +02:00
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2022-06-13 00:55:08 +02:00
write!(f, "{:?}", self)
2022-06-11 16:49:16 +02:00
}
}
2022-06-18 01:39:38 +02:00
struct MyRx<UART: serial::Uart>(Rx<UART>);
impl<UART: serial::Uart> MyRx<UART> {
fn read(&mut self) -> nb::Result<u8, SerialError> {
self.0.read()
}
fn read_blocking(&mut self) -> std::result::Result<u8, SerialError> {
nb::block!(self.read())
}
}
impl<UART: serial::Uart> std::io::Read for MyRx<UART> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
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)
}
}
2022-06-11 16:49:16 +02:00
2022-06-13 00:55:08 +02:00
impl<UART: serial::Uart> Modem<UART> {
pub fn new(tx: Tx<UART>, rx: Rx<UART>) -> Self {
2022-06-11 16:49:16 +02:00
Self {
is_connected: false,
2022-06-18 01:39:38 +02:00
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.
2022-06-18 01:39:38 +02:00
fn read_response(&mut self, contains: Option<String>, timeout: Duration) -> Result<String> {
let mut response = String::new();
let now = Instant::now();
2022-06-18 01:39:38 +02:00
let match_text: String = contains.unwrap_or("".to_string());
let mut reader = std::io::BufReader::new(&mut self.rx);
loop {
2022-06-18 01:39:38 +02:00
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() {
2022-06-18 01:39:38 +02:00
return Err(ModemError::TimeoutError);
}
2022-06-18 01:39:38 +02:00
thread::sleep(Duration::from_millis(1000));
continue;
} else {
2022-06-18 01:39:38 +02:00
response.push_str(&line);
if line.contains(&match_text) {
println!("Found match {} for line {} ... exiting response reader now!", match_text, line);
println!("-----------------------------------------------------------");
break;
}
}
2022-06-18 01:39:38 +02:00
}
Ok(response.to_string())
2022-06-11 16:49:16 +02:00
}
fn send_command(&mut self, cmd: Command) -> Result<String> {
for b in cmd.text.as_bytes().iter() {
2022-06-18 01:39:38 +02:00
nb::block!(self.tx.write(*b)).map_err(|_| ModemError::CommandError("error writing to serial".to_string()))?;
}
2022-06-18 01:39:38 +02:00
nb::block!(self.tx.write('\r' as u8)).map_err(|_| ModemError::CommandError("error writing <CR> to serial".to_string()))?;
self.read_response(cmd.contains.clone(), cmd.timeout.clone())
}
pub fn get_ip_addr(&mut self) -> Result<String> {
println!("getting ip addres ...");
let res = self.send_command(Command::getbear())?;
println!("{}", res);
Ok(res)
2022-06-13 00:55:08 +02:00
}
pub fn connect_to_gprs_ap(&mut self, apn: &str, username: &str, password: &str)-> Result<()> {
2022-06-18 01:39:38 +02:00
println!("init gprs ...");
let _ = self.send_command(Command::initgprs())?;
2022-06-13 00:55:08 +02:00
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))?;
2022-06-18 01:39:38 +02:00
println!("open gprs ...");
let _ = self.send_command(Command::initgprs())?;
self.is_connected = true;
Ok(())
2022-06-13 00:55:08 +02:00
}
2022-06-18 01:39:38 +02:00
pub fn info(&mut self)-> Result<String> {
println!("getting modem info with API command");
self.send_command(Command::modeminfo())
2022-06-11 16:49:16 +02:00
}
2022-06-18 01:39:38 +02:00
pub fn probe(&mut self)-> Result<String> {
println!("probing modem with AP command");
self.send_command(Command::probe())
}
pub fn is_gprs_attached(&mut self)-> Result<bool> {
println!("testing gprs connection ...");
let res = self.send_command(Command::is_gprs_attached())?;
Ok(res.contains("+CGATT: 1"))
}
2022-06-10 01:32:52 +02:00
}
/// 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 ...");
2022-06-18 01:39:38 +02:00
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
2022-06-18 01:39:38 +02:00
pwrkey.set_high().map_err(|_| ModemError::SetupError("Error setting PWRKEY to high.".to_string()))?;
thread::sleep(Duration::from_millis(100));
2022-06-18 01:39:38 +02:00
pwrkey.set_low().map_err(|_| ModemError::SetupError("Error setting PWRKEY to low.".to_string()))?;
thread::sleep(Duration::from_millis(1000));
2022-06-18 01:39:38 +02:00
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(())
}