rupsc: parsing and basic usage (minus clients)

This commit is contained in:
Aram 🍐 2021-07-31 01:15:15 -04:00
parent 80ceb6f1df
commit f3d9195bc4
8 changed files with 384 additions and 22 deletions

View file

@ -38,6 +38,16 @@ impl Connection {
.collect()),
}
}
/// Queries one variable for a UPS device.
pub fn get_var(&mut self, ups_name: &str, variable: &str) -> crate::Result<Variable> {
match self {
Self::Tcp(conn) => {
let var = conn.get_var(ups_name, variable)?;
Ok(Variable::parse(var.0.as_str(), var.1))
}
}
}
}
/// A blocking TCP NUT client connection.
@ -95,6 +105,15 @@ impl TcpConnection {
.collect())
}
fn get_var(&mut self, ups_name: &str, variable: &str) -> crate::Result<(String, String)> {
let query = &["VAR", ups_name, variable];
Self::write_cmd(&mut self.tcp_stream, Command::Get(query))?;
let resp = Self::read_response(&mut self.tcp_stream)?;
let (name, value) = resp.expect_var()?;
Ok((name.into(), value.into()))
}
fn write_cmd(stream: &mut TcpStream, line: Command) -> crate::Result<()> {
let line = format!("{}\n", line);
stream.write_all(line.as_bytes())?;

View file

@ -1,9 +1,10 @@
use core::fmt;
use crate::NutError;
use crate::{ClientError, NutError};
#[derive(Debug, Clone)]
pub enum Command<'a> {
Get(&'a [&'a str]),
/// Passes the login username.
SetUsername(&'a str),
/// Passes the login password.
@ -16,6 +17,7 @@ impl<'a> Command<'a> {
/// The network identifier of the command.
pub fn name(&self) -> &'static str {
match self {
Self::Get(_) => "GET",
Self::SetUsername(_) => "USERNAME",
Self::SetPassword(_) => "PASSWORD",
Self::List(_) => "LIST",
@ -25,6 +27,7 @@ impl<'a> Command<'a> {
/// The arguments of the command to serialize.
pub fn args(&self) -> Vec<&str> {
match self {
Self::Get(cmd) => cmd.to_vec(),
Self::SetUsername(username) => vec![username],
Self::SetPassword(password) => vec![password],
Self::List(query) => query.to_vec(),
@ -48,6 +51,8 @@ pub enum Response {
BeginList(String),
/// Marks the end of a list response.
EndList(String),
/// A variable response.
Var(String, String),
}
impl Response {
@ -109,6 +114,23 @@ impl Response {
}
}
}
"VAR" => {
let var_name = if args.is_empty() {
Err(ClientError::from(NutError::Generic(
"Unspecified VAR name in response".into(),
)))
} else {
Ok(args.remove(0))
}?;
let var_value = if args.is_empty() {
Err(ClientError::from(NutError::Generic(
"Unspecified VAR value in response".into(),
)))
} else {
Ok(args.remove(0))
}?;
Ok(Response::Var(var_name, var_value))
}
_ => Err(NutError::UnknownResponseType(cmd_name).into()),
}
}
@ -145,4 +167,12 @@ impl Response {
Err(NutError::UnexpectedResponse.into())
}
}
pub fn expect_var(&self) -> crate::Result<(&str, &str)> {
if let Self::Var(name, value) = &self {
Ok((name, value))
} else {
Err(NutError::UnexpectedResponse.into())
}
}
}

View file

@ -21,6 +21,12 @@ impl Default for Host {
}
}
impl From<SocketAddr> for Host {
fn from(addr: SocketAddr) -> Self {
Self::Tcp(addr)
}
}
/// An authentication mechanism.
#[derive(Clone)]
pub struct Auth {

View file

@ -79,28 +79,46 @@ impl Variable {
_ => Self::Other((name.into(), value)),
}
}
/// Returns the NUT name of the variable.
pub fn name(&self) -> &str {
use self::key::*;
match self {
Self::DeviceModel(_) => DEVICE_MODEL,
Self::DeviceManufacturer(_) => DEVICE_MANUFACTURER,
Self::DeviceSerial(_) => DEVICE_SERIAL,
Self::DeviceType(_) => DEVICE_TYPE,
Self::DeviceDescription(_) => DEVICE_DESCRIPTION,
Self::DeviceContact(_) => DEVICE_CONTACT,
Self::DeviceLocation(_) => DEVICE_LOCATION,
Self::DevicePart(_) => DEVICE_PART,
Self::DeviceMacAddress(_) => DEVICE_MAC_ADDRESS,
Self::DeviceUptime(_) => DEVICE_UPTIME,
Self::Other((name, _)) => name.as_str(),
}
}
/// Returns the value of the NUT variable.
pub fn value(&self) -> String {
match self {
Self::DeviceModel(value) => value.clone(),
Self::DeviceManufacturer(value) => value.clone(),
Self::DeviceSerial(value) => value.clone(),
Self::DeviceType(value) => value.to_string(),
Self::DeviceDescription(value) => value.clone(),
Self::DeviceContact(value) => value.clone(),
Self::DeviceLocation(value) => value.clone(),
Self::DevicePart(value) => value.clone(),
Self::DeviceMacAddress(value) => value.clone(),
Self::DeviceUptime(value) => value.as_secs().to_string(),
Self::Other((_, value)) => value.clone(),
}
}
}
impl fmt::Display for Variable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::key::*;
match self {
Self::DeviceModel(value) => write!(f, "{} = {}", DEVICE_MODEL, value),
Self::DeviceManufacturer(value) => write!(f, "{} = {}", DEVICE_MANUFACTURER, value),
Self::DeviceSerial(value) => write!(f, "{} = {}", DEVICE_SERIAL, value),
Self::DeviceType(value) => write!(f, "{} = {}", DEVICE_TYPE, value),
Self::DeviceDescription(value) => write!(f, "{} = {}", DEVICE_DESCRIPTION, value),
Self::DeviceContact(value) => write!(f, "{} = {}", DEVICE_CONTACT, value),
Self::DeviceLocation(value) => write!(f, "{} = {}", DEVICE_LOCATION, value),
Self::DevicePart(value) => write!(f, "{} = {}", DEVICE_PART, value),
Self::DeviceMacAddress(value) => write!(f, "{} = {}", DEVICE_MAC_ADDRESS, value),
Self::DeviceUptime(value) => {
write!(f, "{} = {} seconds", DEVICE_UPTIME, value.as_secs())
}
Self::Other((key, value)) => write!(f, "other({}) = {}", key, value),
}
write!(f, "{}: {}", self.name(), self.value())
}
}