#![deny(missing_docs)]
#![forbid(unsafe_code)]
use hidapi::{HidApi, HidDevice};
#[cfg(feature = "units")]
use uom::si::f64::Force;
mod dymo;
#[derive(Clone, Debug)]
pub enum HidScaleError {
CantReadDueTo(String),
NotEnoughData,
Overloaded,
UnknownUnits,
UnreportableReading,
}
pub type Result<T> = std::result::Result<T, HidScaleError>;
pub trait ScaleDriver {
#[cfg(feature = "units")]
fn read(&self) -> Result<Force>;
fn read_kilograms(&self) -> Result<f64>;
fn read_pounds(&self) -> Result<f64>;
}
pub fn get_all_scales() -> Vec<Box<dyn ScaleDriver>> {
let api = HidApi::new().expect("Couldn't aquire the HID API???");
api.device_list()
.filter_map(|info| {
let vendor_id = info.vendor_id();
let product_id = info.product_id();
info.open_device(&api).ok().and_then(|dev| make_driver(vendor_id, product_id, dev))
})
.collect()
}
pub fn get_scales_by_usb_id(vendor_id: u16, product_id: u16) -> Vec<Box<dyn ScaleDriver>> {
let api = HidApi::new().expect("Couldn't aquire the HID API???");
api.device_list()
.filter_map(|info| {
let vid = info.vendor_id();
let pid = info.product_id();
if vid != vendor_id || pid != product_id {
return None;
}
info.open_device(&api).ok().and_then(|dev| make_driver(vendor_id, product_id, dev))
})
.collect()
}
pub fn get_scale_by_serial_number(serial_number: &str) -> Option<Box<dyn ScaleDriver>> {
let api = HidApi::new().expect("Couldn't aquire the HID API???");
let result = api
.device_list()
.filter_map(|info| {
let vendor_id = info.vendor_id();
let product_id = info.product_id();
info.open_device(&api).ok().and_then(|dev| match dev.get_serial_number_string() {
Ok(Some(s)) if s == serial_number => make_driver(vendor_id, product_id, dev),
_ => None,
})
})
.next();
result
}
fn make_driver(vendor_id: u16, product_id: u16, device: HidDevice) -> Option<Box<dyn ScaleDriver>> {
match vendor_id {
dymo::VENDOR_ID => dymo::make_driver(product_id, device),
_ => None,
}
}