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

399 lines
14 KiB
Rust
Raw Normal View History

use crate::command::Command;
2022-06-13 00:55:08 +02:00
use std::thread;
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;
use esp_idf_hal::serial::{self, Rx, Tx};
2022-06-13 00:55:08 +02:00
const MAX_TCP_MANUAL_REPLY_SIZE: usize = 300;
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-21 01:27:27 +02:00
rx: RxIter<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),
SendDataError,
ReadError,
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-21 01:27:27 +02:00
pub struct RxIter<UART: serial::Uart> {
inner: Rx<UART>,
timeout: Duration,
}
2022-06-21 01:27:27 +02:00
impl<UART: serial::Uart> RxIter<UART> {
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<String> {
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)
}
}
}
2022-06-21 01:27:27 +02:00
impl<UART: serial::Uart> Iterator for RxIter<UART> {
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<Self::Item> {
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<UART: serial::Uart> Modem<UART> {
pub fn new(tx: Tx<UART>, rx: Rx<UART>) -> Self {
Self {
2022-06-21 01:27:27 +02:00
rx: RxIter { inner: rx, timeout: Duration::from_millis(0) },
tx,
}
2022-06-18 01:39:38 +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 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(())
2022-06-18 01:39:38 +02:00
}
2022-07-04 17:04:09 +02:00
/// Reads the serial RX until the `contains` string is encoutered if `contains` is Some(s), if
/// None, then the first line is returned. If a timeout is reached. The timeout is provided on
/// input via the `timeout` argument. The first argument `contains` is checked against every
/// line in the response.
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 start = Instant::now();
let match_text: String = contains.unwrap_or("\n".to_string());
2022-06-18 01:39:38 +02:00
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())
}
2022-06-18 01:39:38 +02:00
}
2022-06-11 16:49:16 +02:00
}
2022-06-26 00:56:59 +02:00
#[inline(always)]
fn send_bytes(&mut self, payload: &[u8], eos: Option<u8>) -> Result<()> {
2022-07-04 17:04:09 +02:00
//self.rx.clear();
for b in payload.iter() {
2022-06-26 00:56:59 +02:00
nb::block!(self.tx.write(*b))
.map_err(|_| ModemError::CommandError(format!("error writing {} to serial", b)))?;
}
eos.map(|b| nb::block!(self.tx.write(b)));
Ok(())
}
fn send_command(&mut self, cmd: Command) -> Result<String> {
println!("-----------------------------------------------------------");
println!("Sending {} ...", cmd.text);
let _ = self.send_bytes(cmd.text.as_bytes(), Some('\r' as u8))?;
self.read_response(cmd.contains, cmd.timeout)
}
fn tcp_send_data(&mut self, buf: &[u8]) -> Result<String> {
let _ = self.send_bytes("AT+CIPSEND".as_bytes(), Some('\r' as u8))?;
let send_request: String = self.rx.reset(Duration::from_millis(3000))
.map(char::from)
.take_while(|c| *c != '>').collect();
2022-07-04 17:04:09 +02:00
if send_request != "\r\n" {
println!("{:?}", send_request.as_bytes());
return Err(ModemError::SendDataError);
}
self.send_bytes(buf, Some(26))?; // 26_u8 = Ctrl+z - to end sending data
2022-07-04 17:04:09 +02:00
self.read_response(Some("SEND OK".to_string()), Duration::from_millis(3000))
2022-06-18 01:39:38 +02:00
}
pub fn gprs_status(&mut self) -> Result<String> {
self.send_command(Command::gprs_bearer_status())
}
pub fn gprs_attach_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::gprs_init())?;
2022-06-18 01:39:38 +02:00
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))?;
2022-06-18 01:39:38 +02:00
Ok(())
}
pub fn gprs_connect(&mut self)-> Result<()> {
2022-06-18 01:39:38 +02:00
println!("open gprs ...");
let _ = self.send_command(Command::gprs_bearer_open())?;
Ok(())
2022-06-13 00:55:08 +02:00
}
2022-06-18 01:39:38 +02:00
pub fn is_gprs_attached(&mut self)-> Result<bool> {
let res = self.send_command(Command::is_gprs_attached())?;
Ok(res.contains("+CGATT: 1"))
}
pub fn tcp_is_ssl_enabled(&mut self) -> Result<bool> {
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(())
}
2022-07-04 17:04:09 +02:00
pub fn tcp_set_manual_receive(&mut self, is_manual: bool) -> Result<()> {
self.send_command(Command::tcp_set_manual_receive(is_manual))?;
2022-06-21 02:30:00 +02:00
Ok(())
}
2022-06-25 18:31:43 +02:00
pub fn tcp_send(&mut self, buf: &[u8]) -> Result<()> {
self.tcp_send_data(buf)?;
Ok(())
}
2022-06-21 02:30:00 +02:00
fn tcp_parse_response_size(&mut self, reply_line: &str) -> Result<usize> {
2022-06-22 19:35:01 +02:00
reply_line.split(',')
.into_iter()
.last()
.unwrap_or("x")
.parse::<usize>()
.map_err(|_| ModemError::CommandError(format!("response size should be a number, got {}", reply_line)))
}
pub fn tcp_receive_reply_len(&mut self) -> Result<usize> {
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))
2022-06-22 19:35:01 +02:00
.unwrap_or(Err(ModemError::CommandError(format!("received 0 elements from parsing"))))
}
pub fn tcp_receive(&mut self, buf: &mut [u8]) -> Result<usize> {
let mut size = 0;
loop {
2022-07-04 17:04:09 +02:00
let reply = self.send_command(Command::tcp_receive(MAX_TCP_MANUAL_REPLY_SIZE))
.map(|reply| {
reply
.split("\r\n")
.filter(|line| line.len() > 2 && !line.contains("+CIPRXGET: 2,"))
.next()
.map(|line| line.chars().enumerate().map(|(idx, c)| buf[size + idx] = c as u8).count())
})?;
2022-07-04 17:04:09 +02:00
match reply {
Some(0) | None => {
break Ok(size)
},
Some(x) => {
size += x;
continue
},
}
}
2022-06-21 02:30:00 +02:00
}
pub fn tcp_close_connection(&mut self) -> Result<String> {
self.send_command(Command::tcp_close())
}
pub fn http_post(&mut self, url: &str, token: &str, content: &[u8]) -> Result<String> {
let _ = self.send_command(Command::http_init());
let _ = self.send_command(Command::http_set_cid());
2022-07-04 17:04:09 +02:00
let _ = self.send_command(Command::http_set_url(url));
let _ = self.send_command(Command::http_set_header("X-Secret", token));
let _ = self.send_command(Command::http_set_header("X-Topic", "device-dev"));
let _ = self.send_command(Command::http_set_content("application/json"));
2022-07-04 17:04:09 +02:00
let _ = self.send_command(Command::http_set_ssl(true));
let _ = self.send_command(Command::http_post_len(content.len(), 100000));
let _ = self.send_bytes(content, Some(26));
let _ = self.send_command(Command::http_post());
2022-07-04 17:04:09 +02:00
self.send_command(Command::http_read_response())
}
pub fn http_get(&mut self, url: &str) -> Result<String> {
let _ = self.send_command(Command::http_init());
let _ = self.send_command(Command::http_set_cid());
let _ = self.send_command(Command::http_set_url(url));
let _ = self.send_command(Command::http_set_redirect(true));
let _ = self.send_command(Command::http_set_ssl(true));
let _ = self.send_command(Command::http_get());
self.send_command(Command::http_read_response())
}
pub fn http_close(&mut self) -> Result<()> {
let _ = self.send_command(Command::http_close())?;
Ok(())
}
pub fn chip_info(&mut self) -> Result<()> {
let _ = self.send_command(Command::manufacturer_id())?;
thread::sleep(Duration::from_millis(1000));
let _ = self.send_command(Command::model_id())?;
thread::sleep(Duration::from_millis(1000));
let _ = self.send_command(Command::release_id())?;
Ok(())
}
pub fn location(&mut self) -> Result<()> {
let _ = self.send_command(Command::get_location())?;
Ok(())
}
pub fn ssl_opt(&mut self) -> Result<()> {
let _ = self.send_command(Command::ssl_opt())?;
Ok(())
}
2022-07-04 17:04:09 +02:00
fn file_write(&mut self, buf: &[u8], path: &str, append: bool, input_time_sec: usize) -> Result<()> {
let cmd = Command::fs_file_write(path, append, buf.len(), input_time_sec);
let _ = self.send_bytes(cmd.text.as_bytes(), Some('\r' as u8))?;
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, None)?;
let _ = self.read_response(Some("OK".to_string()), Duration::from_millis(3000));
Ok(())
}
pub fn upload_cert(&mut self, path: &str, cert: &[u8]) -> Result<()> {
let _ = self.send_command(Command::fs_file_create(path))?;
let _ = self.file_write(cert, path, false, 20000)?;
Ok(())
}
pub fn fs_list(&mut self, path: &str) -> Result<()> {
let _ = self.send_command(Command::fs_list(path))?;
Ok(())
}
pub fn fs_free_space(&mut self) -> Result<()> {
let _ = self.send_command(Command::fs_free_size())?;
Ok(())
}
pub fn ssl_set_client_cert(&mut self, path: &str, password: &str) -> Result<()> {
let _ = self.send_command(Command::ssl_set_client_cert(path, password))?;
Ok(())
}
pub fn ssl_set_root_cert(&mut self, path: &str, filesize: usize) -> Result<()> {
let _ = self.send_command(Command::ssl_set_root_cert(path, filesize))?;
Ok(())
}
}