dream_cheeky 0.2.0 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 45d34d83f54214f386a67acbbf34245978841873
4
+ data.tar.gz: d4a2ed114ec30aaf3f8fd667fb51ed0c524cf31f
5
+ SHA512:
6
+ metadata.gz: 856e649cdd1139659ad283edce818dfc9ebc0702036f4e7107caa1c05dbbf60e1291b7ef7581c8e31c0d7d91020181c26caef101a2090ecd5d3d43e97d0cdb8f
7
+ data.tar.gz: f2d9aa4fe34cd77aab8059845da917b3777cca98b0cd92c5eb959af683daa0a10ef6d85807a7c29e78d64445cb6f1bc6dd80c8b8eee1d7421af4a09c55c7e494
data/.gitignore ADDED
@@ -0,0 +1,27 @@
1
+ # Ignore bundler config
2
+ /.bundle
3
+
4
+ # Ignore all logfiles and tempfiles.
5
+ /log/*.log
6
+ /tmp
7
+
8
+ # Ignore other unneeded files.
9
+ doc/
10
+ *.swp
11
+ *~
12
+ .project
13
+ .DS_Store
14
+
15
+ # Ignore compilation products
16
+ Makefile
17
+ *.o
18
+ *.so
19
+ *.log
20
+ dream_cheeky*.gem
21
+ Gemfile.lock
22
+ hidapi.c
23
+ *.bundle
24
+
25
+ # Rbenv
26
+ .ruby-version
27
+ .rbenv*
data/README.md CHANGED
@@ -54,4 +54,24 @@ end
54
54
  ## Requirements
55
55
 
56
56
  1. A supported Dream Cheeky USB Device. Example: http://dreamcheeky.com/big-red-button
57
- 2. Mac OS X with Developer Tools installed. (Support for Linux and Windows is planned).
57
+
58
+ 2. Mac OS X with Developer Tools installed or Linux with libusb and udev installed.
59
+
60
+ 3. On Linux you may have to
61
+ [add a udev rule](http://reactivated.net/writing_udev_rules.html). To do that,
62
+ create a file named 99-dream_cheeky.rules with the following content:
63
+
64
+ SUBSYSTEM=="usb", ATTRS{idVendor}=="1d34", ATTRS{idProduct}=="000d", MODE="0666", GROUP="plugdev"
65
+
66
+ Then, copy the file to /etc/udev/rules.d/99-dream_cheeky.rules (you probably would
67
+ need root priviles to copy it).
68
+
69
+ ## Maintainers
70
+
71
+ * Derrick Spell (https://github.com/derrick)
72
+
73
+ ## Contributors
74
+
75
+ * Gustavo Armagno (http://github.com/gusaaaaa) added Linux support - many thanks!
76
+ * Matt Sephton (http://github.com/gingerbeardman) added the UsbFidget class.
77
+
data/Rakefile CHANGED
@@ -1,32 +1,35 @@
1
1
  require "bundler/gem_tasks"
2
2
  require 'rake/clean'
3
3
  require 'rspec/core/rake_task'
4
+ require 'rbconfig'
4
5
 
5
6
  NAME = 'dream_cheeky'
6
7
 
8
+ DL_EXTENSION = RbConfig::CONFIG['DLEXT']
9
+
7
10
  # rule to build the extension: this says
8
11
  # that the extension should be rebuilt
9
12
  # after any change to the files in ext
10
- file "lib/#{NAME}/#{NAME}.bundle" => Dir.glob("ext/#{NAME}/*{.rb,.c}") do
13
+ file "lib/#{NAME}/#{NAME}.#{DL_EXTENSION}" => Dir.glob("ext/#{NAME}/*{.rb,.c}") do
11
14
  Dir.chdir("ext/#{NAME}") do
12
15
  # this does essentially the same thing
13
16
  # as what RubyGems does
14
17
  ruby "extconf.rb"
15
18
  sh "make"
16
19
  end
17
- cp "ext/#{NAME}/#{NAME}.bundle", "lib/#{NAME}"
20
+ cp "ext/#{NAME}/#{NAME}.#{DL_EXTENSION}", "lib/#{NAME}"
18
21
  end
19
22
 
20
23
  # make the :test task depend on the shared
21
24
  # object, so it will be built automatically
22
25
  # before running the tests
23
- task :rspec => "lib/#{NAME}/#{NAME}.bundle"
26
+ task :rspec => "lib/#{NAME}/#{NAME}.#{DL_EXTENSION}"
24
27
 
25
28
  # use 'rake clean' and 'rake clobber' to
26
29
  # easily delete generated files
27
- CLEAN.include('ext/**/*{.o,.log,.bundle}')
30
+ CLEAN.include("ext/**/*{.o,.log,.#{DL_EXTENSION}")
28
31
  CLEAN.include('ext/**/Makefile')
29
- CLOBBER.include('lib/**/*.bundle')
32
+ CLOBBER.include("lib/**/*.#{DL_EXTENSION}")
30
33
 
31
34
  RSpec::Core::RakeTask.new(:rspec) do |spec|
32
35
  spec.pattern = 'spec/**/*_spec.rb'
data/dream_cheeky.gemspec CHANGED
@@ -1,6 +1,7 @@
1
1
  # -*- encoding: utf-8 -*-
2
2
  $:.push File.expand_path("../lib", __FILE__)
3
3
  require "dream_cheeky/version"
4
+ require 'rbconfig'
4
5
 
5
6
  Gem::Specification.new do |s|
6
7
  s.name = "dream_cheeky"
@@ -14,6 +15,7 @@ Gem::Specification.new do |s|
14
15
  s.rubyforge_project = "dream_cheeky"
15
16
 
16
17
  s.files = `git ls-files`.split("\n")
18
+
17
19
  s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
20
  s.extensions = ['ext/dream_cheeky/extconf.rb']
19
21
  s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
@@ -21,4 +23,5 @@ Gem::Specification.new do |s|
21
23
 
22
24
  # specify any dependencies here; for example:
23
25
  s.add_development_dependency "rspec"
26
+ s.add_dependency 'pkg-config'
24
27
  end
@@ -1,37 +1,55 @@
1
1
  require 'mkmf'
2
+ require 'rbconfig'
3
+ require 'fileutils'
2
4
 
3
- $CFLAGS << " " << "-ObjC"
4
-
5
- unless defined?(have_framework)
6
- def have_framework(fw, &b)
7
- checking_for fw do
8
- src = cpp_include("#{fw}/#{fw}.h") << "\n" "int main(void){return 0;}"
9
- if try_link(src, opt = "-ObjC -framework #{fw}", &b)
10
- $defs.push(format("-DHAVE_FRAMEWORK_%s", fw.tr_cpp))
11
- $LDFLAGS << " " << opt
12
- true
13
- else
14
- false
5
+ if RbConfig::CONFIG['host_os'] =~ /darwin/
6
+
7
+ $CFLAGS << " " << "-ObjC"
8
+
9
+ unless defined?(have_framework)
10
+ def have_framework(fw, &b)
11
+ checking_for fw do
12
+ src = cpp_include("#{fw}/#{fw}.h") << "\n" "int main(void){return 0;}"
13
+ if try_link(src, opt = "-ObjC -framework #{fw}", &b)
14
+ $defs.push(format("-DHAVE_FRAMEWORK_%s", fw.tr_cpp))
15
+ $LDFLAGS << " " << opt
16
+ true
17
+ else
18
+ false
19
+ end
15
20
  end
16
21
  end
17
22
  end
18
- end
23
+
24
+ if have_framework('CoreFoundation')
25
+ $LDFLAGS << " -ObjC -framework IOKit"
26
+ FileUtils.cp('hidapi.c.mac', 'hidapi.c')
27
+ create_makefile('dream_cheeky/dream_cheeky')
28
+ else
29
+ abort "Could not include required frameworks..."
30
+ end
31
+
32
+ else
19
33
 
20
- if have_framework('CoreFoundation')
34
+ require 'pkg-config'
21
35
 
22
- $LDFLAGS << " -ObjC -framework IOKit"
36
+ if PKGConfig::exist?('libusb-1.0')
37
+ $LIBS << ' ' << PKGConfig::libs('libusb-1.0')
38
+ $CFLAGS << ' ' << PKGConfig::cflags('libusb-1.0')
39
+ FileUtils.cp('hidapi.c.linux', 'hidapi.c')
40
+ create_makefile('dream_cheeky/dream_cheeky')
41
+ else
42
+ abort 'Could not find library libusb'
43
+ end
23
44
 
24
- create_makefile('dream_cheeky/dream_cheeky')
45
+ end
25
46
 
26
- # workaround for mkmf.rb in 1.9.2
27
- if RUBY_VERSION < "1.9.3"
28
- open("Makefile", "a") do |f|
29
- f.puts <<-EOS
47
+ # workaround for mkmf.rb in 1.9.2
48
+ if RUBY_VERSION < "1.9.3"
49
+ open("Makefile", "a") do |f|
50
+ f.puts <<-EOS
30
51
  .m.o:
31
- $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $<
32
- EOS
33
- end
52
+ $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $<
53
+ EOS
34
54
  end
35
- else
36
- abort "Could not include required frameworks..."
37
55
  end
@@ -0,0 +1,1425 @@
1
+ /*******************************************************
2
+ HIDAPI - Multi-Platform library for
3
+ communication with HID devices.
4
+
5
+ Alan Ott
6
+ Signal 11 Software
7
+
8
+ 8/22/2009
9
+ Linux Version - 6/2/2010
10
+ Libusb Version - 8/13/2010
11
+ FreeBSD Version - 11/1/2011
12
+
13
+ Copyright 2009, All Rights Reserved.
14
+
15
+ At the discretion of the user of this library,
16
+ this software may be licensed under the terms of the
17
+ GNU Public License v3, a BSD-Style license, or the
18
+ original HIDAPI license as outlined in the LICENSE.txt,
19
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
20
+ files located at the root of the source distribution.
21
+ These files may also be found in the public source
22
+ code repository located at:
23
+ http://github.com/signal11/hidapi .
24
+ ********************************************************/
25
+
26
+ #define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */
27
+
28
+ /* C */
29
+ #include <stdio.h>
30
+ #include <string.h>
31
+ #include <stdlib.h>
32
+ #include <ctype.h>
33
+ #include <locale.h>
34
+ #include <errno.h>
35
+
36
+ /* Unix */
37
+ #include <unistd.h>
38
+ #include <sys/types.h>
39
+ #include <sys/stat.h>
40
+ #include <sys/ioctl.h>
41
+ #include <sys/utsname.h>
42
+ #include <fcntl.h>
43
+ #include <pthread.h>
44
+ #include <wchar.h>
45
+
46
+ /* GNU / LibUSB */
47
+ #include "libusb.h"
48
+ #include "iconv.h"
49
+
50
+ #include "hidapi.h"
51
+
52
+ #ifdef __cplusplus
53
+ extern "C" {
54
+ #endif
55
+
56
+ #ifdef DEBUG_PRINTF
57
+ #define LOG(...) fprintf(stderr, __VA_ARGS__)
58
+ #else
59
+ #define LOG(...) do {} while (0)
60
+ #endif
61
+
62
+ #ifndef __FreeBSD__
63
+ #define DETACH_KERNEL_DRIVER
64
+ #endif
65
+
66
+ /* Uncomment to enable the retrieval of Usage and Usage Page in
67
+ hid_enumerate(). Warning, on platforms different from FreeBSD
68
+ this is very invasive as it requires the detach
69
+ and re-attach of the kernel driver. See comments inside hid_enumerate().
70
+ libusb HIDAPI programs are encouraged to use the interface number
71
+ instead to differentiate between interfaces on a composite HID device. */
72
+ /*#define INVASIVE_GET_USAGE*/
73
+
74
+ /* Linked List of input reports received from the device. */
75
+ struct input_report {
76
+ uint8_t *data;
77
+ size_t len;
78
+ struct input_report *next;
79
+ };
80
+
81
+
82
+ struct hid_device_ {
83
+ /* Handle to the actual device. */
84
+ libusb_device_handle *device_handle;
85
+
86
+ /* Endpoint information */
87
+ int input_endpoint;
88
+ int output_endpoint;
89
+ int input_ep_max_packet_size;
90
+
91
+ /* The interface number of the HID */
92
+ int interface;
93
+
94
+ /* Indexes of Strings */
95
+ int manufacturer_index;
96
+ int product_index;
97
+ int serial_index;
98
+
99
+ /* Whether blocking reads are used */
100
+ int blocking; /* boolean */
101
+
102
+ /* Read thread objects */
103
+ pthread_t thread;
104
+ pthread_mutex_t mutex; /* Protects input_reports */
105
+ pthread_cond_t condition;
106
+ pthread_barrier_t barrier; /* Ensures correct startup sequence */
107
+ int shutdown_thread;
108
+ struct libusb_transfer *transfer;
109
+
110
+ /* List of received input reports. */
111
+ struct input_report *input_reports;
112
+ };
113
+
114
+ static libusb_context *usb_context = NULL;
115
+
116
+ uint16_t get_usb_code_for_current_locale(void);
117
+ static int return_data(hid_device *dev, unsigned char *data, size_t length);
118
+
119
+ static hid_device *new_hid_device(void)
120
+ {
121
+ hid_device *dev = calloc(1, sizeof(hid_device));
122
+ dev->blocking = 1;
123
+
124
+ pthread_mutex_init(&dev->mutex, NULL);
125
+ pthread_cond_init(&dev->condition, NULL);
126
+ pthread_barrier_init(&dev->barrier, NULL, 2);
127
+
128
+ return dev;
129
+ }
130
+
131
+ static void free_hid_device(hid_device *dev)
132
+ {
133
+ /* Clean up the thread objects */
134
+ pthread_barrier_destroy(&dev->barrier);
135
+ pthread_cond_destroy(&dev->condition);
136
+ pthread_mutex_destroy(&dev->mutex);
137
+
138
+ /* Free the device itself */
139
+ free(dev);
140
+ }
141
+
142
+ #if 0
143
+ /*TODO: Implement this funciton on hidapi/libusb.. */
144
+ static void register_error(hid_device *device, const char *op)
145
+ {
146
+
147
+ }
148
+ #endif
149
+
150
+ #ifdef INVASIVE_GET_USAGE
151
+ /* Get bytes from a HID Report Descriptor.
152
+ Only call with a num_bytes of 0, 1, 2, or 4. */
153
+ static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)
154
+ {
155
+ /* Return if there aren't enough bytes. */
156
+ if (cur + num_bytes >= len)
157
+ return 0;
158
+
159
+ if (num_bytes == 0)
160
+ return 0;
161
+ else if (num_bytes == 1) {
162
+ return rpt[cur+1];
163
+ }
164
+ else if (num_bytes == 2) {
165
+ return (rpt[cur+2] * 256 + rpt[cur+1]);
166
+ }
167
+ else if (num_bytes == 4) {
168
+ return (rpt[cur+4] * 0x01000000 +
169
+ rpt[cur+3] * 0x00010000 +
170
+ rpt[cur+2] * 0x00000100 +
171
+ rpt[cur+1] * 0x00000001);
172
+ }
173
+ else
174
+ return 0;
175
+ }
176
+
177
+ /* Retrieves the device's Usage Page and Usage from the report
178
+ descriptor. The algorithm is simple, as it just returns the first
179
+ Usage and Usage Page that it finds in the descriptor.
180
+ The return value is 0 on success and -1 on failure. */
181
+ static int get_usage(uint8_t *report_descriptor, size_t size,
182
+ unsigned short *usage_page, unsigned short *usage)
183
+ {
184
+ unsigned int i = 0;
185
+ int size_code;
186
+ int data_len, key_size;
187
+ int usage_found = 0, usage_page_found = 0;
188
+
189
+ while (i < size) {
190
+ int key = report_descriptor[i];
191
+ int key_cmd = key & 0xfc;
192
+
193
+ //printf("key: %02hhx\n", key);
194
+
195
+ if ((key & 0xf0) == 0xf0) {
196
+ /* This is a Long Item. The next byte contains the
197
+ length of the data section (value) for this key.
198
+ See the HID specification, version 1.11, section
199
+ 6.2.2.3, titled "Long Items." */
200
+ if (i+1 < size)
201
+ data_len = report_descriptor[i+1];
202
+ else
203
+ data_len = 0; /* malformed report */
204
+ key_size = 3;
205
+ }
206
+ else {
207
+ /* This is a Short Item. The bottom two bits of the
208
+ key contain the size code for the data section
209
+ (value) for this key. Refer to the HID
210
+ specification, version 1.11, section 6.2.2.2,
211
+ titled "Short Items." */
212
+ size_code = key & 0x3;
213
+ switch (size_code) {
214
+ case 0:
215
+ case 1:
216
+ case 2:
217
+ data_len = size_code;
218
+ break;
219
+ case 3:
220
+ data_len = 4;
221
+ break;
222
+ default:
223
+ /* Can't ever happen since size_code is & 0x3 */
224
+ data_len = 0;
225
+ break;
226
+ };
227
+ key_size = 1;
228
+ }
229
+
230
+ if (key_cmd == 0x4) {
231
+ *usage_page = get_bytes(report_descriptor, size, data_len, i);
232
+ usage_page_found = 1;
233
+ //printf("Usage Page: %x\n", (uint32_t)*usage_page);
234
+ }
235
+ if (key_cmd == 0x8) {
236
+ *usage = get_bytes(report_descriptor, size, data_len, i);
237
+ usage_found = 1;
238
+ //printf("Usage: %x\n", (uint32_t)*usage);
239
+ }
240
+
241
+ if (usage_page_found && usage_found)
242
+ return 0; /* success */
243
+
244
+ /* Skip over this key and it's associated data */
245
+ i += data_len + key_size;
246
+ }
247
+
248
+ return -1; /* failure */
249
+ }
250
+ #endif /* INVASIVE_GET_USAGE */
251
+
252
+ #ifdef __FreeBSD__
253
+ /* The FreeBSD version of libusb doesn't have this funciton. In mainline
254
+ libusb, it's inlined in libusb.h. This function will bear a striking
255
+ resemblence to that one, because there's about one way to code it.
256
+
257
+ Note that the data parameter is Unicode in UTF-16LE encoding.
258
+ Return value is the number of bytes in data, or LIBUSB_ERROR_*.
259
+ */
260
+ static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
261
+ uint8_t descriptor_index, uint16_t lang_id,
262
+ unsigned char *data, int length)
263
+ {
264
+ return libusb_control_transfer(dev,
265
+ LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */
266
+ LIBUSB_REQUEST_GET_DESCRIPTOR,
267
+ (LIBUSB_DT_STRING << 8) | descriptor_index,
268
+ lang_id, data, (uint16_t) length, 1000);
269
+ }
270
+
271
+ #endif
272
+
273
+
274
+ /* Get the first language the device says it reports. This comes from
275
+ USB string #0. */
276
+ static uint16_t get_first_language(libusb_device_handle *dev)
277
+ {
278
+ uint16_t buf[32];
279
+ int len;
280
+
281
+ /* Get the string from libusb. */
282
+ len = libusb_get_string_descriptor(dev,
283
+ 0x0, /* String ID */
284
+ 0x0, /* Language */
285
+ (unsigned char*)buf,
286
+ sizeof(buf));
287
+ if (len < 4)
288
+ return 0x0;
289
+
290
+ return buf[1]; /* First two bytes are len and descriptor type. */
291
+ }
292
+
293
+ static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
294
+ {
295
+ uint16_t buf[32];
296
+ int len;
297
+ int i;
298
+
299
+ /* Get the string from libusb. */
300
+ len = libusb_get_string_descriptor(dev,
301
+ 0x0, /* String ID */
302
+ 0x0, /* Language */
303
+ (unsigned char*)buf,
304
+ sizeof(buf));
305
+ if (len < 4)
306
+ return 0x0;
307
+
308
+
309
+ len /= 2; /* language IDs are two-bytes each. */
310
+ /* Start at index 1 because there are two bytes of protocol data. */
311
+ for (i = 1; i < len; i++) {
312
+ if (buf[i] == lang)
313
+ return 1;
314
+ }
315
+
316
+ return 0;
317
+ }
318
+
319
+
320
+ /* This function returns a newly allocated wide string containing the USB
321
+ device string numbered by the index. The returned string must be freed
322
+ by using free(). */
323
+ static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
324
+ {
325
+ char buf[512];
326
+ int len;
327
+ wchar_t *str = NULL;
328
+ wchar_t wbuf[256];
329
+
330
+ /* iconv variables */
331
+ iconv_t ic;
332
+ size_t inbytes;
333
+ size_t outbytes;
334
+ size_t res;
335
+ #ifdef __FreeBSD__
336
+ const char *inptr;
337
+ #else
338
+ char *inptr;
339
+ #endif
340
+ char *outptr;
341
+
342
+ /* Determine which language to use. */
343
+ uint16_t lang;
344
+ lang = get_usb_code_for_current_locale();
345
+ if (!is_language_supported(dev, lang))
346
+ lang = get_first_language(dev);
347
+
348
+ /* Get the string from libusb. */
349
+ len = libusb_get_string_descriptor(dev,
350
+ idx,
351
+ lang,
352
+ (unsigned char*)buf,
353
+ sizeof(buf));
354
+ if (len < 0)
355
+ return NULL;
356
+
357
+ /* buf does not need to be explicitly NULL-terminated because
358
+ it is only passed into iconv() which does not need it. */
359
+
360
+ /* Initialize iconv. */
361
+ ic = iconv_open("WCHAR_T", "UTF-16LE");
362
+ if (ic == (iconv_t)-1) {
363
+ LOG("iconv_open() failed\n");
364
+ return NULL;
365
+ }
366
+
367
+ /* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
368
+ Skip the first character (2-bytes). */
369
+ inptr = buf+2;
370
+ inbytes = len-2;
371
+ outptr = (char*) wbuf;
372
+ outbytes = sizeof(wbuf);
373
+ res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
374
+ if (res == (size_t)-1) {
375
+ LOG("iconv() failed\n");
376
+ goto err;
377
+ }
378
+
379
+ /* Write the terminating NULL. */
380
+ wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
381
+ if (outbytes >= sizeof(wbuf[0]))
382
+ *((wchar_t*)outptr) = 0x00000000;
383
+
384
+ /* Allocate and copy the string. */
385
+ str = wcsdup(wbuf);
386
+
387
+ err:
388
+ iconv_close(ic);
389
+
390
+ return str;
391
+ }
392
+
393
+ static char *make_path(libusb_device *dev, int interface_number)
394
+ {
395
+ char str[64];
396
+ snprintf(str, sizeof(str), "%04x:%04x:%02x",
397
+ libusb_get_bus_number(dev),
398
+ libusb_get_device_address(dev),
399
+ interface_number);
400
+ str[sizeof(str)-1] = '\0';
401
+
402
+ return strdup(str);
403
+ }
404
+
405
+
406
+ int HID_API_EXPORT hid_init(void)
407
+ {
408
+ if (!usb_context) {
409
+ const char *locale;
410
+
411
+ /* Init Libusb */
412
+ if (libusb_init(&usb_context))
413
+ return -1;
414
+
415
+ /* Set the locale if it's not set. */
416
+ locale = setlocale(LC_CTYPE, NULL);
417
+ if (!locale)
418
+ setlocale(LC_CTYPE, "");
419
+ }
420
+
421
+ return 0;
422
+ }
423
+
424
+ int HID_API_EXPORT hid_exit(void)
425
+ {
426
+ if (usb_context) {
427
+ libusb_exit(usb_context);
428
+ usb_context = NULL;
429
+ }
430
+
431
+ return 0;
432
+ }
433
+
434
+ struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
435
+ {
436
+ libusb_device **devs;
437
+ libusb_device *dev;
438
+ libusb_device_handle *handle;
439
+ ssize_t num_devs;
440
+ int i = 0;
441
+
442
+ struct hid_device_info *root = NULL; /* return object */
443
+ struct hid_device_info *cur_dev = NULL;
444
+
445
+ hid_init();
446
+
447
+ num_devs = libusb_get_device_list(usb_context, &devs);
448
+ if (num_devs < 0)
449
+ return NULL;
450
+ while ((dev = devs[i++]) != NULL) {
451
+ struct libusb_device_descriptor desc;
452
+ struct libusb_config_descriptor *conf_desc = NULL;
453
+ int j, k;
454
+ int interface_num = 0;
455
+
456
+ int res = libusb_get_device_descriptor(dev, &desc);
457
+ unsigned short dev_vid = desc.idVendor;
458
+ unsigned short dev_pid = desc.idProduct;
459
+
460
+ /* HID's are defined at the interface level. */
461
+ if (desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE)
462
+ continue;
463
+
464
+ res = libusb_get_active_config_descriptor(dev, &conf_desc);
465
+ if (res < 0)
466
+ libusb_get_config_descriptor(dev, 0, &conf_desc);
467
+ if (conf_desc) {
468
+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
469
+ const struct libusb_interface *intf = &conf_desc->interface[j];
470
+ for (k = 0; k < intf->num_altsetting; k++) {
471
+ const struct libusb_interface_descriptor *intf_desc;
472
+ intf_desc = &intf->altsetting[k];
473
+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
474
+ interface_num = intf_desc->bInterfaceNumber;
475
+
476
+ /* Check the VID/PID against the arguments */
477
+ if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
478
+ (product_id == 0x0 || product_id == dev_pid)) {
479
+ struct hid_device_info *tmp;
480
+
481
+ /* VID/PID match. Create the record. */
482
+ tmp = calloc(1, sizeof(struct hid_device_info));
483
+ if (cur_dev) {
484
+ cur_dev->next = tmp;
485
+ }
486
+ else {
487
+ root = tmp;
488
+ }
489
+ cur_dev = tmp;
490
+
491
+ /* Fill out the record */
492
+ cur_dev->next = NULL;
493
+ cur_dev->path = make_path(dev, interface_num);
494
+
495
+ res = libusb_open(dev, &handle);
496
+
497
+ if (res >= 0) {
498
+ /* Serial Number */
499
+ if (desc.iSerialNumber > 0)
500
+ cur_dev->serial_number =
501
+ get_usb_string(handle, desc.iSerialNumber);
502
+
503
+ /* Manufacturer and Product strings */
504
+ if (desc.iManufacturer > 0)
505
+ cur_dev->manufacturer_string =
506
+ get_usb_string(handle, desc.iManufacturer);
507
+ if (desc.iProduct > 0)
508
+ cur_dev->product_string =
509
+ get_usb_string(handle, desc.iProduct);
510
+
511
+ #ifdef INVASIVE_GET_USAGE
512
+ {
513
+ /*
514
+ This section is removed because it is too
515
+ invasive on the system. Getting a Usage Page
516
+ and Usage requires parsing the HID Report
517
+ descriptor. Getting a HID Report descriptor
518
+ involves claiming the interface. Claiming the
519
+ interface involves detaching the kernel driver.
520
+ Detaching the kernel driver is hard on the system
521
+ because it will unclaim interfaces (if another
522
+ app has them claimed) and the re-attachment of
523
+ the driver will sometimes change /dev entry names.
524
+ It is for these reasons that this section is
525
+ #if 0. For composite devices, use the interface
526
+ field in the hid_device_info struct to distinguish
527
+ between interfaces. */
528
+ unsigned char data[256];
529
+ #ifdef DETACH_KERNEL_DRIVER
530
+ int detached = 0;
531
+ /* Usage Page and Usage */
532
+ res = libusb_kernel_driver_active(handle, interface_num);
533
+ if (res == 1) {
534
+ res = libusb_detach_kernel_driver(handle, interface_num);
535
+ if (res < 0)
536
+ LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
537
+ else
538
+ detached = 1;
539
+ }
540
+ #endif
541
+ res = libusb_claim_interface(handle, interface_num);
542
+ if (res >= 0) {
543
+ /* Get the HID Report Descriptor. */
544
+ res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
545
+ if (res >= 0) {
546
+ unsigned short page=0, usage=0;
547
+ /* Parse the usage and usage page
548
+ out of the report descriptor. */
549
+ get_usage(data, res, &page, &usage);
550
+ cur_dev->usage_page = page;
551
+ cur_dev->usage = usage;
552
+ }
553
+ else
554
+ LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);
555
+
556
+ /* Release the interface */
557
+ res = libusb_release_interface(handle, interface_num);
558
+ if (res < 0)
559
+ LOG("Can't release the interface.\n");
560
+ }
561
+ else
562
+ LOG("Can't claim interface %d\n", res);
563
+ #ifdef DETACH_KERNEL_DRIVER
564
+ /* Re-attach kernel driver if necessary. */
565
+ if (detached) {
566
+ res = libusb_attach_kernel_driver(handle, interface_num);
567
+ if (res < 0)
568
+ LOG("Couldn't re-attach kernel driver.\n");
569
+ }
570
+ #endif
571
+ }
572
+ #endif /* INVASIVE_GET_USAGE */
573
+
574
+ libusb_close(handle);
575
+ }
576
+ /* VID/PID */
577
+ cur_dev->vendor_id = dev_vid;
578
+ cur_dev->product_id = dev_pid;
579
+
580
+ /* Release Number */
581
+ cur_dev->release_number = desc.bcdDevice;
582
+
583
+ /* Interface Number */
584
+ cur_dev->interface_number = interface_num;
585
+ }
586
+ }
587
+ } /* altsettings */
588
+ } /* interfaces */
589
+ libusb_free_config_descriptor(conf_desc);
590
+ }
591
+ }
592
+
593
+ libusb_free_device_list(devs, 1);
594
+
595
+ return root;
596
+ }
597
+
598
+ void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
599
+ {
600
+ struct hid_device_info *d = devs;
601
+ while (d) {
602
+ struct hid_device_info *next = d->next;
603
+ free(d->path);
604
+ free(d->serial_number);
605
+ free(d->manufacturer_string);
606
+ free(d->product_string);
607
+ free(d);
608
+ d = next;
609
+ }
610
+ }
611
+
612
+ hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)
613
+ {
614
+ struct hid_device_info *devs, *cur_dev;
615
+ const char *path_to_open = NULL;
616
+ hid_device *handle = NULL;
617
+
618
+ devs = hid_enumerate(vendor_id, product_id);
619
+ cur_dev = devs;
620
+ while (cur_dev) {
621
+ if (cur_dev->vendor_id == vendor_id &&
622
+ cur_dev->product_id == product_id) {
623
+ if (serial_number) {
624
+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
625
+ path_to_open = cur_dev->path;
626
+ break;
627
+ }
628
+ }
629
+ else {
630
+ path_to_open = cur_dev->path;
631
+ break;
632
+ }
633
+ }
634
+ cur_dev = cur_dev->next;
635
+ }
636
+
637
+ if (path_to_open) {
638
+ /* Open the device */
639
+ handle = hid_open_path(path_to_open);
640
+ }
641
+
642
+ hid_free_enumeration(devs);
643
+
644
+ return handle;
645
+ }
646
+
647
+ static void read_callback(struct libusb_transfer *transfer)
648
+ {
649
+ hid_device *dev = transfer->user_data;
650
+ int res;
651
+
652
+ if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
653
+
654
+ struct input_report *rpt = malloc(sizeof(*rpt));
655
+ rpt->data = malloc(transfer->actual_length);
656
+ memcpy(rpt->data, transfer->buffer, transfer->actual_length);
657
+ rpt->len = transfer->actual_length;
658
+ rpt->next = NULL;
659
+
660
+ pthread_mutex_lock(&dev->mutex);
661
+
662
+ /* Attach the new report object to the end of the list. */
663
+ if (dev->input_reports == NULL) {
664
+ /* The list is empty. Put it at the root. */
665
+ dev->input_reports = rpt;
666
+ pthread_cond_signal(&dev->condition);
667
+ }
668
+ else {
669
+ /* Find the end of the list and attach. */
670
+ struct input_report *cur = dev->input_reports;
671
+ int num_queued = 0;
672
+ while (cur->next != NULL) {
673
+ cur = cur->next;
674
+ num_queued++;
675
+ }
676
+ cur->next = rpt;
677
+
678
+ /* Pop one off if we've reached 30 in the queue. This
679
+ way we don't grow forever if the user never reads
680
+ anything from the device. */
681
+ if (num_queued > 30) {
682
+ return_data(dev, NULL, 0);
683
+ }
684
+ }
685
+ pthread_mutex_unlock(&dev->mutex);
686
+ }
687
+ else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
688
+ dev->shutdown_thread = 1;
689
+ return;
690
+ }
691
+ else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
692
+ dev->shutdown_thread = 1;
693
+ return;
694
+ }
695
+ else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
696
+ //LOG("Timeout (normal)\n");
697
+ }
698
+ else {
699
+ LOG("Unknown transfer code: %d\n", transfer->status);
700
+ }
701
+
702
+ /* Re-submit the transfer object. */
703
+ res = libusb_submit_transfer(transfer);
704
+ if (res != 0) {
705
+ LOG("Unable to submit URB. libusb error code: %d\n", res);
706
+ dev->shutdown_thread = 1;
707
+ }
708
+ }
709
+
710
+
711
+ static void *read_thread(void *param)
712
+ {
713
+ hid_device *dev = param;
714
+ unsigned char *buf;
715
+ const size_t length = dev->input_ep_max_packet_size;
716
+
717
+ /* Set up the transfer object. */
718
+ buf = malloc(length);
719
+ dev->transfer = libusb_alloc_transfer(0);
720
+ libusb_fill_interrupt_transfer(dev->transfer,
721
+ dev->device_handle,
722
+ dev->input_endpoint,
723
+ buf,
724
+ length,
725
+ read_callback,
726
+ dev,
727
+ 5000/*timeout*/);
728
+
729
+ /* Make the first submission. Further submissions are made
730
+ from inside read_callback() */
731
+ libusb_submit_transfer(dev->transfer);
732
+
733
+ /* Notify the main thread that the read thread is up and running. */
734
+ pthread_barrier_wait(&dev->barrier);
735
+
736
+ /* Handle all the events. */
737
+ while (!dev->shutdown_thread) {
738
+ int res;
739
+ res = libusb_handle_events(usb_context);
740
+ if (res < 0) {
741
+ /* There was an error. */
742
+ LOG("read_thread(): libusb reports error # %d\n", res);
743
+
744
+ /* Break out of this loop only on fatal error.*/
745
+ if (res != LIBUSB_ERROR_BUSY &&
746
+ res != LIBUSB_ERROR_TIMEOUT &&
747
+ res != LIBUSB_ERROR_OVERFLOW &&
748
+ res != LIBUSB_ERROR_INTERRUPTED) {
749
+ break;
750
+ }
751
+ }
752
+ }
753
+
754
+ /* Cancel any transfer that may be pending. This call will fail
755
+ if no transfers are pending, but that's OK. */
756
+ if (libusb_cancel_transfer(dev->transfer) == 0) {
757
+ /* The transfer was cancelled, so wait for its completion. */
758
+ libusb_handle_events(usb_context);
759
+ }
760
+
761
+ /* Now that the read thread is stopping, Wake any threads which are
762
+ waiting on data (in hid_read_timeout()). Do this under a mutex to
763
+ make sure that a thread which is about to go to sleep waiting on
764
+ the condition acutally will go to sleep before the condition is
765
+ signaled. */
766
+ pthread_mutex_lock(&dev->mutex);
767
+ pthread_cond_broadcast(&dev->condition);
768
+ pthread_mutex_unlock(&dev->mutex);
769
+
770
+ /* The dev->transfer->buffer and dev->transfer objects are cleaned up
771
+ in hid_close(). They are not cleaned up here because this thread
772
+ could end either due to a disconnect or due to a user
773
+ call to hid_close(). In both cases the objects can be safely
774
+ cleaned up after the call to pthread_join() (in hid_close()), but
775
+ since hid_close() calls libusb_cancel_transfer(), on these objects,
776
+ they can not be cleaned up here. */
777
+
778
+ return NULL;
779
+ }
780
+
781
+
782
+ hid_device * HID_API_EXPORT hid_open_path(const char *path)
783
+ {
784
+ hid_device *dev = NULL;
785
+
786
+ libusb_device **devs;
787
+ libusb_device *usb_dev;
788
+ int res;
789
+ int d = 0;
790
+ int good_open = 0;
791
+
792
+ dev = new_hid_device();
793
+
794
+ hid_init();
795
+
796
+ libusb_get_device_list(usb_context, &devs);
797
+ while ((usb_dev = devs[d++]) != NULL) {
798
+ struct libusb_device_descriptor desc;
799
+ struct libusb_config_descriptor *conf_desc = NULL;
800
+ int i,j,k;
801
+ libusb_get_device_descriptor(usb_dev, &desc);
802
+
803
+ if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
804
+ continue;
805
+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
806
+ const struct libusb_interface *intf = &conf_desc->interface[j];
807
+ for (k = 0; k < intf->num_altsetting; k++) {
808
+ const struct libusb_interface_descriptor *intf_desc;
809
+ intf_desc = &intf->altsetting[k];
810
+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
811
+ char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
812
+ if (!strcmp(dev_path, path)) {
813
+ /* Matched Paths. Open this device */
814
+
815
+ /* OPEN HERE */
816
+ res = libusb_open(usb_dev, &dev->device_handle);
817
+ if (res < 0) {
818
+ LOG("can't open device\n");
819
+ free(dev_path);
820
+ break;
821
+ }
822
+ good_open = 1;
823
+ #ifdef DETACH_KERNEL_DRIVER
824
+ /* Detach the kernel driver, but only if the
825
+ device is managed by the kernel */
826
+ if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
827
+ res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
828
+ if (res < 0) {
829
+ libusb_close(dev->device_handle);
830
+ LOG("Unable to detach Kernel Driver\n");
831
+ free(dev_path);
832
+ good_open = 0;
833
+ break;
834
+ }
835
+ }
836
+ #endif
837
+ res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
838
+ if (res < 0) {
839
+ LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
840
+ free(dev_path);
841
+ libusb_close(dev->device_handle);
842
+ good_open = 0;
843
+ break;
844
+ }
845
+
846
+ /* Store off the string descriptor indexes */
847
+ dev->manufacturer_index = desc.iManufacturer;
848
+ dev->product_index = desc.iProduct;
849
+ dev->serial_index = desc.iSerialNumber;
850
+
851
+ /* Store off the interface number */
852
+ dev->interface = intf_desc->bInterfaceNumber;
853
+
854
+ /* Find the INPUT and OUTPUT endpoints. An
855
+ OUTPUT endpoint is not required. */
856
+ for (i = 0; i < intf_desc->bNumEndpoints; i++) {
857
+ const struct libusb_endpoint_descriptor *ep
858
+ = &intf_desc->endpoint[i];
859
+
860
+ /* Determine the type and direction of this
861
+ endpoint. */
862
+ int is_interrupt =
863
+ (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
864
+ == LIBUSB_TRANSFER_TYPE_INTERRUPT;
865
+ int is_output =
866
+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
867
+ == LIBUSB_ENDPOINT_OUT;
868
+ int is_input =
869
+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
870
+ == LIBUSB_ENDPOINT_IN;
871
+
872
+ /* Decide whether to use it for intput or output. */
873
+ if (dev->input_endpoint == 0 &&
874
+ is_interrupt && is_input) {
875
+ /* Use this endpoint for INPUT */
876
+ dev->input_endpoint = ep->bEndpointAddress;
877
+ dev->input_ep_max_packet_size = ep->wMaxPacketSize;
878
+ }
879
+ if (dev->output_endpoint == 0 &&
880
+ is_interrupt && is_output) {
881
+ /* Use this endpoint for OUTPUT */
882
+ dev->output_endpoint = ep->bEndpointAddress;
883
+ }
884
+ }
885
+
886
+ pthread_create(&dev->thread, NULL, read_thread, dev);
887
+
888
+ /* Wait here for the read thread to be initialized. */
889
+ pthread_barrier_wait(&dev->barrier);
890
+
891
+ }
892
+ free(dev_path);
893
+ }
894
+ }
895
+ }
896
+ libusb_free_config_descriptor(conf_desc);
897
+
898
+ }
899
+
900
+ libusb_free_device_list(devs, 1);
901
+
902
+ /* If we have a good handle, return it. */
903
+ if (good_open) {
904
+ return dev;
905
+ }
906
+ else {
907
+ /* Unable to open any devices. */
908
+ free_hid_device(dev);
909
+ return NULL;
910
+ }
911
+ }
912
+
913
+
914
+ int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
915
+ {
916
+ int res;
917
+ int report_number = data[0];
918
+ int skipped_report_id = 0;
919
+
920
+ if (report_number == 0x0) {
921
+ data++;
922
+ length--;
923
+ skipped_report_id = 1;
924
+ }
925
+
926
+
927
+ if (dev->output_endpoint <= 0) {
928
+ /* No interrput out endpoint. Use the Control Endpoint */
929
+ res = libusb_control_transfer(dev->device_handle,
930
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
931
+ 0x09/*HID Set_Report*/,
932
+ (2/*HID output*/ << 8) | report_number,
933
+ dev->interface,
934
+ (unsigned char *)data, length,
935
+ 1000/*timeout millis*/);
936
+
937
+ if (res < 0)
938
+ return -1;
939
+
940
+ if (skipped_report_id)
941
+ length++;
942
+
943
+ return length;
944
+ }
945
+ else {
946
+ /* Use the interrupt out endpoint */
947
+ int actual_length;
948
+ res = libusb_interrupt_transfer(dev->device_handle,
949
+ dev->output_endpoint,
950
+ (unsigned char*)data,
951
+ length,
952
+ &actual_length, 1000);
953
+
954
+ if (res < 0)
955
+ return -1;
956
+
957
+ if (skipped_report_id)
958
+ actual_length++;
959
+
960
+ return actual_length;
961
+ }
962
+ }
963
+
964
+ /* Helper function, to simplify hid_read().
965
+ This should be called with dev->mutex locked. */
966
+ static int return_data(hid_device *dev, unsigned char *data, size_t length)
967
+ {
968
+ /* Copy the data out of the linked list item (rpt) into the
969
+ return buffer (data), and delete the liked list item. */
970
+ struct input_report *rpt = dev->input_reports;
971
+ size_t len = (length < rpt->len)? length: rpt->len;
972
+ if (len > 0)
973
+ memcpy(data, rpt->data, len);
974
+ dev->input_reports = rpt->next;
975
+ free(rpt->data);
976
+ free(rpt);
977
+ return len;
978
+ }
979
+
980
+ static void cleanup_mutex(void *param)
981
+ {
982
+ hid_device *dev = param;
983
+ pthread_mutex_unlock(&dev->mutex);
984
+ }
985
+
986
+
987
+ int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
988
+ {
989
+ int bytes_read = -1;
990
+
991
+ #if 0
992
+ int transferred;
993
+ int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
994
+ LOG("transferred: %d\n", transferred);
995
+ return transferred;
996
+ #endif
997
+
998
+ pthread_mutex_lock(&dev->mutex);
999
+ pthread_cleanup_push(&cleanup_mutex, dev);
1000
+
1001
+ /* There's an input report queued up. Return it. */
1002
+ if (dev->input_reports) {
1003
+ /* Return the first one */
1004
+ bytes_read = return_data(dev, data, length);
1005
+ goto ret;
1006
+ }
1007
+
1008
+ if (dev->shutdown_thread) {
1009
+ /* This means the device has been disconnected.
1010
+ An error code of -1 should be returned. */
1011
+ bytes_read = -1;
1012
+ goto ret;
1013
+ }
1014
+
1015
+ if (milliseconds == -1) {
1016
+ /* Blocking */
1017
+ while (!dev->input_reports && !dev->shutdown_thread) {
1018
+ pthread_cond_wait(&dev->condition, &dev->mutex);
1019
+ }
1020
+ if (dev->input_reports) {
1021
+ bytes_read = return_data(dev, data, length);
1022
+ }
1023
+ }
1024
+ else if (milliseconds > 0) {
1025
+ /* Non-blocking, but called with timeout. */
1026
+ int res;
1027
+ struct timespec ts;
1028
+ clock_gettime(CLOCK_REALTIME, &ts);
1029
+ ts.tv_sec += milliseconds / 1000;
1030
+ ts.tv_nsec += (milliseconds % 1000) * 1000000;
1031
+ if (ts.tv_nsec >= 1000000000L) {
1032
+ ts.tv_sec++;
1033
+ ts.tv_nsec -= 1000000000L;
1034
+ }
1035
+
1036
+ while (!dev->input_reports && !dev->shutdown_thread) {
1037
+ res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
1038
+ if (res == 0) {
1039
+ if (dev->input_reports) {
1040
+ bytes_read = return_data(dev, data, length);
1041
+ break;
1042
+ }
1043
+
1044
+ /* If we're here, there was a spurious wake up
1045
+ or the read thread was shutdown. Run the
1046
+ loop again (ie: don't break). */
1047
+ }
1048
+ else if (res == ETIMEDOUT) {
1049
+ /* Timed out. */
1050
+ bytes_read = 0;
1051
+ break;
1052
+ }
1053
+ else {
1054
+ /* Error. */
1055
+ bytes_read = -1;
1056
+ break;
1057
+ }
1058
+ }
1059
+ }
1060
+ else {
1061
+ /* Purely non-blocking */
1062
+ bytes_read = 0;
1063
+ }
1064
+
1065
+ ret:
1066
+ pthread_mutex_unlock(&dev->mutex);
1067
+ pthread_cleanup_pop(0);
1068
+
1069
+ return bytes_read;
1070
+ }
1071
+
1072
+ int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
1073
+ {
1074
+ return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);
1075
+ }
1076
+
1077
+ int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
1078
+ {
1079
+ dev->blocking = !nonblock;
1080
+
1081
+ return 0;
1082
+ }
1083
+
1084
+
1085
+ int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
1086
+ {
1087
+ int res = -1;
1088
+ int skipped_report_id = 0;
1089
+ int report_number = data[0];
1090
+
1091
+ if (report_number == 0x0) {
1092
+ data++;
1093
+ length--;
1094
+ skipped_report_id = 1;
1095
+ }
1096
+
1097
+ res = libusb_control_transfer(dev->device_handle,
1098
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
1099
+ 0x09/*HID set_report*/,
1100
+ (3/*HID feature*/ << 8) | report_number,
1101
+ dev->interface,
1102
+ (unsigned char *)data, length,
1103
+ 1000/*timeout millis*/);
1104
+
1105
+ if (res < 0)
1106
+ return -1;
1107
+
1108
+ /* Account for the report ID */
1109
+ if (skipped_report_id)
1110
+ length++;
1111
+
1112
+ return length;
1113
+ }
1114
+
1115
+ int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
1116
+ {
1117
+ int res = -1;
1118
+ int skipped_report_id = 0;
1119
+ int report_number = data[0];
1120
+
1121
+ if (report_number == 0x0) {
1122
+ /* Offset the return buffer by 1, so that the report ID
1123
+ will remain in byte 0. */
1124
+ data++;
1125
+ length--;
1126
+ skipped_report_id = 1;
1127
+ }
1128
+ res = libusb_control_transfer(dev->device_handle,
1129
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,
1130
+ 0x01/*HID get_report*/,
1131
+ (3/*HID feature*/ << 8) | report_number,
1132
+ dev->interface,
1133
+ (unsigned char *)data, length,
1134
+ 1000/*timeout millis*/);
1135
+
1136
+ if (res < 0)
1137
+ return -1;
1138
+
1139
+ if (skipped_report_id)
1140
+ res++;
1141
+
1142
+ return res;
1143
+ }
1144
+
1145
+
1146
+ void HID_API_EXPORT hid_close(hid_device *dev)
1147
+ {
1148
+ if (!dev)
1149
+ return;
1150
+
1151
+ /* Cause read_thread() to stop. */
1152
+ dev->shutdown_thread = 1;
1153
+ libusb_cancel_transfer(dev->transfer);
1154
+
1155
+ /* Wait for read_thread() to end. */
1156
+ pthread_join(dev->thread, NULL);
1157
+
1158
+ /* Clean up the Transfer objects allocated in read_thread(). */
1159
+ free(dev->transfer->buffer);
1160
+ libusb_free_transfer(dev->transfer);
1161
+
1162
+ /* release the interface */
1163
+ libusb_release_interface(dev->device_handle, dev->interface);
1164
+
1165
+ /* Close the handle */
1166
+ libusb_close(dev->device_handle);
1167
+
1168
+ /* Clear out the queue of received reports. */
1169
+ pthread_mutex_lock(&dev->mutex);
1170
+ while (dev->input_reports) {
1171
+ return_data(dev, NULL, 0);
1172
+ }
1173
+ pthread_mutex_unlock(&dev->mutex);
1174
+
1175
+ free_hid_device(dev);
1176
+ }
1177
+
1178
+
1179
+ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
1180
+ {
1181
+ return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);
1182
+ }
1183
+
1184
+ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
1185
+ {
1186
+ return hid_get_indexed_string(dev, dev->product_index, string, maxlen);
1187
+ }
1188
+
1189
+ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
1190
+ {
1191
+ return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);
1192
+ }
1193
+
1194
+ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
1195
+ {
1196
+ wchar_t *str;
1197
+
1198
+ str = get_usb_string(dev->device_handle, string_index);
1199
+ if (str) {
1200
+ wcsncpy(string, str, maxlen);
1201
+ string[maxlen-1] = L'\0';
1202
+ free(str);
1203
+ return 0;
1204
+ }
1205
+ else
1206
+ return -1;
1207
+ }
1208
+
1209
+
1210
+ HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
1211
+ {
1212
+ return NULL;
1213
+ }
1214
+
1215
+
1216
+ struct lang_map_entry {
1217
+ const char *name;
1218
+ const char *string_code;
1219
+ uint16_t usb_code;
1220
+ };
1221
+
1222
+ #define LANG(name,code,usb_code) { name, code, usb_code }
1223
+ static struct lang_map_entry lang_map[] = {
1224
+ LANG("Afrikaans", "af", 0x0436),
1225
+ LANG("Albanian", "sq", 0x041C),
1226
+ LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
1227
+ LANG("Arabic - Bahrain", "ar_bh", 0x3C01),
1228
+ LANG("Arabic - Algeria", "ar_dz", 0x1401),
1229
+ LANG("Arabic - Egypt", "ar_eg", 0x0C01),
1230
+ LANG("Arabic - Iraq", "ar_iq", 0x0801),
1231
+ LANG("Arabic - Jordan", "ar_jo", 0x2C01),
1232
+ LANG("Arabic - Kuwait", "ar_kw", 0x3401),
1233
+ LANG("Arabic - Lebanon", "ar_lb", 0x3001),
1234
+ LANG("Arabic - Libya", "ar_ly", 0x1001),
1235
+ LANG("Arabic - Morocco", "ar_ma", 0x1801),
1236
+ LANG("Arabic - Oman", "ar_om", 0x2001),
1237
+ LANG("Arabic - Qatar", "ar_qa", 0x4001),
1238
+ LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),
1239
+ LANG("Arabic - Syria", "ar_sy", 0x2801),
1240
+ LANG("Arabic - Tunisia", "ar_tn", 0x1C01),
1241
+ LANG("Arabic - Yemen", "ar_ye", 0x2401),
1242
+ LANG("Armenian", "hy", 0x042B),
1243
+ LANG("Azeri - Latin", "az_az", 0x042C),
1244
+ LANG("Azeri - Cyrillic", "az_az", 0x082C),
1245
+ LANG("Basque", "eu", 0x042D),
1246
+ LANG("Belarusian", "be", 0x0423),
1247
+ LANG("Bulgarian", "bg", 0x0402),
1248
+ LANG("Catalan", "ca", 0x0403),
1249
+ LANG("Chinese - China", "zh_cn", 0x0804),
1250
+ LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),
1251
+ LANG("Chinese - Macau SAR", "zh_mo", 0x1404),
1252
+ LANG("Chinese - Singapore", "zh_sg", 0x1004),
1253
+ LANG("Chinese - Taiwan", "zh_tw", 0x0404),
1254
+ LANG("Croatian", "hr", 0x041A),
1255
+ LANG("Czech", "cs", 0x0405),
1256
+ LANG("Danish", "da", 0x0406),
1257
+ LANG("Dutch - Netherlands", "nl_nl", 0x0413),
1258
+ LANG("Dutch - Belgium", "nl_be", 0x0813),
1259
+ LANG("English - Australia", "en_au", 0x0C09),
1260
+ LANG("English - Belize", "en_bz", 0x2809),
1261
+ LANG("English - Canada", "en_ca", 0x1009),
1262
+ LANG("English - Caribbean", "en_cb", 0x2409),
1263
+ LANG("English - Ireland", "en_ie", 0x1809),
1264
+ LANG("English - Jamaica", "en_jm", 0x2009),
1265
+ LANG("English - New Zealand", "en_nz", 0x1409),
1266
+ LANG("English - Phillippines", "en_ph", 0x3409),
1267
+ LANG("English - Southern Africa", "en_za", 0x1C09),
1268
+ LANG("English - Trinidad", "en_tt", 0x2C09),
1269
+ LANG("English - Great Britain", "en_gb", 0x0809),
1270
+ LANG("English - United States", "en_us", 0x0409),
1271
+ LANG("Estonian", "et", 0x0425),
1272
+ LANG("Farsi", "fa", 0x0429),
1273
+ LANG("Finnish", "fi", 0x040B),
1274
+ LANG("Faroese", "fo", 0x0438),
1275
+ LANG("French - France", "fr_fr", 0x040C),
1276
+ LANG("French - Belgium", "fr_be", 0x080C),
1277
+ LANG("French - Canada", "fr_ca", 0x0C0C),
1278
+ LANG("French - Luxembourg", "fr_lu", 0x140C),
1279
+ LANG("French - Switzerland", "fr_ch", 0x100C),
1280
+ LANG("Gaelic - Ireland", "gd_ie", 0x083C),
1281
+ LANG("Gaelic - Scotland", "gd", 0x043C),
1282
+ LANG("German - Germany", "de_de", 0x0407),
1283
+ LANG("German - Austria", "de_at", 0x0C07),
1284
+ LANG("German - Liechtenstein", "de_li", 0x1407),
1285
+ LANG("German - Luxembourg", "de_lu", 0x1007),
1286
+ LANG("German - Switzerland", "de_ch", 0x0807),
1287
+ LANG("Greek", "el", 0x0408),
1288
+ LANG("Hebrew", "he", 0x040D),
1289
+ LANG("Hindi", "hi", 0x0439),
1290
+ LANG("Hungarian", "hu", 0x040E),
1291
+ LANG("Icelandic", "is", 0x040F),
1292
+ LANG("Indonesian", "id", 0x0421),
1293
+ LANG("Italian - Italy", "it_it", 0x0410),
1294
+ LANG("Italian - Switzerland", "it_ch", 0x0810),
1295
+ LANG("Japanese", "ja", 0x0411),
1296
+ LANG("Korean", "ko", 0x0412),
1297
+ LANG("Latvian", "lv", 0x0426),
1298
+ LANG("Lithuanian", "lt", 0x0427),
1299
+ LANG("F.Y.R.O. Macedonia", "mk", 0x042F),
1300
+ LANG("Malay - Malaysia", "ms_my", 0x043E),
1301
+ LANG("Malay – Brunei", "ms_bn", 0x083E),
1302
+ LANG("Maltese", "mt", 0x043A),
1303
+ LANG("Marathi", "mr", 0x044E),
1304
+ LANG("Norwegian - Bokml", "no_no", 0x0414),
1305
+ LANG("Norwegian - Nynorsk", "no_no", 0x0814),
1306
+ LANG("Polish", "pl", 0x0415),
1307
+ LANG("Portuguese - Portugal", "pt_pt", 0x0816),
1308
+ LANG("Portuguese - Brazil", "pt_br", 0x0416),
1309
+ LANG("Raeto-Romance", "rm", 0x0417),
1310
+ LANG("Romanian - Romania", "ro", 0x0418),
1311
+ LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),
1312
+ LANG("Russian", "ru", 0x0419),
1313
+ LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),
1314
+ LANG("Sanskrit", "sa", 0x044F),
1315
+ LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),
1316
+ LANG("Serbian - Latin", "sr_sp", 0x081A),
1317
+ LANG("Setsuana", "tn", 0x0432),
1318
+ LANG("Slovenian", "sl", 0x0424),
1319
+ LANG("Slovak", "sk", 0x041B),
1320
+ LANG("Sorbian", "sb", 0x042E),
1321
+ LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),
1322
+ LANG("Spanish - Argentina", "es_ar", 0x2C0A),
1323
+ LANG("Spanish - Bolivia", "es_bo", 0x400A),
1324
+ LANG("Spanish - Chile", "es_cl", 0x340A),
1325
+ LANG("Spanish - Colombia", "es_co", 0x240A),
1326
+ LANG("Spanish - Costa Rica", "es_cr", 0x140A),
1327
+ LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),
1328
+ LANG("Spanish - Ecuador", "es_ec", 0x300A),
1329
+ LANG("Spanish - Guatemala", "es_gt", 0x100A),
1330
+ LANG("Spanish - Honduras", "es_hn", 0x480A),
1331
+ LANG("Spanish - Mexico", "es_mx", 0x080A),
1332
+ LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),
1333
+ LANG("Spanish - Panama", "es_pa", 0x180A),
1334
+ LANG("Spanish - Peru", "es_pe", 0x280A),
1335
+ LANG("Spanish - Puerto Rico", "es_pr", 0x500A),
1336
+ LANG("Spanish - Paraguay", "es_py", 0x3C0A),
1337
+ LANG("Spanish - El Salvador", "es_sv", 0x440A),
1338
+ LANG("Spanish - Uruguay", "es_uy", 0x380A),
1339
+ LANG("Spanish - Venezuela", "es_ve", 0x200A),
1340
+ LANG("Southern Sotho", "st", 0x0430),
1341
+ LANG("Swahili", "sw", 0x0441),
1342
+ LANG("Swedish - Sweden", "sv_se", 0x041D),
1343
+ LANG("Swedish - Finland", "sv_fi", 0x081D),
1344
+ LANG("Tamil", "ta", 0x0449),
1345
+ LANG("Tatar", "tt", 0X0444),
1346
+ LANG("Thai", "th", 0x041E),
1347
+ LANG("Turkish", "tr", 0x041F),
1348
+ LANG("Tsonga", "ts", 0x0431),
1349
+ LANG("Ukrainian", "uk", 0x0422),
1350
+ LANG("Urdu", "ur", 0x0420),
1351
+ LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),
1352
+ LANG("Uzbek – Latin", "uz_uz", 0x0443),
1353
+ LANG("Vietnamese", "vi", 0x042A),
1354
+ LANG("Xhosa", "xh", 0x0434),
1355
+ LANG("Yiddish", "yi", 0x043D),
1356
+ LANG("Zulu", "zu", 0x0435),
1357
+ LANG(NULL, NULL, 0x0),
1358
+ };
1359
+
1360
+ uint16_t get_usb_code_for_current_locale(void)
1361
+ {
1362
+ char *locale;
1363
+ char search_string[64];
1364
+ char *ptr;
1365
+ struct lang_map_entry *lang;
1366
+
1367
+ /* Get the current locale. */
1368
+ locale = setlocale(0, NULL);
1369
+ if (!locale)
1370
+ return 0x0;
1371
+
1372
+ /* Make a copy of the current locale string. */
1373
+ strncpy(search_string, locale, sizeof(search_string));
1374
+ search_string[sizeof(search_string)-1] = '\0';
1375
+
1376
+ /* Chop off the encoding part, and make it lower case. */
1377
+ ptr = search_string;
1378
+ while (*ptr) {
1379
+ *ptr = tolower(*ptr);
1380
+ if (*ptr == '.') {
1381
+ *ptr = '\0';
1382
+ break;
1383
+ }
1384
+ ptr++;
1385
+ }
1386
+
1387
+ /* Find the entry which matches the string code of our locale. */
1388
+ lang = lang_map;
1389
+ while (lang->string_code) {
1390
+ if (!strcmp(lang->string_code, search_string)) {
1391
+ return lang->usb_code;
1392
+ }
1393
+ lang++;
1394
+ }
1395
+
1396
+ /* There was no match. Find with just the language only. */
1397
+ /* Chop off the variant. Chop it off at the '_'. */
1398
+ ptr = search_string;
1399
+ while (*ptr) {
1400
+ *ptr = tolower(*ptr);
1401
+ if (*ptr == '_') {
1402
+ *ptr = '\0';
1403
+ break;
1404
+ }
1405
+ ptr++;
1406
+ }
1407
+
1408
+ #if 0 /* TODO: Do we need this? */
1409
+ /* Find the entry which matches the string code of our language. */
1410
+ lang = lang_map;
1411
+ while (lang->string_code) {
1412
+ if (!strcmp(lang->string_code, search_string)) {
1413
+ return lang->usb_code;
1414
+ }
1415
+ lang++;
1416
+ }
1417
+ #endif
1418
+
1419
+ /* Found nothing. */
1420
+ return 0x0;
1421
+ }
1422
+
1423
+ #ifdef __cplusplus
1424
+ }
1425
+ #endif