forked from karalabe/hid
-
Notifications
You must be signed in to change notification settings - Fork 13
/
hid_enabled.go
592 lines (517 loc) · 15.9 KB
/
hid_enabled.go
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
// hid - Gopher Interface Devices (USB HID)
// Copyright (c) 2017 Péter Szilágyi. All rights reserved.
//
// This file is released under the 3-clause BSD license. Note however that Linux
// support depends on libusb, released under LGNU GPL 2.1 or later.
//go:build (linux && cgo) || (darwin && !ios && cgo) || (windows && cgo) || (android && cgo)
package hid
/*
#cgo CFLAGS: -I./hidapi/. -I./libusb/libusb/.
#cgo !hidraw,linux,!android LDFLAGS: -lrt
#cgo hidraw,linux,!android pkg-config: libudev
#cgo darwin LDFLAGS: -framework CoreFoundation -framework IOKit -framework AppKit
#cgo windows LDFLAGS: -lsetupapi
#include <stdlib.h>
#include "hidapi.h"
#include "libusb.h"
static void set_default_options(void) {
#if defined(__ANDROID__)
// see also: https://github.com/libusb/libusb/blob/e678b3fad58a508cbd0a6e6dc777fb48346f948b/android/README#L84
libusb_set_option(NULL, LIBUSB_OPTION_NO_DEVICE_DISCOVERY, NULL);
#endif
}
*/
import "C"
import (
"errors"
"runtime"
"sync"
"syscall"
"unsafe"
)
func init() {
C.set_default_options()
// just to be sure: from the docs:
// This function should be called at the beginning of
// execution however, if there is a chance of HIDAPI handles
// being opened by different threads simultaneously.
C.hid_init()
}
// enumerateLock is a mutex serializing access to USB device enumeration needed
// by the macOS USB HID system calls, which require 2 consecutive method calls
// for enumeration, causing crashes if called concurrently.
//
// For more details, see:
//
// https://developer.apple.com/documentation/iokit/1438371-iohidmanagersetdevicematching
// > "subsequent calls will cause the hid manager to release previously enumerated devices"
var enumerateLock sync.Mutex
// Supported returns whether this platform is supported by the HID library or not.
// The goal of this method is to allow programmatically handling platforms that do
// not support USB HID and not having to fall back to build constraints.
func Supported() bool {
return true
}
// Enumerate returns a list of all the HID devices attached to the system which
// match the vendor and product id:
// - If the vendor id is set to 0 then any vendor matches.
// - If the product id is set to 0 then any product matches.
// - If the vendor and product id are both 0, all HID devices are returned.
func Enumerate(vendorID uint16, productID uint16) []DeviceInfo {
enumerateLock.Lock()
defer enumerateLock.Unlock()
// Gather all device infos and ensure they are freed before returning
head := C.hid_enumerate(C.ushort(vendorID), C.ushort(productID))
if head == nil {
return nil
}
defer C.hid_free_enumeration(head)
// Iterate the list and retrieve the device details
var infos []DeviceInfo
for ; head != nil; head = head.next {
info := DeviceInfo{
Path: C.GoString(head.path),
VendorID: uint16(head.vendor_id),
ProductID: uint16(head.product_id),
Release: uint16(head.release_number),
UsagePage: uint16(head.usage_page),
Usage: uint16(head.usage),
Interface: int(head.interface_number),
BusType: BusType(head.bus_type),
}
if head.serial_number != nil {
info.Serial, _ = wcharTToString(head.serial_number)
}
if head.product_string != nil {
info.Product, _ = wcharTToString(head.product_string)
}
if head.manufacturer_string != nil {
info.Manufacturer, _ = wcharTToString(head.manufacturer_string)
}
infos = append(infos, info)
}
return infos
}
// Open connects to an HID device by its path name.
func (info DeviceInfo) Open() (*Device, error) {
enumerateLock.Lock()
defer enumerateLock.Unlock()
path := C.CString(info.Path)
defer C.free(unsafe.Pointer(path))
device := C.hid_open_path(path)
if device == nil {
return nil, errors.New("hidapi: failed to open device")
}
return &Device{
DeviceInfo: info,
device: device,
}, nil
}
// Device is a live HID USB connected device handle.
type Device struct {
DeviceInfo // Embed the infos for easier access
device *C.hid_device // Low level HID device to communicate through
lock sync.Mutex
}
// OpenByPath open the HID USB device by path and return a device handle.
func OpenByPath(p string) (*Device, error) {
path := C.CString(p)
defer C.free(unsafe.Pointer(path))
device := C.hid_open_path(path)
if device == nil {
return nil, errors.New("hidapi: failed to open device")
}
info := C.hid_get_device_info(device)
if info == nil {
return nil, errors.New("hidapi: failed to query device info")
}
dev := &Device{
device: device,
DeviceInfo: DeviceInfo{
Path: C.GoString(info.path),
VendorID: uint16(info.vendor_id),
ProductID: uint16(info.product_id),
Release: uint16(info.release_number),
UsagePage: uint16(info.usage_page),
Usage: uint16(info.usage),
Interface: int(info.interface_number),
BusType: BusType(info.bus_type),
},
}
if info.serial_number != nil {
dev.Serial, _ = wcharTToString(info.serial_number)
}
if info.product_string != nil {
dev.Product, _ = wcharTToString(info.product_string)
}
if info.manufacturer_string != nil {
dev.Manufacturer, _ = wcharTToString(info.manufacturer_string)
}
return dev, nil
}
// Close releases the HID USB device handle.
func (dev *Device) Close() error {
dev.lock.Lock()
defer dev.lock.Unlock()
if dev.device != nil {
C.hid_close(dev.device)
dev.device = nil
}
return nil
}
// Write sends an output report to a HID device.
//
// Write will send the data on the first OUT endpoint, if one exists. If it does
// not, it will send the data through the Control Endpoint (Endpoint 0).
func (dev *Device) Write(b []byte) (int, error) {
// Abort if nothing to write
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Prepend a HID report ID on Windows, other OSes don't need it
var report []byte
if runtime.GOOS == "windows" {
report = append([]byte{0x00}, b...)
} else {
report = b
}
// Execute the write operation
written := int(C.hid_write(device, (*C.uchar)(&report[0]), C.size_t(len(report))))
if written == -1 {
// If the write failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return written, nil
}
// SendFeatureReport sends a feature report to a HID device
//
// Feature reports are sent over the Control endpoint as a Set_Report transfer.
// The first byte of b must contain the Report ID. For devices which only
// support a single report, this must be set to 0x0. The remaining bytes
// contain the report data. Since the Report ID is mandatory, calls to
// SendFeatureReport() will always contain one more byte than the report
// contains. For example, if a hid report is 16 bytes long, 17 bytes must be
// passed to SendFeatureReport(): the Report ID (or 0x0, for devices
// which do not use numbered reports), followed by the report data (16 bytes).
// In this example, the length passed in would be 17.
func (dev *Device) SendFeatureReport(b []byte) (int, error) {
// Abort if nothing to write
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Send the feature report
written := int(C.hid_send_feature_report(device, (*C.uchar)(&b[0]), C.size_t(len(b))))
if written == -1 {
// If the write failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return written, nil
}
// Read retrieves an input report from a HID device.
//
// Input reports are returned to the host through the INTERRUPT IN
// endpoint. The first byte will contain the Report number if the
// device uses numbered reports.
func (dev *Device) Read(b []byte) (int, error) {
// Abort if nothing to read
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
readAgain:
// Execute the read operation
read, err := C.hid_read(device, (*C.uchar)(&b[0]), C.size_t(len(b)))
if read == -1 {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EINTR {
goto readAgain
}
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return int(read), nil
}
// ReadTimeout retrieves an input report from a HID device with a timeout. If timeout is -1 a
// blocking read is performed, else a non-blocking that waits timeout milliseconds
//
// Input reports are returned to the host through the INTERRUPT IN
// endpoint. The first byte will contain the Report number if the
// device uses numbered reports.
func (dev *Device) ReadTimeout(b []byte, timeout int) (int, error) {
// Abort if nothing to read
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
readAgain:
// Execute the read operation
read, err := C.hid_read_timeout(device, (*C.uchar)(&b[0]), C.size_t(len(b)), C.int(timeout))
if read == -1 {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EINTR {
goto readAgain
}
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return int(read), nil
}
// GetFeatureReport retrieves a feature report from a HID device
//
// Set the first byte of []b to the Report ID of the report to be read. Make
// sure to allow space for this extra byte in []b. Upon return, the first byte
// will still contain the Report ID, and the report data will start in b[1].
func (dev *Device) GetFeatureReport(b []byte) (int, error) {
// Abort if we don't have anywhere to write the results
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Retrieve the feature report
read := int(C.hid_get_feature_report(device, (*C.uchar)(&b[0]), C.size_t(len(b))))
if read == -1 {
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return read, nil
}
// GetInputReport retrieves a input report from a HID device
//
// Set the first byte of []b to the Report ID of the report to be read. Make
// sure to allow space for this extra byte in []b. Upon return, the first byte
// will still contain the Report ID, and the report data will start in b[1].
func (dev *Device) GetInputReport(b []byte) (int, error) {
// Abort if we don't have anywhere to write the results
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Retrieve the feature report
read := int(C.hid_get_input_report(device, (*C.uchar)(&b[0]), C.size_t(len(b))))
if read == -1 {
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return read, nil
}
// SetNonblocking sets the device handle to be non-blocking.
//
// In non-blocking mode calls to Read() will return
// immediately with a value of 0 if there is no data to be
// read. In blocking mode, Read() will wait (block) until
// there is data to read before returning.
func (dev *Device) SetNonblocking(b bool) error {
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return ErrDeviceClosed
}
i := C.int(0)
if b {
i = 1
}
res := int(C.hid_set_nonblocking(device, i))
if res == -1 {
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return errors.New("hidapi: " + failure)
}
return nil
}
// GetDeviceInfo gets the DeviceInfo from a HID device.
func (dev *Device) GetDeviceInfo() (*DeviceInfo, error) {
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return nil, ErrDeviceClosed
}
i := C.hid_get_device_info(device)
if i == nil {
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return nil, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return nil, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return nil, errors.New("hidapi: " + failure)
}
info := &DeviceInfo{
Path: C.GoString(i.path),
VendorID: uint16(i.vendor_id),
ProductID: uint16(i.product_id),
Release: uint16(i.release_number),
UsagePage: uint16(i.usage_page),
Usage: uint16(i.usage),
Interface: int(i.interface_number),
BusType: BusType(i.bus_type),
}
if i.serial_number != nil {
info.Serial, _ = wcharTToString(i.serial_number)
}
if i.product_string != nil {
info.Product, _ = wcharTToString(i.product_string)
}
if i.manufacturer_string != nil {
info.Manufacturer, _ = wcharTToString(i.manufacturer_string)
}
return info, nil
}
// GetDeviceInfo gets a report descriptor from a HID device.
func (dev *Device) GetReportDescriptor() ([]byte, error) {
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return nil, ErrDeviceClosed
}
b := make([]byte, C.HID_API_MAX_REPORT_DESCRIPTOR_SIZE)
read := int(C.hid_get_report_descriptor(device, (*C.uchar)(&b[0]), C.size_t(len(b))))
if read == -1 {
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return nil, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return nil, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return nil, errors.New("hidapi: " + failure)
}
return b[:read], nil
}