Skip to content
0.2.0-dev Download ZIP
1612 lines ·44.6 KB Raw
1/*******************************************************
2 HIDAPI - Multi-Platform library for
3 communication with HID devices.
4
5 Alan Ott
6 Signal 11 Software
7
8 libusb/hidapi Team
9
10 Copyright 2022, All Rights Reserved.
11
12 At the discretion of the user of this library,
13 this software may be licensed under the terms of the
14 GNU General Public License v3, a BSD-Style license, or the
15 original HIDAPI license as outlined in the LICENSE.txt,
16 LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
17 files located at the root of the source distribution.
18 These files may also be found in the public source
19 code repository located at:
20 https://github.com/libusb/hidapi .
21********************************************************/
22
23/* See Apple Technical Note TN2187 for details on IOHidManager. */
24
25#include <IOKit/hid/IOHIDManager.h>
26#include <IOKit/hid/IOHIDKeys.h>
27#include <IOKit/IOKitLib.h>
28#include <IOKit/usb/USBSpec.h>
29#include <CoreFoundation/CoreFoundation.h>
30#include <mach/mach_error.h>
31#include <stdbool.h>
32#include <wchar.h>
33#include <locale.h>
34#include <pthread.h>
35#include <sys/time.h>
36#include <unistd.h>
37#include <dlfcn.h>
38
39#include "hidapi_darwin.h"
40
41/* Barrier implementation because Mac OSX doesn't have pthread_barrier.
42 It also doesn't have clock_gettime(). So much for POSIX and SUSv2.
43 This implementation came from Brent Priddy and was posted on
44 StackOverflow. It is used with his permission. */
45typedef int pthread_barrierattr_t;
46typedef struct pthread_barrier {
47 pthread_mutex_t mutex;
48 pthread_cond_t cond;
49 int count;
50 int trip_count;
51} pthread_barrier_t;
52
53static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
54{
55 (void) attr;
56
57 if (count == 0) {
58 errno = EINVAL;
59 return -1;
60 }
61
62 if (pthread_mutex_init(&barrier->mutex, 0) < 0) {
63 return -1;
64 }
65 if (pthread_cond_init(&barrier->cond, 0) < 0) {
66 pthread_mutex_destroy(&barrier->mutex);
67 return -1;
68 }
69 barrier->trip_count = count;
70 barrier->count = 0;
71
72 return 0;
73}
74
75static int pthread_barrier_destroy(pthread_barrier_t *barrier)
76{
77 pthread_cond_destroy(&barrier->cond);
78 pthread_mutex_destroy(&barrier->mutex);
79 return 0;
80}
81
82static int pthread_barrier_wait(pthread_barrier_t *barrier)
83{
84 pthread_mutex_lock(&barrier->mutex);
85 ++(barrier->count);
86 if (barrier->count >= barrier->trip_count) {
87 barrier->count = 0;
88 pthread_mutex_unlock(&barrier->mutex);
89 pthread_cond_broadcast(&barrier->cond);
90 return 1;
91 }
92 else {
93 do {
94 pthread_cond_wait(&barrier->cond, &(barrier->mutex));
95 }
96 while (barrier->count != 0);
97
98 pthread_mutex_unlock(&barrier->mutex);
99 return 0;
100 }
101}
102
103static int return_data(hid_device *dev, unsigned char *data, size_t length);
104
105/* Linked List of input reports received from the device. */
106struct input_report {
107 uint8_t *data;
108 size_t len;
109 struct input_report *next;
110};
111
112static struct hid_api_version api_version = {
113 .major = HID_API_VERSION_MAJOR,
114 .minor = HID_API_VERSION_MINOR,
115 .patch = HID_API_VERSION_PATCH
116};
117
118/* - Run context - */
119static IOHIDManagerRef hid_mgr = 0x0;
120static int is_macos_10_10_or_greater = 0;
121static IOOptionBits device_open_options = 0;
122static wchar_t *last_global_error_str = NULL;
123/* --- */
124
125struct hid_device_ {
126 IOHIDDeviceRef device_handle;
127 IOOptionBits open_options;
128 int blocking;
129 int disconnected;
130 CFStringRef run_loop_mode;
131 CFRunLoopRef run_loop;
132 CFRunLoopSourceRef source;
133 uint8_t *input_report_buf;
134 CFIndex max_input_report_len;
135 struct input_report *input_reports;
136 struct hid_device_info* device_info;
137
138 pthread_t thread;
139 pthread_mutex_t mutex; /* Protects input_reports */
140 pthread_cond_t condition;
141 pthread_barrier_t barrier; /* Ensures correct startup sequence */
142 pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */
143 int shutdown_thread;
144 wchar_t *last_error_str;
145};
146
147static hid_device *new_hid_device(void)
148{
149 hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
150 if (dev == NULL) {
151 return NULL;
152 }
153
154 dev->device_handle = NULL;
155 dev->open_options = device_open_options;
156 dev->blocking = 1;
157 dev->disconnected = 0;
158 dev->run_loop_mode = NULL;
159 dev->run_loop = NULL;
160 dev->source = NULL;
161 dev->input_report_buf = NULL;
162 dev->input_reports = NULL;
163 dev->device_info = NULL;
164 dev->shutdown_thread = 0;
165 dev->last_error_str = NULL;
166
167 /* Thread objects */
168 pthread_mutex_init(&dev->mutex, NULL);
169 pthread_cond_init(&dev->condition, NULL);
170 pthread_barrier_init(&dev->barrier, NULL, 2);
171 pthread_barrier_init(&dev->shutdown_barrier, NULL, 2);
172
173 return dev;
174}
175
176static void free_hid_device(hid_device *dev)
177{
178 if (!dev)
179 return;
180
181 /* Delete any input reports still left over. */
182 struct input_report *rpt = dev->input_reports;
183 while (rpt) {
184 struct input_report *next = rpt->next;
185 free(rpt->data);
186 free(rpt);
187 rpt = next;
188 }
189
190 /* Free the string and the report buffer. The check for NULL
191 is necessary here as CFRelease() doesn't handle NULL like
192 free() and others do. */
193 if (dev->run_loop_mode)
194 CFRelease(dev->run_loop_mode);
195 if (dev->source)
196 CFRelease(dev->source);
197 free(dev->input_report_buf);
198 hid_free_enumeration(dev->device_info);
199
200 /* Clean up the thread objects */
201 pthread_barrier_destroy(&dev->shutdown_barrier);
202 pthread_barrier_destroy(&dev->barrier);
203 pthread_cond_destroy(&dev->condition);
204 pthread_mutex_destroy(&dev->mutex);
205
206 /* Free the structure itself. */
207 free(dev);
208}
209
210
211#ifndef HIDAPI_USING_SDL_RUNTIME
212/* The caller must free the returned string with free(). */
213static wchar_t *utf8_to_wchar_t(const char *utf8)
214{
215 wchar_t *ret = NULL;
216
217 if (utf8) {
218 size_t wlen = mbstowcs(NULL, utf8, 0);
219 if ((size_t) -1 == wlen) {
220 return wcsdup(L"");
221 }
222 ret = (wchar_t*) calloc(wlen+1, sizeof(wchar_t));
223 if (ret == NULL) {
224 /* as much as we can do at this point */
225 return NULL;
226 }
227 mbstowcs(ret, utf8, wlen+1);
228 ret[wlen] = 0x0000;
229 }
230
231 return ret;
232}
233#endif
234
235
236/* Makes a copy of the given error message (and decoded according to the
237 * currently locale) into the wide string pointer pointed by error_str.
238 * The last stored error string is freed.
239 * Use register_error_str(NULL) to free the error message completely. */
240static void register_error_str(wchar_t **error_str, const char *msg)
241{
242 free(*error_str);
243#ifdef HIDAPI_USING_SDL_RUNTIME
244 /* Thread-safe error handling */
245 if (msg) {
246 SDL_SetError("%s", msg);
247 } else {
248 SDL_ClearError();
249 }
250#else
251 *error_str = utf8_to_wchar_t(msg);
252#endif
253}
254
255/* Similar to register_error_str, but allows passing a format string with va_list args into this function. */
256static void register_error_str_vformat(wchar_t **error_str, const char *format, va_list args)
257{
258 char msg[1024];
259 vsnprintf(msg, sizeof(msg), format, args);
260
261 register_error_str(error_str, msg);
262}
263
264/* Set the last global error to be reported by hid_error(NULL).
265 * The given error message will be copied (and decoded according to the
266 * currently locale, so do not pass in string constants).
267 * The last stored global error message is freed.
268 * Use register_global_error(NULL) to indicate "no error". */
269static void register_global_error(const char *msg)
270{
271 register_error_str(&last_global_error_str, msg);
272}
273
274/* Similar to register_global_error, but allows passing a format string into this function. */
275static void register_global_error_format(const char *format, ...)
276{
277 va_list args;
278 va_start(args, format);
279 register_error_str_vformat(&last_global_error_str, format, args);
280 va_end(args);
281}
282
283/* Set the last error for a device to be reported by hid_error(dev).
284 * The given error message will be copied (and decoded according to the
285 * currently locale, so do not pass in string constants).
286 * The last stored device error message is freed.
287 * Use register_device_error(dev, NULL) to indicate "no error". */
288static void register_device_error(hid_device *dev, const char *msg)
289{
290 register_error_str(&dev->last_error_str, msg);
291}
292
293/* Similar to register_device_error, but you can pass a format string into this function. */
294static void register_device_error_format(hid_device *dev, const char *format, ...)
295{
296 va_list args;
297 va_start(args, format);
298 register_error_str_vformat(&dev->last_error_str, format, args);
299 va_end(args);
300}
301
302
303static CFArrayRef get_array_property(IOHIDDeviceRef device, CFStringRef key)
304{
305 CFTypeRef ref = IOHIDDeviceGetProperty(device, key);
306 if (ref != NULL && CFGetTypeID(ref) == CFArrayGetTypeID()) {
307 return (CFArrayRef)ref;
308 } else {
309 return NULL;
310 }
311}
312
313static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key)
314{
315 CFTypeRef ref;
316 int32_t value = 0;
317
318 ref = IOHIDDeviceGetProperty(device, key);
319 if (ref) {
320 if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
321 CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value);
322 return value;
323 }
324 }
325 return 0;
326}
327
328static bool try_get_int_property(IOHIDDeviceRef device, CFStringRef key, int32_t *out_val)
329{
330 bool result = false;
331 CFTypeRef ref;
332
333 ref = IOHIDDeviceGetProperty(device, key);
334 if (ref) {
335 if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
336 result = CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, out_val);
337 }
338 }
339 return result;
340}
341
342static bool try_get_ioregistry_int_property(io_service_t service, CFStringRef property, int32_t *out_val)
343{
344 bool result = false;
345 CFTypeRef ref = IORegistryEntryCreateCFProperty(service, property, kCFAllocatorDefault, 0);
346
347 if (ref) {
348 if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
349 result = CFNumberGetValue(ref, kCFNumberSInt32Type, out_val);
350 }
351
352 CFRelease(ref);
353 }
354
355 return result;
356}
357
358static CFArrayRef get_usage_pairs(IOHIDDeviceRef device)
359{
360 return get_array_property(device, CFSTR(kIOHIDDeviceUsagePairsKey));
361}
362
363static unsigned short get_vendor_id(IOHIDDeviceRef device)
364{
365 return get_int_property(device, CFSTR(kIOHIDVendorIDKey));
366}
367
368static unsigned short get_product_id(IOHIDDeviceRef device)
369{
370 return get_int_property(device, CFSTR(kIOHIDProductIDKey));
371}
372
373static int32_t get_max_report_length(IOHIDDeviceRef device)
374{
375 return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));
376}
377
378static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len)
379{
380 CFStringRef str;
381
382 if (!len)
383 return 0;
384
385 str = (CFStringRef) IOHIDDeviceGetProperty(device, prop);
386
387 buf[0] = 0;
388
389 if (str && CFGetTypeID(str) == CFStringGetTypeID()) {
390 CFIndex str_len = CFStringGetLength(str);
391 CFRange range;
392 CFIndex used_buf_len;
393 CFIndex chars_copied;
394
395 len --;
396
397 range.location = 0;
398 range.length = ((size_t) str_len > len)? len: (size_t) str_len;
399 chars_copied = CFStringGetBytes(str,
400 range,
401 kCFStringEncodingUTF32LE,
402 (char) '?',
403 FALSE,
404 (UInt8*)buf,
405 len * sizeof(wchar_t),
406 &used_buf_len);
407
408 if (chars_copied <= 0)
409 buf[0] = 0;
410 else
411 buf[chars_copied] = 0;
412
413 return 0;
414 }
415 else
416 return -1;
417
418}
419
420static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len)
421{
422 return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len);
423}
424
425static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
426{
427 return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len);
428}
429
430static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
431{
432 return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len);
433}
434
435
436/* Implementation of wcsdup() for Mac. */
437static wchar_t *dup_wcs(const wchar_t *s)
438{
439 size_t len = wcslen(s);
440 wchar_t *ret = (wchar_t*) malloc((len+1)*sizeof(wchar_t));
441 wcscpy(ret, s);
442
443 return ret;
444}
445
446/* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */
447static int init_hid_manager(void)
448{
449 /* Initialize all the HID Manager Objects */
450 hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
451 if (hid_mgr) {
452 IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
453 IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
454 return 0;
455 }
456
457 register_global_error("Failed to create IOHIDManager");
458 return -1;
459}
460
461HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void)
462{
463 return &api_version;
464}
465
466HID_API_EXPORT const char* HID_API_CALL hid_version_str(void)
467{
468 return HID_API_VERSION_STR;
469}
470
471/* Initialize the IOHIDManager if necessary. This is the public function, and
472 it is safe to call this function repeatedly. Return 0 for success and -1
473 for failure. */
474int HID_API_EXPORT hid_init(void)
475{
476 register_global_error(NULL);
477
478 if (!hid_mgr) {
479 is_macos_10_10_or_greater = (kCFCoreFoundationVersionNumber >= 1151.16); /* kCFCoreFoundationVersionNumber10_10 */
480 hid_darwin_set_open_exclusive(1); /* Backward compatibility */
481 return init_hid_manager();
482 }
483
484 /* Already initialized. */
485 return 0;
486}
487
488int HID_API_EXPORT hid_exit(void)
489{
490 if (hid_mgr) {
491 /* Close the HID manager. */
492 IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone);
493 CFRelease(hid_mgr);
494 hid_mgr = NULL;
495 }
496
497 /* Free global error message */
498 register_global_error(NULL);
499
500 return 0;
501}
502
503static void process_pending_events(void) {
504 SInt32 res;
505 do {
506 res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE);
507 } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut);
508}
509
510static int read_usb_interface_from_hid_service_parent(io_service_t hid_service)
511{
512 int32_t result = -1;
513 bool success = false;
514 io_registry_entry_t current = IO_OBJECT_NULL;
515 kern_return_t res;
516 int parent_number = 0;
517
518 res = IORegistryEntryGetParentEntry(hid_service, kIOServicePlane, &current);
519 while (KERN_SUCCESS == res
520 /* Only search up to 3 parent entries.
521 * With the default driver - the parent-of-interest supposed to be the first one,
522 * but lets assume some custom drivers or so, with deeper tree. */
523 && parent_number < 3) {
524 io_registry_entry_t parent = IO_OBJECT_NULL;
525 int32_t interface_number = -1;
526 parent_number++;
527
528 success = try_get_ioregistry_int_property(current, CFSTR(kUSBInterfaceNumber), &interface_number);
529 if (success) {
530 result = interface_number;
531 break;
532 }
533
534 res = IORegistryEntryGetParentEntry(current, kIOServicePlane, &parent);
535 if (parent) {
536 IOObjectRelease(current);
537 current = parent;
538 }
539
540 }
541
542 if (current) {
543 IOObjectRelease(current);
544 current = IO_OBJECT_NULL;
545 }
546
547 return result;
548}
549
550#ifdef HIDAPI_IGNORE_DEVICE
551static hid_bus_type get_bus_type(IOHIDDeviceRef dev)
552{
553 hid_bus_type bus_type = HID_API_BUS_UNKNOWN;
554
555 CFTypeRef transport_prop = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDTransportKey));
556
557 if (transport_prop != NULL && CFGetTypeID(transport_prop) == CFStringGetTypeID()) {
558 if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportUSBValue), 0) == kCFCompareEqualTo) {
559 bus_type = HID_API_BUS_USB;
560 } else if (CFStringHasPrefix((CFStringRef)transport_prop, CFSTR(kIOHIDTransportBluetoothValue))) {
561 bus_type = HID_API_BUS_BLUETOOTH;
562 } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportI2CValue), 0) == kCFCompareEqualTo) {
563 bus_type = HID_API_BUS_I2C;
564 } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportSPIValue), 0) == kCFCompareEqualTo) {
565 bus_type = HID_API_BUS_SPI;
566 }
567 }
568 return bus_type;
569}
570#endif /* HIDAPI_IGNORE_DEVICE */
571
572static struct hid_device_info *create_device_info_with_usage(IOHIDDeviceRef dev, int32_t usage_page, int32_t usage)
573{
574 unsigned short dev_vid;
575 unsigned short dev_pid;
576 unsigned short dev_version;
577 int BUF_LEN = 256;
578 wchar_t buf[BUF_LEN];
579 CFTypeRef transport_prop;
580
581 struct hid_device_info *cur_dev;
582 io_service_t hid_service;
583 kern_return_t res;
584 uint64_t entry_id = 0;
585
586 if (dev == NULL) {
587 return NULL;
588 }
589
590 cur_dev = (struct hid_device_info *)calloc(1, sizeof(struct hid_device_info));
591 if (cur_dev == NULL) {
592 return NULL;
593 }
594
595 dev_vid = get_vendor_id(dev);
596 dev_pid = get_product_id(dev);
597 dev_version = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));
598
599#ifdef HIDAPI_IGNORE_DEVICE
600 /* See if there are any devices we should skip in enumeration */
601 if (HIDAPI_IGNORE_DEVICE(get_bus_type(dev), dev_vid, dev_pid, usage_page, usage, false, false)) {
602 free(cur_dev);
603 return NULL;
604 }
605#endif
606
607#ifdef HIDAPI_USING_SDL_RUNTIME
608 if (SDL_IsJoystickSteamVirtualGamepad(dev_vid, dev_pid, dev_version)) {
609 if (IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDVirtualHIDevice)) != kCFBooleanTrue) {
610 /* This is a real Xbox 360 controller, adjust the version so it's not detected as a Steam virtual gamepad */
611 dev_version = 1;
612 }
613 }
614#endif
615
616 cur_dev->usage_page = usage_page;
617 cur_dev->usage = usage;
618
619 /* Fill out the record */
620 cur_dev->next = NULL;
621
622 /* Fill in the path (as a unique ID of the service entry) */
623 cur_dev->path = NULL;
624 hid_service = IOHIDDeviceGetService(dev);
625 if (hid_service != MACH_PORT_NULL) {
626 res = IORegistryEntryGetRegistryEntryID(hid_service, &entry_id);
627 }
628 else {
629 res = KERN_INVALID_ARGUMENT;
630 }
631
632 if (res == KERN_SUCCESS) {
633 /* max value of entry_id(uint64_t) is 18446744073709551615 which is 20 characters long,
634 so for (max) "path" string 'DevSrvsID:18446744073709551615' we would need
635 9+1+20+1=31 bytes buffer, but allocate 32 for simple alignment */
636 const size_t path_len = 32;
637 cur_dev->path = calloc(1, path_len);
638 if (cur_dev->path != NULL) {
639 snprintf(cur_dev->path, path_len, "DevSrvsID:%llu", entry_id);
640 }
641 }
642
643 if (cur_dev->path == NULL) {
644 /* for whatever reason, trying to keep it a non-NULL string */
645 cur_dev->path = strdup("");
646 }
647
648 /* Serial Number */
649 get_serial_number(dev, buf, BUF_LEN);
650 cur_dev->serial_number = dup_wcs(buf);
651
652 /* Manufacturer and Product strings */
653 get_manufacturer_string(dev, buf, BUF_LEN);
654 cur_dev->manufacturer_string = dup_wcs(buf);
655 get_product_string(dev, buf, BUF_LEN);
656 cur_dev->product_string = dup_wcs(buf);
657
658 /* VID/PID */
659 cur_dev->vendor_id = dev_vid;
660 cur_dev->product_id = dev_pid;
661
662 /* Release Number */
663 cur_dev->release_number = dev_version;
664
665 /* Interface Number.
666 * We can only retrieve the interface number for USB HID devices.
667 * See below */
668 cur_dev->interface_number = -1;
669
670 /* Bus Type */
671 transport_prop = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDTransportKey));
672
673 if (transport_prop != NULL && CFGetTypeID(transport_prop) == CFStringGetTypeID()) {
674 if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportUSBValue), 0) == kCFCompareEqualTo) {
675 int32_t interface_number = -1;
676 cur_dev->bus_type = HID_API_BUS_USB;
677
678 /* A IOHIDDeviceRef used to have this simple property,
679 * until macOS 13.3 - we will try to use it. */
680 if (try_get_int_property(dev, CFSTR(kUSBInterfaceNumber), &interface_number)) {
681 cur_dev->interface_number = interface_number;
682 } else {
683 /* Otherwise fallback to io_service_t property.
684 * (of one of the parent services). */
685 cur_dev->interface_number = read_usb_interface_from_hid_service_parent(hid_service);
686
687 /* If the above doesn't work -
688 * no (known) fallback exists at this point. */
689 }
690
691 /* Match "Bluetooth", "BluetoothLowEnergy" and "Bluetooth Low Energy" strings */
692 } else if (CFStringHasPrefix((CFStringRef)transport_prop, CFSTR(kIOHIDTransportBluetoothValue))) {
693 cur_dev->bus_type = HID_API_BUS_BLUETOOTH;
694 } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportI2CValue), 0) == kCFCompareEqualTo) {
695 cur_dev->bus_type = HID_API_BUS_I2C;
696 } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportSPIValue), 0) == kCFCompareEqualTo) {
697 cur_dev->bus_type = HID_API_BUS_SPI;
698 }
699 }
700
701 return cur_dev;
702}
703
704static struct hid_device_info *create_device_info(IOHIDDeviceRef device)
705{
706 const int32_t primary_usage_page = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey));
707 const int32_t primary_usage = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey));
708
709 /* Primary should always be first, to match previous behavior. */
710 struct hid_device_info *root = create_device_info_with_usage(device, primary_usage_page, primary_usage);
711 struct hid_device_info *cur = root;
712
713 CFArrayRef usage_pairs = get_usage_pairs(device);
714
715 if (usage_pairs != NULL) {
716 struct hid_device_info *next = NULL;
717 for (CFIndex i = 0; i < CFArrayGetCount(usage_pairs); i++) {
718 CFTypeRef dict = CFArrayGetValueAtIndex(usage_pairs, i);
719 if (CFGetTypeID(dict) != CFDictionaryGetTypeID()) {
720 continue;
721 }
722
723 CFTypeRef usage_page_ref, usage_ref;
724 int32_t usage_page, usage;
725
726 if (!CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsagePageKey), &usage_page_ref) ||
727 !CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsageKey), &usage_ref) ||
728 CFGetTypeID(usage_page_ref) != CFNumberGetTypeID() ||
729 CFGetTypeID(usage_ref) != CFNumberGetTypeID() ||
730 !CFNumberGetValue((CFNumberRef)usage_page_ref, kCFNumberSInt32Type, &usage_page) ||
731 !CFNumberGetValue((CFNumberRef)usage_ref, kCFNumberSInt32Type, &usage)) {
732 continue;
733 }
734 if (usage_page == primary_usage_page && usage == primary_usage)
735 continue; /* Already added. */
736
737 next = create_device_info_with_usage(device, usage_page, usage);
738 if (cur) {
739 if (next != NULL) {
740 cur->next = next;
741 cur = next;
742 }
743 } else {
744 root = cur = next;
745 }
746 }
747 }
748
749 return root;
750}
751
752struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
753{
754 struct hid_device_info *root = NULL; /* return object */
755 struct hid_device_info *cur_dev = NULL;
756 CFIndex num_devices;
757 int i;
758
759 /* Set up the HID Manager if it hasn't been done */
760 if (hid_init() < 0) {
761 return NULL;
762 }
763 /* register_global_error: global error is set/reset by hid_init */
764
765 /* give the IOHIDManager a chance to update itself */
766 process_pending_events();
767
768 /* Get a list of the Devices */
769 CFMutableDictionaryRef matching = NULL;
770 if (vendor_id != 0 || product_id != 0) {
771 matching = CFDictionaryCreateMutable(kCFAllocatorDefault, kIOHIDOptionsTypeNone, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
772
773 if (matching && vendor_id != 0) {
774 CFNumberRef v = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &vendor_id);
775 CFDictionarySetValue(matching, CFSTR(kIOHIDVendorIDKey), v);
776 CFRelease(v);
777 }
778
779 if (matching && product_id != 0) {
780 CFNumberRef p = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &product_id);
781 CFDictionarySetValue(matching, CFSTR(kIOHIDProductIDKey), p);
782 CFRelease(p);
783 }
784 }
785 IOHIDManagerSetDeviceMatching(hid_mgr, matching);
786 if (matching != NULL) {
787 CFRelease(matching);
788 }
789
790 CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
791
792 IOHIDDeviceRef *device_array = NULL;
793
794 if (device_set != NULL) {
795 /* Convert the list into a C array so we can iterate easily. */
796 num_devices = CFSetGetCount(device_set);
797 device_array = (IOHIDDeviceRef*) calloc(num_devices, sizeof(IOHIDDeviceRef));
798 CFSetGetValues(device_set, (const void **) device_array);
799 } else {
800 num_devices = 0;
801 }
802
803 /* Iterate over each device, making an entry for it. */
804 for (i = 0; i < num_devices; i++) {
805
806 IOHIDDeviceRef dev = device_array[i];
807 if (!dev) {
808 continue;
809 }
810
811 struct hid_device_info *tmp = create_device_info(dev);
812 if (tmp == NULL) {
813 continue;
814 }
815
816 if (cur_dev) {
817 cur_dev->next = tmp;
818 }
819 else {
820 root = tmp;
821 }
822 cur_dev = tmp;
823
824 /* move the pointer to the tail of returned list */
825 while (cur_dev->next != NULL) {
826 cur_dev = cur_dev->next;
827 }
828 }
829
830 free(device_array);
831 if (device_set != NULL)
832 CFRelease(device_set);
833
834 if (root == NULL) {
835 if (vendor_id == 0 && product_id == 0) {
836 register_global_error("No HID devices found in the system.");
837 } else {
838 register_global_error("No HID devices with requested VID/PID found in the system.");
839 }
840 }
841
842 return root;
843}
844
845void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
846{
847 /* This function is identical to the Linux version. Platform independent. */
848 struct hid_device_info *d = devs;
849 while (d) {
850 struct hid_device_info *next = d->next;
851 free(d->path);
852 free(d->serial_number);
853 free(d->manufacturer_string);
854 free(d->product_string);
855 free(d);
856 d = next;
857 }
858}
859
860hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
861{
862 /* This function is identical to the Linux version. Platform independent. */
863
864 struct hid_device_info *devs, *cur_dev;
865 const char *path_to_open = NULL;
866 hid_device * handle = NULL;
867
868 /* register_global_error: global error is reset by hid_enumerate/hid_init */
869 devs = hid_enumerate(vendor_id, product_id);
870 if (devs == NULL) {
871 /* register_global_error: global error is already set by hid_enumerate */
872 return NULL;
873 }
874
875 cur_dev = devs;
876 while (cur_dev) {
877 if (cur_dev->vendor_id == vendor_id &&
878 cur_dev->product_id == product_id) {
879 if (serial_number) {
880 if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
881 path_to_open = cur_dev->path;
882 break;
883 }
884 }
885 else {
886 path_to_open = cur_dev->path;
887 break;
888 }
889 }
890 cur_dev = cur_dev->next;
891 }
892
893 if (path_to_open) {
894 handle = hid_open_path(path_to_open);
895 } else {
896 register_global_error("Device with requested VID/PID/(SerialNumber) not found");
897 }
898
899 hid_free_enumeration(devs);
900
901 return handle;
902}
903
904static void hid_device_removal_callback(void *context, IOReturn result,
905 void *sender)
906{
907 (void) result;
908 (void) sender;
909
910 /* Stop the Run Loop for this device. */
911 hid_device *d = (hid_device*) context;
912
913 d->disconnected = 1;
914 CFRunLoopStop(d->run_loop);
915}
916
917/* The Run Loop calls this function for each input report received.
918 This function puts the data into a linked list to be picked up by
919 hid_read(). */
920static void hid_report_callback(void *context, IOReturn result, void *sender,
921 IOHIDReportType report_type, uint32_t report_id,
922 uint8_t *report, CFIndex report_length)
923{
924 (void) result;
925 (void) sender;
926 (void) report_type;
927 (void) report_id;
928
929 struct input_report *rpt;
930 hid_device *dev = (hid_device*) context;
931
932 /* Make a new Input Report object */
933 rpt = (struct input_report*) calloc(1, sizeof(struct input_report));
934 rpt->data = (uint8_t*) calloc(1, report_length);
935 memcpy(rpt->data, report, report_length);
936 rpt->len = report_length;
937 rpt->next = NULL;
938
939 /* Lock this section */
940 pthread_mutex_lock(&dev->mutex);
941
942 /* Attach the new report object to the end of the list. */
943 if (dev->input_reports == NULL) {
944 /* The list is empty. Put it at the root. */
945 dev->input_reports = rpt;
946 }
947 else {
948 /* Find the end of the list and attach. */
949 struct input_report *cur = dev->input_reports;
950 int num_queued = 0;
951 while (cur->next != NULL) {
952 cur = cur->next;
953 num_queued++;
954 }
955 cur->next = rpt;
956
957 /* Pop one off if we've reached 30 in the queue. This
958 way we don't grow forever if the user never reads
959 anything from the device. */
960 if (num_queued > 30) {
961 return_data(dev, NULL, 0);
962 }
963 }
964
965 /* Signal a waiting thread that there is data. */
966 pthread_cond_signal(&dev->condition);
967
968 /* Unlock */
969 pthread_mutex_unlock(&dev->mutex);
970
971}
972
973/* This gets called when the read_thread's run loop gets signaled by
974 hid_close(), and serves to stop the read_thread's run loop. */
975static void perform_signal_callback(void *context)
976{
977 hid_device *dev = (hid_device*) context;
978 CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/
979}
980
981static void *read_thread(void *param)
982{
983 hid_device *dev = (hid_device*) param;
984 SInt32 code;
985
986 /* Move the device's run loop to this thread. */
987 IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode);
988
989 /* Create the RunLoopSource which is used to signal the
990 event loop to stop when hid_close() is called. */
991 CFRunLoopSourceContext ctx;
992 memset(&ctx, 0, sizeof(ctx));
993 ctx.version = 0;
994 ctx.info = dev;
995 ctx.perform = &perform_signal_callback;
996 dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx);
997 CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode);
998
999 /* Store off the Run Loop so it can be stopped from hid_close()
1000 and on device disconnection. */
1001 dev->run_loop = CFRunLoopGetCurrent();
1002
1003 /* Notify the main thread that the read thread is up and running. */
1004 pthread_barrier_wait(&dev->barrier);
1005
1006 /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input
1007 reports into the hid_report_callback(). */
1008 while (!dev->shutdown_thread && !dev->disconnected) {
1009 code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE);
1010 /* Return if the device has been disconnected */
1011 if (code == kCFRunLoopRunFinished || code == kCFRunLoopRunStopped) {
1012 dev->disconnected = 1;
1013 break;
1014 }
1015
1016
1017 /* Break if The Run Loop returns Finished or Stopped. */
1018 if (code != kCFRunLoopRunTimedOut &&
1019 code != kCFRunLoopRunHandledSource) {
1020 /* There was some kind of error. Setting
1021 shutdown seems to make sense, but
1022 there may be something else more appropriate */
1023 dev->shutdown_thread = 1;
1024 break;
1025 }
1026 }
1027
1028 /* Now that the read thread is stopping, Wake any threads which are
1029 waiting on data (in hid_read_timeout()). Do this under a mutex to
1030 make sure that a thread which is about to go to sleep waiting on
1031 the condition actually will go to sleep before the condition is
1032 signaled. */
1033 pthread_mutex_lock(&dev->mutex);
1034 pthread_cond_broadcast(&dev->condition);
1035 pthread_mutex_unlock(&dev->mutex);
1036
1037 /* Wait here until hid_close() is called and makes it past
1038 the call to CFRunLoopWakeUp(). This thread still needs to
1039 be valid when that function is called on the other thread. */
1040 pthread_barrier_wait(&dev->shutdown_barrier);
1041
1042 return NULL;
1043}
1044
1045/* \p path must be one of:
1046 - in format 'DevSrvsID:<RegistryEntryID>' (as returned by hid_enumerate);
1047 - a valid path to an IOHIDDevice in the IOService plane (as returned by IORegistryEntryGetPath,
1048 e.g.: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver");
1049 Second format is for compatibility with paths accepted by older versions of HIDAPI.
1050*/
1051static io_registry_entry_t hid_open_service_registry_from_path(const char *path)
1052{
1053 if (path == NULL)
1054 return MACH_PORT_NULL;
1055
1056 /* Get the IORegistry entry for the given path */
1057 if (strncmp("DevSrvsID:", path, 10) == 0) {
1058 char *endptr;
1059 uint64_t entry_id = strtoull(path + 10, &endptr, 10);
1060 if (*endptr == '\0') {
1061 return IOServiceGetMatchingService((mach_port_t) 0, IORegistryEntryIDMatching(entry_id));
1062 }
1063 }
1064 else {
1065 /* Fallback to older format of the path */
1066 return IORegistryEntryFromPath((mach_port_t) 0, path);
1067 }
1068
1069 return MACH_PORT_NULL;
1070}
1071
1072hid_device * HID_API_EXPORT hid_open_path(const char *path)
1073{
1074 hid_device *dev = NULL;
1075 io_registry_entry_t entry = MACH_PORT_NULL;
1076 IOReturn ret = kIOReturnInvalid;
1077 char str[32];
1078
1079 /* Set up the HID Manager if it hasn't been done */
1080 if (hid_init() < 0) {
1081 return NULL;
1082 }
1083 /* register_global_error: global error is set/reset by hid_init */
1084
1085 dev = new_hid_device();
1086 if (!dev) {
1087 register_global_error("Couldn't allocate memory");
1088 return NULL;
1089 }
1090
1091 /* Get the IORegistry entry for the given path */
1092 entry = hid_open_service_registry_from_path(path);
1093 if (entry == MACH_PORT_NULL) {
1094 /* Path wasn't valid (maybe device was removed?) */
1095 register_global_error("hid_open_path: device mach entry not found with the given path");
1096 goto return_error;
1097 }
1098
1099 /* Create an IOHIDDevice for the entry */
1100 dev->device_handle = IOHIDDeviceCreate(kCFAllocatorDefault, entry);
1101 if (dev->device_handle == NULL) {
1102 /* Error creating the HID device */
1103 register_global_error("hid_open_path: failed to create IOHIDDevice from the mach entry");
1104 goto return_error;
1105 }
1106
1107 /* Open the IOHIDDevice */
1108 ret = IOHIDDeviceOpen(dev->device_handle, dev->open_options);
1109 if (ret != kIOReturnSuccess) {
1110 register_global_error_format("hid_open_path: failed to open IOHIDDevice from mach entry: (0x%08X) %s", ret, mach_error_string(ret));
1111 goto return_error;
1112 }
1113
1114 /* Create the buffers for receiving data */
1115 dev->max_input_report_len = (CFIndex) get_max_report_length(dev->device_handle);
1116 dev->input_report_buf = (uint8_t*) calloc(dev->max_input_report_len, sizeof(uint8_t));
1117
1118 /* Create the Run Loop Mode for this device.
1119 printing the reference seems to work. */
1120 snprintf(str, sizeof(str), "HIDAPI_%p", (void*) dev->device_handle);
1121 dev->run_loop_mode =
1122 CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);
1123
1124 /* Attach the device to a Run Loop */
1125 IOHIDDeviceRegisterInputReportCallback(
1126 dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
1127 &hid_report_callback, dev);
1128 IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev);
1129
1130 /* Start the read thread */
1131 pthread_create(&dev->thread, NULL, read_thread, dev);
1132
1133 /* Wait here for the read thread to be initialized. */
1134 pthread_barrier_wait(&dev->barrier);
1135
1136 IOObjectRelease(entry);
1137 return dev;
1138
1139return_error:
1140 if (dev->device_handle != NULL)
1141 CFRelease(dev->device_handle);
1142
1143 if (entry != MACH_PORT_NULL)
1144 IOObjectRelease(entry);
1145
1146 free_hid_device(dev);
1147 return NULL;
1148}
1149
1150static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length)
1151{
1152 const char *pass_through_magic = "MAGIC0";
1153 size_t pass_through_magic_length = strlen(pass_through_magic);
1154 const unsigned char *data_to_send = data;
1155 CFIndex length_to_send = length;
1156 IOReturn res;
1157 unsigned char report_id;
1158
1159 register_device_error(dev, NULL);
1160
1161 if (!data || (length == 0)) {
1162 register_device_error(dev, strerror(EINVAL));
1163 return -1;
1164 }
1165
1166 report_id = data[0];
1167
1168 if (report_id == 0x0) {
1169 /* Not using numbered Reports.
1170 Don't send the report number. */
1171 data_to_send = data+1;
1172 length_to_send = length-1;
1173 }
1174 else if (length > 6 && memcmp(data, pass_through_magic, pass_through_magic_length) == 0) {
1175 report_id = data[pass_through_magic_length];
1176 data_to_send = data+pass_through_magic_length;
1177 length_to_send = length-pass_through_magic_length;
1178 }
1179
1180 /* Avoid crash if the device has been unplugged. */
1181 if (dev->disconnected) {
1182 register_device_error(dev, "Device is disconnected");
1183 return -1;
1184 }
1185
1186 res = IOHIDDeviceSetReport(dev->device_handle,
1187 type,
1188 report_id,
1189 data_to_send, length_to_send);
1190
1191 if (res != kIOReturnSuccess) {
1192 register_device_error_format(dev, "IOHIDDeviceSetReport failed: (0x%08X) %s", res, mach_error_string(res));
1193 return -1;
1194 }
1195
1196 return (int) length;
1197}
1198
1199static int get_report(hid_device *dev, IOHIDReportType type, unsigned char *data, size_t length)
1200{
1201 unsigned char *report = data;
1202 CFIndex report_length = length;
1203 IOReturn res = kIOReturnSuccess;
1204 const unsigned char report_id = data[0];
1205
1206 register_device_error(dev, NULL);
1207
1208 if (report_id == 0x0) {
1209 /* Not using numbered Reports.
1210 Don't send the report number. */
1211 report = data+1;
1212 report_length = length-1;
1213 }
1214
1215 /* Avoid crash if the device has been unplugged. */
1216 if (dev->disconnected) {
1217 register_device_error(dev, "Device is disconnected");
1218 return -1;
1219 }
1220
1221 res = IOHIDDeviceGetReport(dev->device_handle,
1222 type,
1223 report_id,
1224 report, &report_length);
1225
1226 if (res != kIOReturnSuccess) {
1227 register_device_error_format(dev, "IOHIDDeviceGetReport failed: (0x%08X) %s", res, mach_error_string(res));
1228 return -1;
1229 }
1230
1231 if (report_id == 0x0) { /* 0 report number still present at the beginning */
1232 report_length++;
1233 }
1234
1235 return (int) report_length;
1236}
1237
1238int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
1239{
1240 return set_report(dev, kIOHIDReportTypeOutput, data, length);
1241}
1242
1243/* Helper function, so that this isn't duplicated in hid_read(). */
1244static int return_data(hid_device *dev, unsigned char *data, size_t length)
1245{
1246 /* Copy the data out of the linked list item (rpt) into the
1247 return buffer (data), and delete the liked list item. */
1248 struct input_report *rpt = dev->input_reports;
1249 size_t len = (length < rpt->len)? length: rpt->len;
1250 if (data != NULL) {
1251 memcpy(data, rpt->data, len);
1252 }
1253 dev->input_reports = rpt->next;
1254 free(rpt->data);
1255 free(rpt);
1256 return (int) len;
1257}
1258
1259static int cond_wait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex)
1260{
1261 while (!dev->input_reports) {
1262 int res = pthread_cond_wait(cond, mutex);
1263 if (res != 0)
1264 return res;
1265
1266 /* A res of 0 means we may have been signaled or it may
1267 be a spurious wakeup. Check to see that there's actually
1268 data in the queue before returning, and if not, go back
1269 to sleep. See the pthread_cond_timedwait() man page for
1270 details. */
1271
1272 if (dev->shutdown_thread || dev->disconnected) {
1273 return -1;
1274 }
1275 }
1276
1277 return 0;
1278}
1279
1280static int cond_timedwait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
1281{
1282 while (!dev->input_reports) {
1283 int res = pthread_cond_timedwait(cond, mutex, abstime);
1284 if (res != 0)
1285 return res;
1286
1287 /* A res of 0 means we may have been signaled or it may
1288 be a spurious wakeup. Check to see that there's actually
1289 data in the queue before returning, and if not, go back
1290 to sleep. See the pthread_cond_timedwait() man page for
1291 details. */
1292
1293 if (dev->shutdown_thread || dev->disconnected) {
1294 return -1;
1295 }
1296 }
1297
1298 return 0;
1299
1300}
1301
1302int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
1303{
1304 int bytes_read = -1;
1305
1306 /* Lock the access to the report list. */
1307 pthread_mutex_lock(&dev->mutex);
1308
1309 /* There's an input report queued up. Return it. */
1310 if (dev->input_reports) {
1311 /* Return the first one */
1312 bytes_read = return_data(dev, data, length);
1313 goto ret;
1314 }
1315
1316 /* Return if the device has been disconnected. */
1317 if (dev->disconnected) {
1318 bytes_read = -1;
1319 register_device_error(dev, "hid_read_timeout: device disconnected");
1320 goto ret;
1321 }
1322
1323 if (dev->shutdown_thread) {
1324 /* This means the device has been closed (or there
1325 has been an error. An error code of -1 should
1326 be returned. */
1327 bytes_read = -1;
1328 register_device_error(dev, "hid_read_timeout: thread shutdown");
1329 goto ret;
1330 }
1331
1332 /* There is no data. Go to sleep and wait for data. */
1333
1334 if (milliseconds == -1) {
1335 /* Blocking */
1336 int res;
1337 res = cond_wait(dev, &dev->condition, &dev->mutex);
1338 if (res == 0)
1339 bytes_read = return_data(dev, data, length);
1340 else {
1341 /* There was an error, or a device disconnection. */
1342 register_device_error(dev, "hid_read_timeout: error waiting for more data");
1343 bytes_read = -1;
1344 }
1345 }
1346 else if (milliseconds > 0) {
1347 /* Non-blocking, but called with timeout. */
1348 int res;
1349 struct timespec ts;
1350 struct timeval tv;
1351 gettimeofday(&tv, NULL);
1352 TIMEVAL_TO_TIMESPEC(&tv, &ts);
1353 ts.tv_sec += milliseconds / 1000;
1354 ts.tv_nsec += (milliseconds % 1000) * 1000000;
1355 if (ts.tv_nsec >= 1000000000L) {
1356 ts.tv_sec++;
1357 ts.tv_nsec -= 1000000000L;
1358 }
1359
1360 res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts);
1361 if (res == 0) {
1362 bytes_read = return_data(dev, data, length);
1363 } else if (res == ETIMEDOUT) {
1364 bytes_read = 0;
1365 } else {
1366 register_device_error(dev, "hid_read_timeout: error waiting for more data");
1367 bytes_read = -1;
1368 }
1369 }
1370 else {
1371 /* Purely non-blocking */
1372 bytes_read = 0;
1373 }
1374
1375ret:
1376 /* Unlock */
1377 pthread_mutex_unlock(&dev->mutex);
1378 return bytes_read;
1379}
1380
1381int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
1382{
1383 return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
1384}
1385
1386int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
1387{
1388 /* All Nonblocking operation is handled by the library. */
1389 dev->blocking = !nonblock;
1390
1391 return 0;
1392}
1393
1394int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
1395{
1396 return set_report(dev, kIOHIDReportTypeFeature, data, length);
1397}
1398
1399int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
1400{
1401 return get_report(dev, kIOHIDReportTypeFeature, data, length);
1402}
1403
1404int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length)
1405{
1406 return get_report(dev, kIOHIDReportTypeInput, data, length);
1407}
1408
1409void HID_API_EXPORT hid_close(hid_device *dev)
1410{
1411 if (!dev)
1412 return;
1413
1414 /* Disconnect the report callback before close.
1415 See comment below.
1416 */
1417 if (is_macos_10_10_or_greater || !dev->disconnected) {
1418 IOHIDDeviceRegisterInputReportCallback(
1419 dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
1420 NULL, dev);
1421 IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev);
1422 IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode);
1423 IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
1424 }
1425
1426 /* Cause read_thread() to stop. */
1427 dev->shutdown_thread = 1;
1428
1429 /* Wake up the run thread's event loop so that the thread can exit. */
1430 CFRunLoopSourceSignal(dev->source);
1431 CFRunLoopWakeUp(dev->run_loop);
1432
1433 /* Notify the read thread that it can shut down now. */
1434 pthread_barrier_wait(&dev->shutdown_barrier);
1435
1436 /* Wait for read_thread() to end. */
1437 pthread_join(dev->thread, NULL);
1438
1439 /* Close the OS handle to the device, but only if it's not
1440 been unplugged. If it's been unplugged, then calling
1441 IOHIDDeviceClose() will crash.
1442
1443 UPD: The crash part was true in/until some version of macOS.
1444 Starting with macOS 10.15, there is an opposite effect in some environments:
1445 crash happens if IOHIDDeviceClose() is not called.
1446 Not leaking a resource in all tested environments.
1447 */
1448 if (is_macos_10_10_or_greater || !dev->disconnected) {
1449 IOHIDDeviceClose(dev->device_handle, dev->open_options);
1450 }
1451
1452 /* Clear out the queue of received reports. */
1453 pthread_mutex_lock(&dev->mutex);
1454 while (dev->input_reports) {
1455 return_data(dev, NULL, 0);
1456 }
1457 pthread_mutex_unlock(&dev->mutex);
1458 CFRelease(dev->device_handle);
1459
1460 free_hid_device(dev);
1461}
1462
1463int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
1464{
1465 if (!string || !maxlen)
1466 {
1467 register_device_error(dev, "Zero buffer/length");
1468 return -1;
1469 }
1470
1471 struct hid_device_info *info = hid_get_device_info(dev);
1472 if (!info)
1473 {
1474 // hid_get_device_info will have set an error already
1475 return -1;
1476 }
1477
1478 wcsncpy(string, info->manufacturer_string, maxlen);
1479 string[maxlen - 1] = L'\0';
1480
1481 return 0;
1482}
1483
1484int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
1485{
1486 if (!string || !maxlen) {
1487 register_device_error(dev, "Zero buffer/length");
1488 return -1;
1489 }
1490
1491 struct hid_device_info *info = hid_get_device_info(dev);
1492 if (!info) {
1493 // hid_get_device_info will have set an error already
1494 return -1;
1495 }
1496
1497 wcsncpy(string, info->product_string, maxlen);
1498 string[maxlen - 1] = L'\0';
1499
1500 return 0;
1501}
1502
1503int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
1504{
1505 if (!string || !maxlen) {
1506 register_device_error(dev, "Zero buffer/length");
1507 return -1;
1508 }
1509
1510 struct hid_device_info *info = hid_get_device_info(dev);
1511 if (!info) {
1512 // hid_get_device_info will have set an error already
1513 return -1;
1514 }
1515
1516 wcsncpy(string, info->serial_number, maxlen);
1517 string[maxlen - 1] = L'\0';
1518
1519 return 0;
1520}
1521
1522HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) {
1523 if (!dev->device_info) {
1524 dev->device_info = create_device_info(dev->device_handle);
1525 if (!dev->device_info) {
1526 register_device_error(dev, "Failed to create hid_device_info");
1527 }
1528 }
1529
1530 return dev->device_info;
1531}
1532
1533int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
1534{
1535 (void) dev;
1536 (void) string_index;
1537 (void) string;
1538 (void) maxlen;
1539
1540 register_device_error(dev, "hid_get_indexed_string: not available on this platform");
1541 return -1;
1542}
1543
1544int HID_API_EXPORT_CALL hid_darwin_get_location_id(hid_device *dev, uint32_t *location_id)
1545{
1546 int res = get_int_property(dev->device_handle, CFSTR(kIOHIDLocationIDKey));
1547 if (res != 0) {
1548 *location_id = (uint32_t) res;
1549 return 0;
1550 } else {
1551 register_device_error(dev, "Failed to get IOHIDLocationID property");
1552 return -1;
1553 }
1554}
1555
1556void HID_API_EXPORT_CALL hid_darwin_set_open_exclusive(int open_exclusive)
1557{
1558 device_open_options = (open_exclusive == 0) ? kIOHIDOptionsTypeNone : kIOHIDOptionsTypeSeizeDevice;
1559}
1560
1561int HID_API_EXPORT_CALL hid_darwin_get_open_exclusive(void)
1562{
1563 return (device_open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0;
1564}
1565
1566int HID_API_EXPORT_CALL hid_darwin_is_device_open_exclusive(hid_device *dev)
1567{
1568 if (!dev)
1569 return -1;
1570
1571 return (dev->open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0;
1572}
1573
1574int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size)
1575{
1576 CFTypeRef ref = IOHIDDeviceGetProperty(dev->device_handle, CFSTR(kIOHIDReportDescriptorKey));
1577 if (ref != NULL && CFGetTypeID(ref) == CFDataGetTypeID()) {
1578 CFDataRef report_descriptor = (CFDataRef) ref;
1579 const UInt8 *descriptor_buf = CFDataGetBytePtr(report_descriptor);
1580 CFIndex descriptor_buf_len = CFDataGetLength(report_descriptor);
1581 size_t copy_len = (size_t) descriptor_buf_len;
1582
1583 if (descriptor_buf == NULL || descriptor_buf_len < 0) {
1584 register_device_error(dev, "Zero buffer/length");
1585 return -1;
1586 }
1587
1588 if (buf_size < copy_len) {
1589 copy_len = buf_size;
1590 }
1591
1592 memcpy(buf, descriptor_buf, copy_len);
1593 return (int)copy_len;
1594 }
1595 else {
1596 register_device_error(dev, "Failed to get kIOHIDReportDescriptorKey property");
1597 return -1;
1598 }
1599}
1600
1601HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
1602{
1603 if (dev) {
1604 if (dev->last_error_str == NULL)
1605 return L"Success";
1606 return dev->last_error_str;
1607 }
1608
1609 if (last_global_error_str == NULL)
1610 return L"Success";
1611 return last_global_error_str;
1612}