Initial commit

This commit is contained in:
2022-10-19 08:38:51 -07:00
commit 1809701a82
6 changed files with 384 additions and 0 deletions

84
src/chrony.rs Normal file
View File

@@ -0,0 +1,84 @@
use chrony_candm::reply::{self, ReplyBody};
use chrony_candm::request::{self, RequestBody};
use std::net::SocketAddr;
use tokio::time::timeout;
pub struct ChronyClient {
pub server: SocketAddr,
client: chrony_candm::Client,
timeout: std::time::Duration,
}
impl ChronyClient {
pub fn new(client: chrony_candm::Client, server: SocketAddr, timeout: std::time::Duration) -> Self {
Self {
server,
client,
timeout,
}
}
pub async fn get_tracking(&self) -> Result<reply::Tracking, std::io::Error> {
let reply = timeout(
self.timeout,
self.client.query(RequestBody::Tracking, self.server),
)
.await??;
match reply.body {
ReplyBody::Tracking(tracking) => Ok(tracking),
_ => Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Unexpected response type",
)),
}
}
pub async fn get_sources(&self) -> Result<Vec<reply::SourceData>, std::io::Error> {
let reply = timeout(
self.timeout,
self.client.query(RequestBody::NSources, self.server),
)
.await??;
let nsources = match reply.body {
ReplyBody::NSources(ns) => Ok(i32::try_from(ns.n_sources).unwrap()),
_ => Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Unexpected response type",
)),
}?;
let mut res = Vec::with_capacity(
nsources
.try_into()
.expect("Ridiculously unconvertible number of sources"),
);
for x in 0..nsources {
res.push(self.get_source(x).await?);
}
Ok(res)
}
async fn get_source(&self, index: i32) -> Result<reply::SourceData, std::io::Error> {
let reply = timeout(
self.timeout,
self.client.query(
RequestBody::SourceData(request::SourceData { index: index }),
self.server,
),
)
.await??;
let sourcedata = match reply.body {
ReplyBody::SourceData(sourcedata) => Ok(sourcedata),
_ => Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Invalid response",
)),
}?;
Ok(sourcedata)
}
}