1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#![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,
}
}