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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use crate::device::*;
use crate::protocol::hidio::*;
use crate::RUNNING;
use hidapi;
use std::sync::atomic::Ordering;
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use crate::api::Endpoint;
use crate::common_capnp::NodeType;
pub const DEV_VID: u16 = 0x308f;
pub const DEV_PID: u16 = 0x0011;
pub const INTERFACE_NUMBER: i32 = 6;
pub const USAGE_PAGE: u16 = 0xFF1C;
pub const USAGE: u16 = 0x1100;
const USB_FULLSPEED_PACKET_SIZE: usize = 64;
const ENUMERATE_DELAY: u64 = 1000;
const POLL_DELAY: u64 = 1;
pub struct HIDUSBDevice {
device: hidapi::HidDevice,
}
impl HIDUSBDevice {
pub fn new(device: hidapi::HidDevice) -> HIDUSBDevice {
device.set_blocking_mode(false).unwrap();
HIDUSBDevice { device }
}
}
impl std::io::Read for HIDUSBDevice {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self.device.read(buf) {
Ok(len) => {
if len > 0 {
trace!("Received {} bytes", len);
trace!("{:x?}", &buf[0..len]);
}
Ok(len)
}
Err(e) => {
warn!("{:?}", e);
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("{:?}", e),
))
}
}
}
}
impl std::io::Write for HIDUSBDevice {
fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
let buf = {
#[allow(clippy::needless_bool)]
let prepend = if cfg!(target_os = "linux") || cfg!(target_os = "macos") {
_buf[0] == 0x00
} else if cfg!(target_os = "windows") {
true
} else {
false
};
if prepend {
let mut new_buf = vec![0x00];
new_buf.extend(_buf);
new_buf
} else {
_buf.to_vec()
}
};
match self.device.write(&buf) {
Ok(len) => {
trace!("Sent {} bytes", len);
trace!("{:x?}", &buf[0..len]);
Ok(len)
}
Err(e) => {
warn!("{:?}", e);
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("{:?}", e),
))
}
}
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl HIDIOTransport for HIDUSBDevice {}
fn device_name(device_info: &hidapi::HidDeviceInfo) -> String {
let mut string = format!(
"[{:04x}:{:04x}] ",
device_info.vendor_id, device_info.product_id
);
if let Some(m) = &device_info.manufacturer_string {
string += &m;
}
if let Some(p) = &device_info.product_string {
string += &format!(" {}", p);
}
if let Some(s) = &device_info.serial_number {
string += &format!(" ({})", s);
}
string
}
#[cfg(target_os = "linux")]
fn match_device(device_info: &hidapi::HidDeviceInfo) -> bool {
device_info.vendor_id == DEV_VID
&& device_info.product_id == DEV_PID
&& device_info.interface_number == INTERFACE_NUMBER
}
#[cfg(target_os = "macos")]
fn match_device(device_info: &hidapi::HidDeviceInfo) -> bool {
device_info.usage_page == USAGE_PAGE && device_info.usage == USAGE
}
#[cfg(target_os = "windows")]
fn match_device(device_info: &hidapi::HidDeviceInfo) -> bool {
device_info.usage_page == USAGE_PAGE && device_info.usage == USAGE
}
fn processing(mut mailer: HIDIOMailer) {
info!("Spawning hidusb spawning thread...");
let mut api = hidapi::HidApi::new().expect("HID API object creation failed");
let mut devices: Vec<HIDIOController> = vec![];
let mut last_scan = Instant::now();
let mut enumerate = true;
use rand::Rng;
let mut rng = rand::thread_rng();
loop {
while enumerate {
if !RUNNING.load(Ordering::SeqCst) {
break;
}
last_scan = Instant::now();
api.refresh_devices().unwrap();
info!("Scanning for devices");
for device_info in api.devices() {
debug!("{:#x?}", device_info);
if !match_device(device_info) {
continue;
}
info!("Connecting to {:#?}", device_info);
let path = device_info.path.clone();
match api.open_path(&path) {
Ok(device) => {
println!("Connected to {}", device_name(device_info));
let device = HIDUSBDevice::new(device);
let mut device =
HIDIOEndpoint::new(Box::new(device), USB_FULLSPEED_PACKET_SIZE as u32);
let (message_tx, message_rx) = channel::<HIDIOPacketBuffer>();
let (response_tx, response_rx) = channel::<HIDIOPacketBuffer>();
device.send_sync();
let id = rng.gen::<u64>();
let master =
HIDIOController::new(id.to_string(), device, message_tx, response_rx);
devices.push(master);
let info = Endpoint {
type_: NodeType::UsbKeyboard,
name: device_info
.product_string
.clone()
.unwrap_or_else(|| "[NONE]".to_string()),
serial: device_info
.serial_number
.clone()
.unwrap_or_else(|| "".to_string()),
id,
};
let device = HIDIOQueue::new(info, message_rx, response_tx);
mailer.register_device(id.to_string(), device);
}
Err(e) => {
warn!("{}", e);
break;
}
};
}
if !devices.is_empty() {
info!("Enumeration finished");
enumerate = false;
break;
}
thread::sleep(Duration::from_millis(ENUMERATE_DELAY));
}
loop {
if !RUNNING.load(Ordering::SeqCst) {
break;
}
if devices.is_empty() {
info!("No connected devices. Forcing scan");
enumerate = true;
break;
}
if last_scan.elapsed().as_secs() >= 60 {
info!("Been a while. Checking for new devices");
enumerate = true;
break;
}
devices = devices
.drain_filter(|dev| {
let ret = dev.process();
if ret.is_err() {
info!("{} disconnected. No loneger polling it", dev.id);
mailer.unregister_device(&dev.id);
}
ret.is_ok()
})
.collect::<Vec<_>>();
mailer.process();
thread::sleep(Duration::from_millis(POLL_DELAY));
}
}
}
pub fn initialize(mailer: HIDIOMailer) {
info!("Initializing device/hidusb...");
thread::Builder::new()
.name("hidusb".to_string())
.spawn(|| processing(mailer))
.unwrap();
}