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

65 lines
1.9 KiB
Rust
Raw Normal View History

2022-06-11 16:49:16 +02:00
use std;
use std::io::{Read, Write};
2022-06-11 16:49:16 +02:00
pub struct Modem<R: Read, W: Write> {
2022-06-11 16:49:16 +02:00
is_connected: bool,
rx: R,
tx: W,
2022-06-11 16:49:16 +02:00
}
pub enum ModemError {
GprsAPConnectionError(String),
ATCommandError(String),
CommandError(String),
}
2022-06-11 16:49:16 +02:00
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 {
match self {
Self::GprsAPConnectionError(msg) => write!(f, "gprs connection error {}", msg),
Self::ATCommandError(msg) => write!(f, "AT command error {}", msg),
Self::CommandError(msg) => write!(f, "Modem command error {}", msg),
}
2022-06-11 16:49:16 +02:00
}
}
pub type Result<T> = std::result::Result<T, ModemError>;
2022-06-11 16:49:16 +02:00
impl<R: Read, W: Write> Modem<R, W> {
pub fn new(rx: R, tx: W) -> Self {
2022-06-11 16:49:16 +02:00
Self {
is_connected: false,
rx,
tx,
}
}
fn at_command(&mut self, cmd: &str) -> Result<String> {
let mut msg = "AT+".to_owned();
msg.push_str(cmd);
self.send_command(msg.to_owned())
.map_err(|err| ModemError::ATCommandError(format!("{}", err)))
}
fn send_command(&mut self, cmd: String) -> Result<String> {
self.tx.write(cmd.as_bytes())
.map_err(|err| ModemError::CommandError(format!("{}", err)))?;
let mut response = String::new();
self.rx.read_to_string(&mut response)
.map_err(|err| ModemError::CommandError(format!("{}", err)))?;
if cfg!(debug_assertions) {
println!("{} = {}", cmd, response);
2022-06-11 16:49:16 +02:00
}
Ok(response)
2022-06-11 16:49:16 +02:00
}
pub fn connect_to_gprs_ap(&mut self, apn: &str, username: &str, password: &str)-> Result<()> {
self.at_command("CGATTCGATT=1")
.map(|_| {
println!("connecting to {} with {}:{}", apn, username, password);
self.is_connected = true;
})
.map_err(|err| ModemError::GprsAPConnectionError(format!("{}", err)))
2022-06-11 16:49:16 +02:00
}
2022-06-10 01:32:52 +02:00
}