use crate::rfcomm::RfcommChannel;
use futures_core::Stream;
use webbluetooth_core::{AtLine, AtParser, DunState, Result};
pub struct DunSession {
channel: RfcommChannel,
parser: AtParser,
state: DunState,
}
impl DunSession {
pub fn new(channel: RfcommChannel) -> Self {
Self {
channel,
parser: AtParser::default(),
state: DunState::Idle,
}
}
pub fn start(&mut self) -> Result<()> {
self.state = DunState::Negotiating;
self.send_command("AT")
}
pub fn send_command(&self, command: &str) -> Result<()> {
let bytes = webbluetooth_core::encode_command(command)
.map_err(|error| webbluetooth_core::Error::InvalidModification(error.to_string()))?;
self.channel.send(&bytes)
}
pub fn dial(&mut self, number: &str) -> Result<()> {
self.state = DunState::Negotiating;
self.send_command(&format!("ATD{number};"))
}
pub fn hang_up(&mut self) -> Result<()> {
self.send_command("ATH")?;
self.state = DunState::Idle;
Ok(())
}
pub fn send_data(&self, data: &[u8]) -> Result<()> {
if self.state != DunState::Connected {
return Err(webbluetooth_core::Error::InvalidState(
"DUN data cannot be sent before CONNECT".into(),
));
}
self.channel.send(data)
}
pub fn parse_bytes(&mut self, bytes: &[u8]) -> Vec<AtLine> {
let lines = self.parser.feed(bytes);
for line in &lines {
if matches!(line, AtLine::Command(command) if command == "CONNECT")
|| (matches!(line, AtLine::Ok) && self.state == DunState::Negotiating)
{
self.state = DunState::Connected;
} else if matches!(line, AtLine::Command(command) if command == "NO CARRIER") {
self.state = DunState::Idle;
} else if matches!(line, AtLine::Error) {
self.state = DunState::Failed;
}
}
lines
}
pub fn state(&self) -> DunState {
self.state
}
pub fn take_incoming(&self) -> Option<impl Stream<Item = Vec<u8>>> {
self.channel.take_incoming()
}
pub fn channel(&self) -> &RfcommChannel {
&self.channel
}
pub fn close(&self) {
self.channel.close();
}
}