Skip to content

Latest commit

 

History

History
1122 lines (963 loc) · 28.9 KB

hid.cpp

File metadata and controls

1122 lines (963 loc) · 28.9 KB
 
1
2
3
4
5
6
7
8
9
10
11
12
//=================== Copyright Valve Corporation, All rights reserved. =======
//
// Purpose: A wrapper implementing "HID" API for Android
//
// This layer glues the hidapi API to Android's USB and BLE stack.
//
//=============================================================================
#include <jni.h>
#include <android/log.h>
#include <pthread.h>
#include <errno.h> // For ETIMEDOUT and ECONNRESET
Aug 21, 2018
Aug 21, 2018
13
#include <stdlib.h> // For malloc() and free()
Sep 25, 2018
Sep 25, 2018
14
#include <string.h> // For memcpy()
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#define TAG "hidapi"
#ifdef DEBUG
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#else
#define LOGV(...)
#define LOGD(...)
#endif
#define SDL_JAVA_PREFIX org_libsdl_app
#define CONCAT1(prefix, class, function) CONCAT2(prefix, class, function)
#define CONCAT2(prefix, class, function) Java_ ## prefix ## _ ## class ## _ ## function
#define HID_DEVICE_MANAGER_JAVA_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, HIDDeviceManager, function)
#include "../hidapi/hidapi.h"
Sep 15, 2018
Sep 15, 2018
31
32
33
34
35
36
37
typedef uint32_t uint32;
typedef uint64_t uint64;
struct hid_device_
{
Sep 17, 2018
Sep 17, 2018
38
39
int m_nId;
int m_nDeviceRefCount;
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
};
static JavaVM *g_JVM;
static pthread_key_t g_ThreadKey;
template<class T>
class hid_device_ref
{
public:
hid_device_ref( T *pObject = nullptr ) : m_pObject( nullptr )
{
SetObject( pObject );
}
hid_device_ref( const hid_device_ref &rhs ) : m_pObject( nullptr )
{
SetObject( rhs.GetObject() );
}
~hid_device_ref()
{
SetObject( nullptr );
}
void SetObject( T *pObject )
{
if ( m_pObject && m_pObject->DecrementRefCount() == 0 )
{
delete m_pObject;
}
m_pObject = pObject;
if ( m_pObject )
{
m_pObject->IncrementRefCount();
}
}
hid_device_ref &operator =( T *pObject )
{
SetObject( pObject );
return *this;
}
hid_device_ref &operator =( const hid_device_ref &rhs )
{
SetObject( rhs.GetObject() );
return *this;
}
T *GetObject() const
{
return m_pObject;
}
T* operator->() const
{
return m_pObject;
}
operator bool() const
{
return ( m_pObject != nullptr );
}
private:
T *m_pObject;
};
class hid_mutex_guard
{
public:
hid_mutex_guard( pthread_mutex_t *pMutex ) : m_pMutex( pMutex )
{
pthread_mutex_lock( m_pMutex );
}
~hid_mutex_guard()
{
pthread_mutex_unlock( m_pMutex );
}
private:
pthread_mutex_t *m_pMutex;
};
class hid_buffer
{
public:
hid_buffer() : m_pData( nullptr ), m_nSize( 0 ), m_nAllocated( 0 )
{
}
hid_buffer( const uint8_t *pData, size_t nSize ) : m_pData( nullptr ), m_nSize( 0 ), m_nAllocated( 0 )
{
assign( pData, nSize );
}
~hid_buffer()
{
delete[] m_pData;
}
void assign( const uint8_t *pData, size_t nSize )
{
if ( nSize > m_nAllocated )
{
delete[] m_pData;
m_pData = new uint8_t[ nSize ];
m_nAllocated = nSize;
}
m_nSize = nSize;
memcpy( m_pData, pData, nSize );
}
void clear()
{
m_nSize = 0;
}
size_t size() const
{
return m_nSize;
}
const uint8_t *data() const
{
return m_pData;
}
private:
uint8_t *m_pData;
size_t m_nSize;
size_t m_nAllocated;
};
class hid_buffer_pool
{
public:
hid_buffer_pool() : m_nSize( 0 ), m_pHead( nullptr ), m_pTail( nullptr ), m_pFree( nullptr )
{
}
~hid_buffer_pool()
{
clear();
while ( m_pFree )
{
hid_buffer_entry *pEntry = m_pFree;
m_pFree = m_pFree->m_pNext;
delete pEntry;
}
}
size_t size() const { return m_nSize; }
const hid_buffer &front() const { return m_pHead->m_buffer; }
void pop_front()
{
hid_buffer_entry *pEntry = m_pHead;
if ( pEntry )
{
m_pHead = pEntry->m_pNext;
if ( !m_pHead )
{
m_pTail = nullptr;
}
pEntry->m_pNext = m_pFree;
m_pFree = pEntry;
--m_nSize;
}
}
void emplace_back( const uint8_t *pData, size_t nSize )
{
hid_buffer_entry *pEntry;
if ( m_pFree )
{
pEntry = m_pFree;
m_pFree = m_pFree->m_pNext;
}
else
{
pEntry = new hid_buffer_entry;
}
pEntry->m_pNext = nullptr;
if ( m_pTail )
{
m_pTail->m_pNext = pEntry;
}
else
{
m_pHead = pEntry;
}
m_pTail = pEntry;
pEntry->m_buffer.assign( pData, nSize );
++m_nSize;
}
void clear()
{
while ( size() > 0 )
{
pop_front();
}
}
private:
struct hid_buffer_entry
{
hid_buffer m_buffer;
hid_buffer_entry *m_pNext;
};
size_t m_nSize;
hid_buffer_entry *m_pHead;
hid_buffer_entry *m_pTail;
hid_buffer_entry *m_pFree;
};
static jbyteArray NewByteArray( JNIEnv* env, const uint8_t *pData, size_t nDataLen )
{
jbyteArray array = env->NewByteArray( nDataLen );
jbyte *pBuf = env->GetByteArrayElements( array, NULL );
memcpy( pBuf, pData, nDataLen );
env->ReleaseByteArrayElements( array, pBuf, 0 );
return array;
}
static char *CreateStringFromJString( JNIEnv *env, const jstring &sString )
{
size_t nLength = env->GetStringUTFLength( sString );
const char *pjChars = env->GetStringUTFChars( sString, NULL );
char *psString = (char*)malloc( nLength + 1 );
memcpy( psString, pjChars, nLength );
psString[ nLength ] = '\0';
env->ReleaseStringUTFChars( sString, pjChars );
return psString;
}
static wchar_t *CreateWStringFromJString( JNIEnv *env, const jstring &sString )
{
size_t nLength = env->GetStringLength( sString );
const jchar *pjChars = env->GetStringChars( sString, NULL );
wchar_t *pwString = (wchar_t*)malloc( ( nLength + 1 ) * sizeof( wchar_t ) );
wchar_t *pwChars = pwString;
for ( size_t iIndex = 0; iIndex < nLength; ++iIndex )
{
pwChars[ iIndex ] = pjChars[ iIndex ];
}
pwString[ nLength ] = '\0';
env->ReleaseStringChars( sString, pjChars );
return pwString;
}
static wchar_t *CreateWStringFromWString( const wchar_t *pwSrc )
{
size_t nLength = wcslen( pwSrc );
wchar_t *pwString = (wchar_t*)malloc( ( nLength + 1 ) * sizeof( wchar_t ) );
memcpy( pwString, pwSrc, nLength * sizeof( wchar_t ) );
pwString[ nLength ] = '\0';
return pwString;
}
static hid_device_info *CopyHIDDeviceInfo( const hid_device_info *pInfo )
{
hid_device_info *pCopy = new hid_device_info;
*pCopy = *pInfo;
pCopy->path = strdup( pInfo->path );
pCopy->product_string = CreateWStringFromWString( pInfo->product_string );
pCopy->manufacturer_string = CreateWStringFromWString( pInfo->manufacturer_string );
pCopy->serial_number = CreateWStringFromWString( pInfo->serial_number );
return pCopy;
}
static void FreeHIDDeviceInfo( hid_device_info *pInfo )
{
free( pInfo->path );
free( pInfo->serial_number );
free( pInfo->manufacturer_string );
free( pInfo->product_string );
delete pInfo;
}
static jclass g_HIDDeviceManagerCallbackClass;
static jobject g_HIDDeviceManagerCallbackHandler;
static jmethodID g_midHIDDeviceManagerOpen;
static jmethodID g_midHIDDeviceManagerSendOutputReport;
static jmethodID g_midHIDDeviceManagerSendFeatureReport;
static jmethodID g_midHIDDeviceManagerGetFeatureReport;
static jmethodID g_midHIDDeviceManagerClose;
Sep 27, 2018
Sep 27, 2018
339
static uint64_t get_timespec_ms( const struct timespec &ts )
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
{
return (uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
class CHIDDevice
{
public:
CHIDDevice( int nDeviceID, hid_device_info *pInfo )
{
m_nId = nDeviceID;
m_pInfo = pInfo;
// The Bluetooth Steam Controller needs special handling
const int VALVE_USB_VID = 0x28DE;
const int D0G_BLE2_PID = 0x1106;
if ( pInfo->vendor_id == VALVE_USB_VID && pInfo->product_id == D0G_BLE2_PID )
{
m_bIsBLESteamController = true;
}
}
~CHIDDevice()
{
FreeHIDDeviceInfo( m_pInfo );
// Note that we don't delete m_pDevice, as the app may still have a reference to it
}
int IncrementRefCount()
{
Sep 15, 2018
Sep 15, 2018
370
371
372
373
374
int nValue;
pthread_mutex_lock( &m_refCountLock );
nValue = ++m_nRefCount;
pthread_mutex_unlock( &m_refCountLock );
return nValue;
375
376
377
378
}
int DecrementRefCount()
{
Sep 15, 2018
Sep 15, 2018
379
380
381
382
383
int nValue;
pthread_mutex_lock( &m_refCountLock );
nValue = --m_nRefCount;
pthread_mutex_unlock( &m_refCountLock );
return nValue;
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
}
int GetId()
{
return m_nId;
}
const hid_device_info *GetDeviceInfo()
{
return m_pInfo;
}
hid_device *GetDevice()
{
return m_pDevice;
}
bool BOpen()
{
// Make sure thread is attached to JVM/env
JNIEnv *env;
g_JVM->AttachCurrentThread( &env, NULL );
pthread_setspecific( g_ThreadKey, (void*)env );
m_bIsWaitingForOpen = false;
m_bOpenResult = env->CallBooleanMethod( g_HIDDeviceManagerCallbackHandler, g_midHIDDeviceManagerOpen, m_nId );
if ( m_bIsWaitingForOpen )
{
hid_mutex_guard cvl( &m_cvLock );
const int OPEN_TIMEOUT_SECONDS = 60;
struct timespec ts, endtime;
clock_gettime( CLOCK_REALTIME, &ts );
endtime = ts;
endtime.tv_sec += OPEN_TIMEOUT_SECONDS;
do
{
if ( pthread_cond_timedwait( &m_cv, &m_cvLock, &endtime ) != 0 )
{
break;
}
}
while ( m_bIsWaitingForOpen && get_timespec_ms( ts ) < get_timespec_ms( endtime ) );
}
if ( !m_bOpenResult )
{
if ( m_bIsWaitingForOpen )
{
LOGV( "Device open failed - timed out waiting for device permission" );
}
else
{
LOGV( "Device open failed" );
}
return false;
}
m_pDevice = new hid_device;
Sep 17, 2018
Sep 17, 2018
444
445
446
m_pDevice->m_nId = m_nId;
m_pDevice->m_nDeviceRefCount = 1;
LOGD("Creating device %d (%p), refCount = 1\n", m_pDevice->m_nId, m_pDevice);
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
return true;
}
void SetOpenPending()
{
m_bIsWaitingForOpen = true;
}
void SetOpenResult( bool bResult )
{
if ( m_bIsWaitingForOpen )
{
m_bOpenResult = bResult;
m_bIsWaitingForOpen = false;
pthread_cond_signal( &m_cv );
}
}
void ProcessInput( const uint8_t *pBuf, size_t nBufSize )
{
hid_mutex_guard l( &m_dataLock );
size_t MAX_REPORT_QUEUE_SIZE = 16;
if ( m_vecData.size() >= MAX_REPORT_QUEUE_SIZE )
{
m_vecData.pop_front();
}
m_vecData.emplace_back( pBuf, nBufSize );
}
int GetInput( unsigned char *data, size_t length )
{
hid_mutex_guard l( &m_dataLock );
if ( m_vecData.size() == 0 )
{
// LOGV( "hid_read_timeout no data available" );
return 0;
}
const hid_buffer &buffer = m_vecData.front();
size_t nDataLen = buffer.size() > length ? length : buffer.size();
if ( m_bIsBLESteamController )
{
data[0] = 0x03;
memcpy( data + 1, buffer.data(), nDataLen );
++nDataLen;
}
else
{
memcpy( data, buffer.data(), nDataLen );
}
m_vecData.pop_front();
// LOGV("Read %u bytes", nDataLen);
// LOGV("%02x %02x %02x %02x %02x %02x %02x %02x ....",
// data[0], data[1], data[2], data[3],
// data[4], data[5], data[6], data[7]);
return nDataLen;
}
int SendOutputReport( const unsigned char *pData, size_t nDataLen )
{
// Make sure thread is attached to JVM/env
JNIEnv *env;
g_JVM->AttachCurrentThread( &env, NULL );
pthread_setspecific( g_ThreadKey, (void*)env );
jbyteArray pBuf = NewByteArray( env, pData, nDataLen );
int nRet = env->CallIntMethod( g_HIDDeviceManagerCallbackHandler, g_midHIDDeviceManagerSendOutputReport, m_nId, pBuf );
env->DeleteLocalRef( pBuf );
return nRet;
}
int SendFeatureReport( const unsigned char *pData, size_t nDataLen )
{
// Make sure thread is attached to JVM/env
JNIEnv *env;
g_JVM->AttachCurrentThread( &env, NULL );
pthread_setspecific( g_ThreadKey, (void*)env );
jbyteArray pBuf = NewByteArray( env, pData, nDataLen );
int nRet = env->CallIntMethod( g_HIDDeviceManagerCallbackHandler, g_midHIDDeviceManagerSendFeatureReport, m_nId, pBuf );
env->DeleteLocalRef( pBuf );
return nRet;
}
void ProcessFeatureReport( const uint8_t *pBuf, size_t nBufSize )
{
hid_mutex_guard cvl( &m_cvLock );
if ( m_bIsWaitingForFeatureReport )
{
m_featureReport.assign( pBuf, nBufSize );
m_bIsWaitingForFeatureReport = false;
m_nFeatureReportError = 0;
pthread_cond_signal( &m_cv );
}
}
int GetFeatureReport( unsigned char *pData, size_t nDataLen )
{
// Make sure thread is attached to JVM/env
JNIEnv *env;
g_JVM->AttachCurrentThread( &env, NULL );
pthread_setspecific( g_ThreadKey, (void*)env );
{
hid_mutex_guard cvl( &m_cvLock );
if ( m_bIsWaitingForFeatureReport )
{
LOGV( "Get feature report already ongoing... bail" );
return -1; // Read already ongoing, we currently do not serialize, TODO
}
m_bIsWaitingForFeatureReport = true;
}
jbyteArray pBuf = NewByteArray( env, pData, nDataLen );
int nRet = env->CallBooleanMethod( g_HIDDeviceManagerCallbackHandler, g_midHIDDeviceManagerGetFeatureReport, m_nId, pBuf ) ? 0 : -1;
env->DeleteLocalRef( pBuf );
if ( nRet < 0 )
{
LOGV( "GetFeatureReport failed" );
m_bIsWaitingForFeatureReport = false;
return -1;
}
{
hid_mutex_guard cvl( &m_cvLock );
if ( m_bIsWaitingForFeatureReport )
{
LOGV("=== Going to sleep" );
// Wait in CV until we are no longer waiting for a feature report.
const int FEATURE_REPORT_TIMEOUT_SECONDS = 2;
struct timespec ts, endtime;
clock_gettime( CLOCK_REALTIME, &ts );
endtime = ts;
endtime.tv_sec += FEATURE_REPORT_TIMEOUT_SECONDS;
do
{
if ( pthread_cond_timedwait( &m_cv, &m_cvLock, &endtime ) != 0 )
{
break;
}
}
while ( m_bIsWaitingForFeatureReport && get_timespec_ms( ts ) < get_timespec_ms( endtime ) );
// We are back
if ( m_bIsWaitingForFeatureReport )
{
m_nFeatureReportError = -ETIMEDOUT;
m_bIsWaitingForFeatureReport = false;
}
LOGV( "=== Got feature report err=%d", m_nFeatureReportError );
if ( m_nFeatureReportError != 0 )
{
return m_nFeatureReportError;
}
}
size_t uBytesToCopy = m_featureReport.size() > nDataLen ? nDataLen : m_featureReport.size();
memcpy( pData, m_featureReport.data(), uBytesToCopy );
m_featureReport.clear();
LOGV( "=== Got %u bytes", uBytesToCopy );
return uBytesToCopy;
}
}
void Close( bool bDeleteDevice )
{
// Make sure thread is attached to JVM/env
JNIEnv *env;
g_JVM->AttachCurrentThread( &env, NULL );
pthread_setspecific( g_ThreadKey, (void*)env );
env->CallVoidMethod( g_HIDDeviceManagerCallbackHandler, g_midHIDDeviceManagerClose, m_nId );
hid_mutex_guard dataLock( &m_dataLock );
m_vecData.clear();
// Clean and release pending feature report reads
hid_mutex_guard cvLock( &m_cvLock );
m_featureReport.clear();
m_bIsWaitingForFeatureReport = false;
m_nFeatureReportError = -ECONNRESET;
pthread_cond_broadcast( &m_cv );
if ( bDeleteDevice )
{
delete m_pDevice;
m_pDevice = nullptr;
}
}
private:
Sep 15, 2018
Sep 15, 2018
644
pthread_mutex_t m_refCountLock = PTHREAD_MUTEX_INITIALIZER;
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
int m_nRefCount = 0;
int m_nId = 0;
hid_device_info *m_pInfo = nullptr;
hid_device *m_pDevice = nullptr;
bool m_bIsBLESteamController = false;
pthread_mutex_t m_dataLock = PTHREAD_MUTEX_INITIALIZER; // This lock has to be held to access m_vecData
hid_buffer_pool m_vecData;
// For handling get_feature_report
pthread_mutex_t m_cvLock = PTHREAD_MUTEX_INITIALIZER; // This lock has to be held to access any variables below
pthread_cond_t m_cv = PTHREAD_COND_INITIALIZER;
bool m_bIsWaitingForOpen = false;
bool m_bOpenResult = false;
bool m_bIsWaitingForFeatureReport = false;
int m_nFeatureReportError = 0;
hid_buffer m_featureReport;
public:
hid_device_ref<CHIDDevice> next;
};
class CHIDDevice;
static pthread_mutex_t g_DevicesMutex = PTHREAD_MUTEX_INITIALIZER;
Sep 17, 2018
Sep 17, 2018
669
static pthread_mutex_t g_DevicesRefCountMutex = PTHREAD_MUTEX_INITIALIZER;
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
static hid_device_ref<CHIDDevice> g_Devices;
static hid_device_ref<CHIDDevice> FindDevice( int nDeviceId )
{
hid_device_ref<CHIDDevice> pDevice;
hid_mutex_guard l( &g_DevicesMutex );
for ( pDevice = g_Devices; pDevice; pDevice = pDevice->next )
{
if ( pDevice->GetId() == nDeviceId )
{
break;
}
}
return pDevice;
}
static void ThreadDestroyed(void* value)
{
/* The thread is being destroyed, detach it from the Java VM and set the g_ThreadKey value to NULL as required */
JNIEnv *env = (JNIEnv*) value;
if (env != NULL) {
g_JVM->DetachCurrentThread();
pthread_setspecific(g_ThreadKey, NULL);
}
}
Sep 27, 2018
Sep 27, 2018
697
698
extern "C"
Oct 8, 2018
Oct 8, 2018
699
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceRegisterCallback)(JNIEnv *env, jobject thiz);
Sep 27, 2018
Sep 27, 2018
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceReleaseCallback)(JNIEnv *env, jobject thiz);
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceConnected)(JNIEnv *env, jobject thiz, int nDeviceID, jstring sIdentifier, int nVendorId, int nProductId, jstring sSerialNumber, int nReleaseNumber, jstring sManufacturer, jstring sProduct, int nInterface );
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceOpenPending)(JNIEnv *env, jobject thiz, int nDeviceID);
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceOpenResult)(JNIEnv *env, jobject thiz, int nDeviceID, bool bOpened);
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceDisconnected)(JNIEnv *env, jobject thiz, int nDeviceID);
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceInputReport)(JNIEnv *env, jobject thiz, int nDeviceID, jbyteArray value);
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceFeatureReport)(JNIEnv *env, jobject thiz, int nDeviceID, jbyteArray value);
723
extern "C"
Oct 8, 2018
Oct 8, 2018
724
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceRegisterCallback)(JNIEnv *env, jobject thiz )
725
726
727
728
729
730
731
732
733
734
735
736
737
{
LOGV( "HIDDeviceRegisterCallback()");
env->GetJavaVM( &g_JVM );
/*
* Create mThreadKey so we can keep track of the JNIEnv assigned to each thread
* Refer to http://developer.android.com/guide/practices/design/jni.html for the rationale behind this
*/
if (pthread_key_create(&g_ThreadKey, ThreadDestroyed) != 0) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "Error initializing pthread key");
}
Oct 8, 2018
Oct 8, 2018
738
739
740
741
742
743
744
745
746
747
if ( g_HIDDeviceManagerCallbackHandler != NULL )
{
env->DeleteGlobalRef( g_HIDDeviceManagerCallbackClass );
g_HIDDeviceManagerCallbackClass = NULL;
env->DeleteGlobalRef( g_HIDDeviceManagerCallbackHandler );
g_HIDDeviceManagerCallbackHandler = NULL;
}
g_HIDDeviceManagerCallbackHandler = env->NewGlobalRef( thiz );
jclass objClass = env->GetObjectClass( thiz );
748
749
if ( objClass )
{
Oct 8, 2018
Oct 8, 2018
750
g_HIDDeviceManagerCallbackClass = reinterpret_cast< jclass >( env->NewGlobalRef( objClass ) );
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
g_midHIDDeviceManagerOpen = env->GetMethodID( g_HIDDeviceManagerCallbackClass, "openDevice", "(I)Z" );
if ( !g_midHIDDeviceManagerOpen )
{
__android_log_print(ANDROID_LOG_ERROR, TAG, "HIDDeviceRegisterCallback: callback class missing openDevice" );
}
g_midHIDDeviceManagerSendOutputReport = env->GetMethodID( g_HIDDeviceManagerCallbackClass, "sendOutputReport", "(I[B)I" );
if ( !g_midHIDDeviceManagerSendOutputReport )
{
__android_log_print(ANDROID_LOG_ERROR, TAG, "HIDDeviceRegisterCallback: callback class missing sendOutputReport" );
}
g_midHIDDeviceManagerSendFeatureReport = env->GetMethodID( g_HIDDeviceManagerCallbackClass, "sendFeatureReport", "(I[B)I" );
if ( !g_midHIDDeviceManagerSendFeatureReport )
{
__android_log_print(ANDROID_LOG_ERROR, TAG, "HIDDeviceRegisterCallback: callback class missing sendFeatureReport" );
}
g_midHIDDeviceManagerGetFeatureReport = env->GetMethodID( g_HIDDeviceManagerCallbackClass, "getFeatureReport", "(I[B)Z" );
if ( !g_midHIDDeviceManagerGetFeatureReport )
{
__android_log_print(ANDROID_LOG_ERROR, TAG, "HIDDeviceRegisterCallback: callback class missing getFeatureReport" );
}
g_midHIDDeviceManagerClose = env->GetMethodID( g_HIDDeviceManagerCallbackClass, "closeDevice", "(I)V" );
if ( !g_midHIDDeviceManagerClose )
{
__android_log_print(ANDROID_LOG_ERROR, TAG, "HIDDeviceRegisterCallback: callback class missing closeDevice" );
}
env->DeleteLocalRef( objClass );
}
}
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceReleaseCallback)(JNIEnv *env, jobject thiz)
{
LOGV("HIDDeviceReleaseCallback");
Oct 8, 2018
Oct 8, 2018
784
785
786
787
788
789
790
if ( env->IsSameObject( thiz, g_HIDDeviceManagerCallbackHandler ) )
{
env->DeleteGlobalRef( g_HIDDeviceManagerCallbackClass );
g_HIDDeviceManagerCallbackClass = NULL;
env->DeleteGlobalRef( g_HIDDeviceManagerCallbackHandler );
g_HIDDeviceManagerCallbackHandler = NULL;
}
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
}
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceConnected)(JNIEnv *env, jobject thiz, int nDeviceID, jstring sIdentifier, int nVendorId, int nProductId, jstring sSerialNumber, int nReleaseNumber, jstring sManufacturer, jstring sProduct, int nInterface )
{
LOGV( "HIDDeviceConnected() id=%d VID/PID = %.4x/%.4x, interface %d\n", nDeviceID, nVendorId, nProductId, nInterface );
hid_device_info *pInfo = new hid_device_info;
memset( pInfo, 0, sizeof( *pInfo ) );
pInfo->path = CreateStringFromJString( env, sIdentifier );
pInfo->vendor_id = nVendorId;
pInfo->product_id = nProductId;
pInfo->serial_number = CreateWStringFromJString( env, sSerialNumber );
pInfo->release_number = nReleaseNumber;
pInfo->manufacturer_string = CreateWStringFromJString( env, sManufacturer );
pInfo->product_string = CreateWStringFromJString( env, sProduct );
pInfo->interface_number = nInterface;
hid_device_ref<CHIDDevice> pDevice( new CHIDDevice( nDeviceID, pInfo ) );
hid_mutex_guard l( &g_DevicesMutex );
hid_device_ref<CHIDDevice> pLast, pCurr;
for ( pCurr = g_Devices; pCurr; pLast = pCurr, pCurr = pCurr->next )
{
continue;
}
if ( pLast )
{
pLast->next = pDevice;
}
else
{
g_Devices = pDevice;
}
}
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceOpenPending)(JNIEnv *env, jobject thiz, int nDeviceID)
{
LOGV( "HIDDeviceOpenPending() id=%d\n", nDeviceID );
hid_device_ref<CHIDDevice> pDevice = FindDevice( nDeviceID );
if ( pDevice )
{
pDevice->SetOpenPending();
}
}
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceOpenResult)(JNIEnv *env, jobject thiz, int nDeviceID, bool bOpened)
{
LOGV( "HIDDeviceOpenResult() id=%d, result=%s\n", nDeviceID, bOpened ? "true" : "false" );
hid_device_ref<CHIDDevice> pDevice = FindDevice( nDeviceID );
if ( pDevice )
{
pDevice->SetOpenResult( bOpened );
}
}
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceDisconnected)(JNIEnv *env, jobject thiz, int nDeviceID)
{
LOGV( "HIDDeviceDisconnected() id=%d\n", nDeviceID );
hid_device_ref<CHIDDevice> pDevice;
{
hid_mutex_guard l( &g_DevicesMutex );
hid_device_ref<CHIDDevice> pLast, pCurr;
for ( pCurr = g_Devices; pCurr; pLast = pCurr, pCurr = pCurr->next )
{
if ( pCurr->GetId() == nDeviceID )
{
pDevice = pCurr;
if ( pLast )
{
pLast->next = pCurr->next;
}
else
{
g_Devices = pCurr->next;
}
}
}
}
if ( pDevice )
{
pDevice->Close( false );
}
}
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceInputReport)(JNIEnv *env, jobject thiz, int nDeviceID, jbyteArray value)
{
jbyte *pBuf = env->GetByteArrayElements(value, NULL);
jsize nBufSize = env->GetArrayLength(value);
// LOGV( "HIDDeviceInput() id=%d len=%u\n", nDeviceID, nBufSize );
hid_device_ref<CHIDDevice> pDevice = FindDevice( nDeviceID );
if ( pDevice )
{
pDevice->ProcessInput( reinterpret_cast< const uint8_t* >( pBuf ), nBufSize );
}
env->ReleaseByteArrayElements(value, pBuf, 0);
}
extern "C"
JNIEXPORT void JNICALL HID_DEVICE_MANAGER_JAVA_INTERFACE(HIDDeviceFeatureReport)(JNIEnv *env, jobject thiz, int nDeviceID, jbyteArray value)
{
jbyte *pBuf = env->GetByteArrayElements(value, NULL);
jsize nBufSize = env->GetArrayLength(value);
LOGV( "HIDDeviceFeatureReport() id=%d len=%u\n", nDeviceID, nBufSize );
hid_device_ref<CHIDDevice> pDevice = FindDevice( nDeviceID );
if ( pDevice )
{
pDevice->ProcessFeatureReport( reinterpret_cast< const uint8_t* >( pBuf ), nBufSize );
}
env->ReleaseByteArrayElements(value, pBuf, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
int hid_init(void)
{
return 0;
}
struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
struct hid_device_info *root = NULL;
hid_mutex_guard l( &g_DevicesMutex );
for ( hid_device_ref<CHIDDevice> pDevice = g_Devices; pDevice; pDevice = pDevice->next )
{
const hid_device_info *info = pDevice->GetDeviceInfo();
if ( ( vendor_id == 0 && product_id == 0 ) ||
( vendor_id == info->vendor_id && product_id == info->product_id ) )
{
hid_device_info *dev = CopyHIDDeviceInfo( info );
dev->next = root;
root = dev;
}
}
return root;
}
void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
{
while ( devs )
{
struct hid_device_info *next = devs->next;
FreeHIDDeviceInfo( devs );
devs = next;
}
}
HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
{
// TODO: Implement
return NULL;
}
HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path, int bExclusive)
{
LOGV( "hid_open_path( %s )", path );
hid_device_ref< CHIDDevice > pDevice;
{
Sep 17, 2018
Sep 17, 2018
964
hid_mutex_guard r( &g_DevicesRefCountMutex );
965
966
967
968
969
hid_mutex_guard l( &g_DevicesMutex );
for ( hid_device_ref<CHIDDevice> pCurr = g_Devices; pCurr; pCurr = pCurr->next )
{
if ( strcmp( pCurr->GetDeviceInfo()->path, path ) == 0 )
{
Sep 17, 2018
Sep 17, 2018
970
971
972
973
974
975
hid_device *pValue = pCurr->GetDevice();
if ( pValue )
{
++pValue->m_nDeviceRefCount;
LOGD("Incrementing device %d (%p), refCount = %d\n", pValue->m_nId, pValue, pValue->m_nDeviceRefCount);
return pValue;
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
}
// Hold a shared pointer to the controller for the duration
pDevice = pCurr;
break;
}
}
}
if ( pDevice && pDevice->BOpen() )
{
return pDevice->GetDevice();
}
return NULL;
}
int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length)
{
Sep 17, 2018
Sep 17, 2018
993
994
LOGV( "hid_write id=%d length=%u", device->m_nId, length );
hid_device_ref<CHIDDevice> pDevice = FindDevice( device->m_nId );
995
996
997
998
999
1000
if ( pDevice )
{
return pDevice->SendOutputReport( data, length );
}
return -1; // Controller was disconnected
}