#![cfg(any(feature = "tokio", feature = "smol"))]
use crate::{
asynchronous::read_response, options::SAMV3_TCP_PORT, proto::router::RouterApiController, Error,
};
#[cfg(feature = "tokio")]
use tokio::{io::AsyncWriteExt, net::TcpStream};
#[cfg(feature = "smol")]
use smol::{io::AsyncWriteExt, net::TcpStream};
pub struct RouterApi {
port: u16,
}
impl Default for RouterApi {
fn default() -> Self {
Self {
port: SAMV3_TCP_PORT,
}
}
}
impl RouterApi {
pub fn new(port: u16) -> Self {
Self { port }
}
}
impl RouterApi {
pub async fn lookup_name(&self, name: &str) -> crate::Result<String> {
let mut controller = RouterApiController::new();
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", self.port)).await?;
let command = controller.handshake_router_api()?;
stream.write_all(&command).await?;
let response = read_response(&mut stream).await.ok_or(Error::Malformed)?;
controller.handle_response(&response)?;
let command = controller.lookup_name(name)?;
stream.write_all(&command).await?;
let response = read_response(&mut stream).await.ok_or(Error::Malformed)?;
controller.handle_response(&response)?;
Ok(controller.destination())
}
pub async fn generate_destination(&self) -> crate::Result<(String, String)> {
let mut controller = RouterApiController::new();
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", self.port)).await?;
let command = controller.handshake_router_api()?;
stream.write_all(&command).await?;
let response = read_response(&mut stream).await.ok_or(Error::Malformed)?;
controller.handle_response(&response)?;
let command = controller.generate_destination()?;
stream.write_all(&command).await?;
let response = read_response(&mut stream).await.ok_or(Error::Malformed)?;
controller.handle_response(&response)?;
Ok(controller.generated_destination())
}
}