use crate::api::ApiRequest;
use crate::error::{RbkError, RbkResult};
use crate::port_client::RbkPortClient;
use std::time::Duration;
const STATE_PORT: u16 = 19204;
const CONTROL_PORT: u16 = 19205;
const NAV_PORT: u16 = 19206;
const CONFIG_PORT: u16 = 19207;
const KERNEL_PORT: u16 = 19208;
const MISC_PORT: u16 = 19210;
pub struct RbkClient {
#[allow(dead_code)]
host: String,
config_client: RbkPortClient,
misc_client: RbkPortClient,
state_client: RbkPortClient,
control_client: RbkPortClient,
nav_client: RbkPortClient,
kernel_client: RbkPortClient,
}
impl RbkClient {
pub fn new(host: impl Into<String>) -> Self {
let host = host.into();
Self {
config_client: RbkPortClient::new(host.clone(), CONFIG_PORT),
misc_client: RbkPortClient::new(host.clone(), MISC_PORT),
state_client: RbkPortClient::new(host.clone(), STATE_PORT),
control_client: RbkPortClient::new(host.clone(), CONTROL_PORT),
nav_client: RbkPortClient::new(host.clone(), NAV_PORT),
kernel_client: RbkPortClient::new(host.clone(), KERNEL_PORT),
host,
}
}
pub async fn request<T>(
&self,
request: T,
timeout: Duration,
) -> RbkResult<T::Response>
where
T: crate::api::ToRequestBody + crate::api::FromResponseBody,
{
let timeout = if timeout.is_zero() {
Duration::from_secs(10)
} else {
timeout
};
let api = request.to_api_request();
let request_str = request
.to_request_body()
.map_err(|e| RbkError::ParseError(e.to_string()))?;
let api_no = api.api_no();
let response_str = match api {
ApiRequest::State(_) => {
self.state_client
.request(api_no, &request_str, timeout)
.await?
}
ApiRequest::Control(_) => {
self.control_client
.request(api_no, &request_str, timeout)
.await?
}
ApiRequest::Nav(_) => {
self.nav_client
.request(api_no, &request_str, timeout)
.await?
}
ApiRequest::Config(_) => {
self.config_client
.request(api_no, &request_str, timeout)
.await?
}
ApiRequest::Peripheral(_) => {
self.misc_client
.request(api_no, &request_str, timeout)
.await?
}
ApiRequest::Kernel(_) => {
self.kernel_client
.request(api_no, &request_str, timeout)
.await?
}
ApiRequest::Push(_) => {
self.misc_client
.request(api_no, &request_str, timeout)
.await?
}
};
serde_json::from_str(&response_str)
.map_err(|e| RbkError::ParseError(e.to_string()))
}
}
impl Drop for RbkClient {
fn drop(&mut self) {
}
}