forked from saki4510t/UVCCamera
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathUSBMonitor.java
More file actions
1386 lines (1289 loc) · 45.6 KB
/
Copy pathUSBMonitor.java
File metadata and controls
1386 lines (1289 loc) · 45.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
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
784
785
786
787
788
789
790
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki t_saki@serenegiant.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usb;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import com.serenegiant.utils.BuildCheck;
import com.serenegiant.utils.HandlerThreadHandler;
public final class USBMonitor {
private static final boolean DEBUG = false; // TODO set false on production
private static final String TAG = "USBMonitor";
private static final String ACTION_USB_PERMISSION_BASE = "com.serenegiant.USB_PERMISSION.";
private final String ACTION_USB_PERMISSION = ACTION_USB_PERMISSION_BASE + hashCode();
public static final String ACTION_USB_DEVICE_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
/**
* openしているUsbControlBlock
*/
private final ConcurrentHashMap<UsbDevice, UsbControlBlock> mCtrlBlocks = new ConcurrentHashMap<UsbDevice, UsbControlBlock>();
private final SparseArray<WeakReference<UsbDevice>> mHasPermissions = new SparseArray<WeakReference<UsbDevice>>();
private final WeakReference<Context> mWeakContext;
private final UsbManager mUsbManager;
private final OnDeviceConnectListener mOnDeviceConnectListener;
private PendingIntent mPermissionIntent = null;
private List<DeviceFilter> mDeviceFilters = new ArrayList<DeviceFilter>();
/**
* コールバックをワーカースレッドで呼び出すためのハンドラー
*/
private final Handler mAsyncHandler;
private volatile boolean destroyed;
/**
* USB機器の状態変更時のコールバックリスナー
*/
public interface OnDeviceConnectListener {
/**
* called when device attached
* @param device
*/
public void onAttach(UsbDevice device);
/**
* called when device dettach(after onDisconnect)
* @param device
*/
public void onDettach(UsbDevice device);
/**
* called after device opend
* @param device
* @param ctrlBlock
* @param createNew
*/
public void onConnect(UsbDevice device, UsbControlBlock ctrlBlock, boolean createNew);
/**
* called when USB device removed or its power off (this callback is called after device closing)
* @param device
* @param ctrlBlock
*/
public void onDisconnect(UsbDevice device, UsbControlBlock ctrlBlock);
/**
* called when canceled or could not get permission from user
* @param device
*/
public void onCancel(UsbDevice device);
}
public USBMonitor(final Context context, final OnDeviceConnectListener listener) {
if (DEBUG) Log.v(TAG, "USBMonitor:Constructor");
if (listener == null)
throw new IllegalArgumentException("OnDeviceConnectListener should not null.");
mWeakContext = new WeakReference<Context>(context);
mUsbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
mOnDeviceConnectListener = listener;
mAsyncHandler = HandlerThreadHandler.createHandler(TAG);
destroyed = false;
if (DEBUG) Log.v(TAG, "USBMonitor:mUsbManager=" + mUsbManager);
}
/**
* Release all related resources,
* never reuse again
*/
public void destroy() {
if (DEBUG) Log.i(TAG, "destroy:");
unregister();
if (!destroyed) {
destroyed = true;
// モニターしているUSB機器を全てcloseする
final Set<UsbDevice> keys = mCtrlBlocks.keySet();
if (keys != null) {
UsbControlBlock ctrlBlock;
try {
for (final UsbDevice key: keys) {
ctrlBlock = mCtrlBlocks.remove(key);
if (ctrlBlock != null) {
ctrlBlock.close();
}
}
} catch (final Exception e) {
Log.e(TAG, "destroy:", e);
}
}
mCtrlBlocks.clear();
try {
mAsyncHandler.getLooper().quit();
} catch (final Exception e) {
Log.e(TAG, "destroy:", e);
}
}
}
/**
* register BroadcastReceiver to monitor USB events
* @throws IllegalStateException
*/
public synchronized void register() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
if (mPermissionIntent == null) {
if (DEBUG) Log.i(TAG, "register:");
final Context context = mWeakContext.get();
if (context != null) {
final var permissionIntent = new Intent(ACTION_USB_PERMISSION);
permissionIntent.setPackage(context.getPackageName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
mPermissionIntent = PendingIntent.getBroadcast(context, 0, permissionIntent, PendingIntent.FLAG_MUTABLE);
} else {
mPermissionIntent = PendingIntent.getBroadcast(context, 0, permissionIntent, 0);
}
final IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
// ACTION_USB_DEVICE_ATTACHED never comes on some devices so it should not be added here
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// For Android 13 (API level 33) and above, use receiver flags
context.registerReceiver(mUsbReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// For Android 12 (API level 31) and above
context.registerReceiver(mUsbReceiver, filter);
} else {
// For older versions of Android
context.registerReceiver(mUsbReceiver, filter);
}
}
// start connection check
mDeviceCounts = 0;
mAsyncHandler.postDelayed(mDeviceCheckRunnable, 1000);
}
}
/**
* unregister BroadcastReceiver
* @throws IllegalStateException
*/
public synchronized void unregister() throws IllegalStateException {
// 接続チェック用Runnableを削除
mDeviceCounts = 0;
if (!destroyed) {
mAsyncHandler.removeCallbacks(mDeviceCheckRunnable);
}
if (mPermissionIntent != null) {
// if (DEBUG) Log.i(TAG, "unregister:");
final Context context = mWeakContext.get();
try {
if (context != null) {
context.unregisterReceiver(mUsbReceiver);
}
} catch (final Exception e) {
Log.w(TAG, e);
}
mPermissionIntent = null;
}
}
public synchronized boolean isRegistered() {
return !destroyed && (mPermissionIntent != null);
}
/**
* set device filter
* @param filter
* @throws IllegalStateException
*/
public void setDeviceFilter(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.clear();
mDeviceFilters.add(filter);
}
/**
* デバイスフィルターを追加
* @param filter
* @throws IllegalStateException
*/
public void addDeviceFilter(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.add(filter);
}
/**
* デバイスフィルターを削除
* @param filter
* @throws IllegalStateException
*/
public void removeDeviceFilter(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.remove(filter);
}
/**
* set device filters
* @param filters
* @throws IllegalStateException
*/
public void setDeviceFilter(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.clear();
mDeviceFilters.addAll(filters);
}
/**
* add device filters
* @param filters
* @throws IllegalStateException
*/
public void addDeviceFilter(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.addAll(filters);
}
/**
* remove device filters
* @param filters
*/
public void removeDeviceFilter(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
mDeviceFilters.removeAll(filters);
}
/**
* return the number of connected USB devices that matched device filter
* @return
* @throws IllegalStateException
*/
public int getDeviceCount() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
return getDeviceList().size();
}
/**
* return device list, return empty list if no device matched
* @return
* @throws IllegalStateException
*/
public List<UsbDevice> getDeviceList() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
return getDeviceList(mDeviceFilters);
}
/**
* return device list, return empty list if no device matched
* @param filters
* @return
* @throws IllegalStateException
*/
public List<UsbDevice> getDeviceList(final List<DeviceFilter> filters) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
final List<UsbDevice> result = new ArrayList<UsbDevice>();
if (deviceList != null) {
if ((filters == null) || filters.isEmpty()) {
result.addAll(deviceList.values());
} else {
for (final UsbDevice device: deviceList.values() ) {
for (final DeviceFilter filter: filters) {
if ((filter != null) && filter.matches(device)) {
// when filter matches
if (!filter.isExclude) {
result.add(device);
}
break;
}
}
}
}
}
return result;
}
/**
* return device list, return empty list if no device matched
* @param filter
* @return
* @throws IllegalStateException
*/
public List<UsbDevice> getDeviceList(final DeviceFilter filter) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
final List<UsbDevice> result = new ArrayList<UsbDevice>();
if (deviceList != null) {
for (final UsbDevice device: deviceList.values() ) {
if ((filter == null) || (filter.matches(device) && !filter.isExclude)) {
result.add(device);
}
}
}
return result;
}
/**
* get USB device list, without filter
* @return
* @throws IllegalStateException
*/
public Iterator<UsbDevice> getDevices() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
Iterator<UsbDevice> iterator = null;
final HashMap<String, UsbDevice> list = mUsbManager.getDeviceList();
if (list != null)
iterator = list.values().iterator();
return iterator;
}
/**
* output device list to LogCat
*/
public final void dumpDevices() {
final HashMap<String, UsbDevice> list = mUsbManager.getDeviceList();
if (list != null) {
final Set<String> keys = list.keySet();
if (keys != null && keys.size() > 0) {
final StringBuilder sb = new StringBuilder();
for (final String key: keys) {
final UsbDevice device = list.get(key);
final int num_interface = device != null ? device.getInterfaceCount() : 0;
sb.setLength(0);
for (int i = 0; i < num_interface; i++) {
sb.append(String.format(Locale.US, "interface%d:%s", i, device.getInterface(i).toString()));
}
Log.i(TAG, "key=" + key + ":" + device + ":" + sb.toString());
}
} else {
Log.i(TAG, "no device");
}
} else {
Log.i(TAG, "no device");
}
}
/**
* return whether the specific Usb device has permission
* @param device
* @return true: 指定したUsbDeviceにパーミッションがある
* @throws IllegalStateException
*/
public final boolean hasPermission(final UsbDevice device) throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
return updatePermission(device, device != null && mUsbManager.hasPermission(device));
}
/**
* 内部で保持しているパーミッション状態を更新
* @param device
* @param hasPermission
* @return hasPermission
*/
private boolean updatePermission(final UsbDevice device, final boolean hasPermission) {
final int deviceKey = getDeviceKey(device, true);
synchronized (mHasPermissions) {
if (hasPermission) {
if (mHasPermissions.get(deviceKey) == null) {
mHasPermissions.put(deviceKey, new WeakReference<UsbDevice>(device));
}
} else {
mHasPermissions.remove(deviceKey);
}
}
return hasPermission;
}
/**
* request permission to access to USB device
* @param device
* @return true if fail to request permission
*/
public synchronized boolean requestPermission(final UsbDevice device) {
// if (DEBUG) Log.v(TAG, "requestPermission:device=" + device);
boolean result = false;
if (isRegistered()) {
if (device != null) {
if (mUsbManager.hasPermission(device)) {
// call onConnect if app already has permission
processConnect(device);
} else {
try {
// パーミッションがなければ要求する
mUsbManager.requestPermission(device, mPermissionIntent);
} catch (final Exception e) {
// Android5.1.xのGALAXY系でandroid.permission.sec.MDM_APP_MGMTという意味不明の例外生成するみたい
Log.w(TAG, e);
processCancel(device);
result = true;
}
}
} else {
processCancel(device);
result = true;
}
} else {
processCancel(device);
result = true;
}
return result;
}
/**
* 指定したUsbDeviceをopenする
* @param device
* @return
* @throws SecurityException パーミッションがなければSecurityExceptionを投げる
*/
public UsbControlBlock openDevice(final UsbDevice device) throws SecurityException, IOException {
if (hasPermission(device)) {
UsbControlBlock result = mCtrlBlocks.get(device);
if (result == null) {
result = new UsbControlBlock(USBMonitor.this, device); // この中でopenDeviceする
mCtrlBlocks.put(device, result);
}
return result;
} else {
throw new SecurityException("has no permission");
}
}
/**
* BroadcastReceiver for USB permission
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
if (destroyed) return;
final String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
// when received the result of requesting USB permission
synchronized (USBMonitor.this) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// get permission, call onConnect
processConnect(device);
}
} else {
// failed to get permission
processCancel(device);
}
}
} else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
updatePermission(device, hasPermission(device));
processAttach(device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
// when device removed
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
UsbControlBlock ctrlBlock = mCtrlBlocks.remove(device);
if (ctrlBlock != null) {
// cleanup
ctrlBlock.close();
}
mDeviceCounts = 0;
processDettach(device);
}
}
}
};
/** number of connected & detected devices */
private volatile int mDeviceCounts = 0;
/**
* periodically check connected devices and if it changed, call onAttach
*/
private final Runnable mDeviceCheckRunnable = new Runnable() {
@Override
public void run() {
if (destroyed) return;
final List<UsbDevice> devices = getDeviceList();
final int n = devices.size();
final int hasPermissionCounts;
final int m;
synchronized (mHasPermissions) {
hasPermissionCounts = mHasPermissions.size();
mHasPermissions.clear();
for (final UsbDevice device: devices) {
hasPermission(device);
}
m = mHasPermissions.size();
}
if ((n > mDeviceCounts) || (m > hasPermissionCounts)) {
mDeviceCounts = n;
if (mOnDeviceConnectListener != null) {
for (int i = 0; i < n; i++) {
final UsbDevice device = devices.get(i);
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onAttach(device);
}
});
}
}
}
mAsyncHandler.postDelayed(this, 2000); // confirm every 2 seconds
}
};
/**
* open specific USB device
* @param device
*/
private final void processConnect(final UsbDevice device) {
if (destroyed) return;
updatePermission(device, true);
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
if (DEBUG) Log.v(TAG, "processConnect:device=" + device);
UsbControlBlock ctrlBlock;
final boolean createNew;
ctrlBlock = mCtrlBlocks.get(device);
if (ctrlBlock == null) {
try {
ctrlBlock = new UsbControlBlock(USBMonitor.this, device);
} catch (final IOException e) {
Log.w(TAG, "processConnect:failed to open device", e);
processCancel(device);
return;
}
mCtrlBlocks.put(device, ctrlBlock);
createNew = true;
} else {
createNew = false;
}
if (mOnDeviceConnectListener != null) {
mOnDeviceConnectListener.onConnect(device, ctrlBlock, createNew);
}
}
});
}
private final void processCancel(final UsbDevice device) {
if (destroyed) return;
if (DEBUG) Log.v(TAG, "processCancel:");
updatePermission(device, false);
if (mOnDeviceConnectListener != null) {
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onCancel(device);
}
});
}
}
private final void processAttach(final UsbDevice device) {
if (destroyed) return;
if (DEBUG) Log.v(TAG, "processAttach:");
if (mOnDeviceConnectListener != null) {
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onAttach(device);
}
});
}
}
private final void processDettach(final UsbDevice device) {
if (destroyed) return;
if (DEBUG) Log.v(TAG, "processDettach:");
if (mOnDeviceConnectListener != null) {
mAsyncHandler.post(new Runnable() {
@Override
public void run() {
mOnDeviceConnectListener.onDettach(device);
}
});
}
}
/**
* USB機器毎の設定保存用にデバイスキー名を生成する。
* ベンダーID, プロダクトID, デバイスクラス, デバイスサブクラス, デバイスプロトコルから生成
* 同種の製品だと同じキー名になるので注意
* @param device nullなら空文字列を返す
* @return
*/
public static final String getDeviceKeyName(final UsbDevice device) {
return getDeviceKeyName(device, null, false);
}
/**
* USB機器毎の設定保存用にデバイスキー名を生成する。
* useNewAPI=falseで同種の製品だと同じデバイスキーになるので注意
* @param device
* @param useNewAPI
* @return
*/
public static final String getDeviceKeyName(final UsbDevice device, final boolean useNewAPI) {
return getDeviceKeyName(device, null, useNewAPI);
}
/**
* USB機器毎の設定保存用にデバイスキー名を生成する。この機器名をHashMapのキーにする
* UsbDeviceがopenしている時のみ有効
* ベンダーID, プロダクトID, デバイスクラス, デバイスサブクラス, デバイスプロトコルから生成
* serialがnullや空文字でなければserialを含めたデバイスキー名を生成する
* useNewAPI=trueでAPIレベルを満たしていればマニュファクチャ名, バージョン, コンフィギュレーションカウントも使う
* @param device nullなら空文字列を返す
* @param serial UsbDeviceConnection#getSerialで取得したシリアル番号を渡す, nullでuseNewAPI=trueでAPI>=21なら内部で取得
* @param useNewAPI API>=21またはAPI>=23のみで使用可能なメソッドも使用する(ただし機器によってはnullが返ってくるので有効かどうかは機器による)
* @return
*/
@SuppressLint("NewApi")
public static final String getDeviceKeyName(final UsbDevice device, final String serial, final boolean useNewAPI) {
if (device == null) return "";
final StringBuilder sb = new StringBuilder();
sb.append(device.getVendorId()); sb.append("#"); // API >= 12
sb.append(device.getProductId()); sb.append("#"); // API >= 12
sb.append(device.getDeviceClass()); sb.append("#"); // API >= 12
sb.append(device.getDeviceSubclass()); sb.append("#"); // API >= 12
sb.append(device.getDeviceProtocol()); // API >= 12
if (!TextUtils.isEmpty(serial)) {
sb.append("#"); sb.append(serial);
}
if (useNewAPI && BuildCheck.isAndroid5()) {
sb.append("#");
if (TextUtils.isEmpty(serial)) {
try {
sb.append(device.getSerialNumber());
sb.append("#");
} // API >= 21 & targetSdkVersion has to be <= 28
catch(SecurityException ignore) {}
}
sb.append(device.getManufacturerName()); sb.append("#"); // API >= 21
sb.append(device.getConfigurationCount()); sb.append("#"); // API >= 21
if (BuildCheck.isMarshmallow()) {
sb.append(device.getVersion()); sb.append("#"); // API >= 23
}
}
// if (DEBUG) Log.v(TAG, "getDeviceKeyName:" + sb.toString());
return sb.toString();
}
/**
* デバイスキーを整数として取得
* getDeviceKeyNameで得られる文字列のhasCodeを取得
* ベンダーID, プロダクトID, デバイスクラス, デバイスサブクラス, デバイスプロトコルから生成
* 同種の製品だと同じデバイスキーになるので注意
* @param device nullなら0を返す
* @return
*/
public static final int getDeviceKey(final UsbDevice device) {
return device != null ? getDeviceKeyName(device, null, false).hashCode() : 0;
}
/**
* デバイスキーを整数として取得
* getDeviceKeyNameで得られる文字列のhasCodeを取得
* useNewAPI=falseで同種の製品だと同じデバイスキーになるので注意
* @param device
* @param useNewAPI
* @return
*/
public static final int getDeviceKey(final UsbDevice device, final boolean useNewAPI) {
return device != null ? getDeviceKeyName(device, null, useNewAPI).hashCode() : 0;
}
/**
* デバイスキーを整数として取得
* getDeviceKeyNameで得られる文字列のhasCodeを取得
* serialがnullでuseNewAPI=falseで同種の製品だと同じデバイスキーになるので注意
* @param device nullなら0を返す
* @param serial UsbDeviceConnection#getSerialで取得したシリアル番号を渡す, nullでuseNewAPI=trueでAPI>=21なら内部で取得
* @param useNewAPI API>=21またはAPI>=23のみで使用可能なメソッドも使用する(ただし機器によってはnullが返ってくるので有効かどうかは機器による)
* @return
*/
public static final int getDeviceKey(final UsbDevice device, final String serial, final boolean useNewAPI) {
return device != null ? getDeviceKeyName(device, serial, useNewAPI).hashCode() : 0;
}
public static class UsbDeviceInfo {
public String usb_version;
public String manufacturer;
public String product;
public String version;
public String serial;
private void clear() {
usb_version = manufacturer = product = version = serial = null;
}
@Override
public String toString() {
return String.format("UsbDevice:usb_version=%s,manufacturer=%s,product=%s,version=%s,serial=%s",
usb_version != null ? usb_version : "",
manufacturer != null ? manufacturer : "",
product != null ? product : "",
version != null ? version : "",
serial != null ? serial : "");
}
}
private static final int USB_DIR_OUT = 0;
private static final int USB_DIR_IN = 0x80;
private static final int USB_TYPE_MASK = (0x03 << 5);
private static final int USB_TYPE_STANDARD = (0x00 << 5);
private static final int USB_TYPE_CLASS = (0x01 << 5);
private static final int USB_TYPE_VENDOR = (0x02 << 5);
private static final int USB_TYPE_RESERVED = (0x03 << 5);
private static final int USB_RECIP_MASK = 0x1f;
private static final int USB_RECIP_DEVICE = 0x00;
private static final int USB_RECIP_INTERFACE = 0x01;
private static final int USB_RECIP_ENDPOINT = 0x02;
private static final int USB_RECIP_OTHER = 0x03;
private static final int USB_RECIP_PORT = 0x04;
private static final int USB_RECIP_RPIPE = 0x05;
private static final int USB_REQ_GET_STATUS = 0x00;
private static final int USB_REQ_CLEAR_FEATURE = 0x01;
private static final int USB_REQ_SET_FEATURE = 0x03;
private static final int USB_REQ_SET_ADDRESS = 0x05;
private static final int USB_REQ_GET_DESCRIPTOR = 0x06;
private static final int USB_REQ_SET_DESCRIPTOR = 0x07;
private static final int USB_REQ_GET_CONFIGURATION = 0x08;
private static final int USB_REQ_SET_CONFIGURATION = 0x09;
private static final int USB_REQ_GET_INTERFACE = 0x0A;
private static final int USB_REQ_SET_INTERFACE = 0x0B;
private static final int USB_REQ_SYNCH_FRAME = 0x0C;
private static final int USB_REQ_SET_SEL = 0x30;
private static final int USB_REQ_SET_ISOCH_DELAY = 0x31;
private static final int USB_REQ_SET_ENCRYPTION = 0x0D;
private static final int USB_REQ_GET_ENCRYPTION = 0x0E;
private static final int USB_REQ_RPIPE_ABORT = 0x0E;
private static final int USB_REQ_SET_HANDSHAKE = 0x0F;
private static final int USB_REQ_RPIPE_RESET = 0x0F;
private static final int USB_REQ_GET_HANDSHAKE = 0x10;
private static final int USB_REQ_SET_CONNECTION = 0x11;
private static final int USB_REQ_SET_SECURITY_DATA = 0x12;
private static final int USB_REQ_GET_SECURITY_DATA = 0x13;
private static final int USB_REQ_SET_WUSB_DATA = 0x14;
private static final int USB_REQ_LOOPBACK_DATA_WRITE = 0x15;
private static final int USB_REQ_LOOPBACK_DATA_READ = 0x16;
private static final int USB_REQ_SET_INTERFACE_DS = 0x17;
private static final int USB_REQ_STANDARD_DEVICE_SET = (USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE); // 0x10
private static final int USB_REQ_STANDARD_DEVICE_GET = (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE); // 0x90
private static final int USB_REQ_STANDARD_INTERFACE_SET = (USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_INTERFACE); // 0x11
private static final int USB_REQ_STANDARD_INTERFACE_GET = (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_INTERFACE); // 0x91
private static final int USB_REQ_STANDARD_ENDPOINT_SET = (USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_ENDPOINT); // 0x12
private static final int USB_REQ_STANDARD_ENDPOINT_GET = (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_ENDPOINT); // 0x92
private static final int USB_REQ_CS_DEVICE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0x20
private static final int USB_REQ_CS_DEVICE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0xa0
private static final int USB_REQ_CS_INTERFACE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0x21
private static final int USB_REQ_CS_INTERFACE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0xa1
private static final int USB_REQ_CS_ENDPOINT_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0x22
private static final int USB_REQ_CS_ENDPOINT_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0xa2
private static final int USB_REQ_VENDER_DEVICE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0x40
private static final int USB_REQ_VENDER_DEVICE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_DEVICE); // 0xc0
private static final int USB_REQ_VENDER_INTERFACE_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0x41
private static final int USB_REQ_VENDER_INTERFACE_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE); // 0xc1
private static final int USB_REQ_VENDER_ENDPOINT_SET = (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0x42
private static final int USB_REQ_VENDER_ENDPOINT_GET = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT); // 0xc2
private static final int USB_DT_DEVICE = 0x01;
private static final int USB_DT_CONFIG = 0x02;
private static final int USB_DT_STRING = 0x03;
private static final int USB_DT_INTERFACE = 0x04;
private static final int USB_DT_ENDPOINT = 0x05;
private static final int USB_DT_DEVICE_QUALIFIER = 0x06;
private static final int USB_DT_OTHER_SPEED_CONFIG = 0x07;
private static final int USB_DT_INTERFACE_POWER = 0x08;
private static final int USB_DT_OTG = 0x09;
private static final int USB_DT_DEBUG = 0x0a;
private static final int USB_DT_INTERFACE_ASSOCIATION = 0x0b;
private static final int USB_DT_SECURITY = 0x0c;
private static final int USB_DT_KEY = 0x0d;
private static final int USB_DT_ENCRYPTION_TYPE = 0x0e;
private static final int USB_DT_BOS = 0x0f;
private static final int USB_DT_DEVICE_CAPABILITY = 0x10;
private static final int USB_DT_WIRELESS_ENDPOINT_COMP = 0x11;
private static final int USB_DT_WIRE_ADAPTER = 0x21;
private static final int USB_DT_RPIPE = 0x22;
private static final int USB_DT_CS_RADIO_CONTROL = 0x23;
private static final int USB_DT_PIPE_USAGE = 0x24;
private static final int USB_DT_SS_ENDPOINT_COMP = 0x30;
private static final int USB_DT_CS_DEVICE = (USB_TYPE_CLASS | USB_DT_DEVICE);
private static final int USB_DT_CS_CONFIG = (USB_TYPE_CLASS | USB_DT_CONFIG);
private static final int USB_DT_CS_STRING = (USB_TYPE_CLASS | USB_DT_STRING);
private static final int USB_DT_CS_INTERFACE = (USB_TYPE_CLASS | USB_DT_INTERFACE);
private static final int USB_DT_CS_ENDPOINT = (USB_TYPE_CLASS | USB_DT_ENDPOINT);
private static final int USB_DT_DEVICE_SIZE = 18;
/**
* 指定したIDのStringディスクリプタから文字列を取得する。取得できなければnull
* @param connection
* @param id
* @param languageCount
* @param languages
* @return
*/
private static String getString(final UsbDeviceConnection connection, final int id, final int languageCount, final byte[] languages) {
final byte[] work = new byte[256];
String result = null;
for (int i = 1; i <= languageCount; i++) {
int ret = connection.controlTransfer(
USB_REQ_STANDARD_DEVICE_GET, // USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE
USB_REQ_GET_DESCRIPTOR,
(USB_DT_STRING << 8) | id, languages[i], work, 256, 0);
if ((ret > 2) && (work[0] == ret) && (work[1] == USB_DT_STRING)) {
// skip first two bytes(bLength & bDescriptorType), and copy the rest to the string
try {
result = new String(work, 2, ret - 2, "UTF-16LE");
if (!"Љ".equals(result)) { // 変なゴミが返ってくる時がある
break;
} else {
result = null;
}
} catch (final UnsupportedEncodingException e) {
// ignore
}
}
}
return result;
}
/**
* ベンダー名・製品名・バージョン・シリアルを取得する
* @param device
* @return
*/
public UsbDeviceInfo getDeviceInfo(final UsbDevice device) {
return updateDeviceInfo(mUsbManager, device, null);
}
/**
* ベンダー名・製品名・バージョン・シリアルを取得する
* #updateDeviceInfo(final UsbManager, final UsbDevice, final UsbDeviceInfo)のヘルパーメソッド
* @param context
* @param device
* @return
*/
public static UsbDeviceInfo getDeviceInfo(final Context context, final UsbDevice device) {
return updateDeviceInfo((UsbManager)context.getSystemService(Context.USB_SERVICE), device, new UsbDeviceInfo());
}
/**
* ベンダー名・製品名・バージョン・シリアルを取得する
* @param manager
* @param device
* @param _info
* @return
*/
public static UsbDeviceInfo updateDeviceInfo(final UsbManager manager, final UsbDevice device, final UsbDeviceInfo _info) {
final UsbDeviceInfo info = _info != null ? _info : new UsbDeviceInfo();
info.clear();
if (device != null) {
if (BuildCheck.isLollipop()) {
try {
info.manufacturer = device.getManufacturerName();
info.product = device.getProductName();
info.serial = device.getSerialNumber();
} catch (final SecurityException e) {
Log.w(TAG, "updateDeviceInfo:failed to get device info", e);
}
}
if (BuildCheck.isMarshmallow()) {
info.usb_version = device.getVersion();
}
if ((manager != null) && manager.hasPermission(device)) {
final UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) {
Log.w(TAG, "updateDeviceInfo:openDevice failed, device may have been disconnected");
return info;
}
final byte[] desc = connection.getRawDescriptors();
if (TextUtils.isEmpty(info.usb_version)) {
info.usb_version = String.format("%x.%02x", ((int)desc[3] & 0xff), ((int)desc[2] & 0xff));
}
if (TextUtils.isEmpty(info.version)) {
info.version = String.format("%x.%02x", ((int)desc[13] & 0xff), ((int)desc[12] & 0xff));
}
if (TextUtils.isEmpty(info.serial)) {
info.serial = connection.getSerial();
}
final byte[] languages = new byte[256];
int languageCount = 0;
// controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)
try {
int result = connection.controlTransfer(
USB_REQ_STANDARD_DEVICE_GET, // USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE
USB_REQ_GET_DESCRIPTOR,
(USB_DT_STRING << 8) | 0, 0, languages, 256, 0);
if (result > 0) {
languageCount = (result - 2) / 2;
}
if (languageCount > 0) {
if (TextUtils.isEmpty(info.manufacturer)) {
info.manufacturer = getString(connection, desc[14], languageCount, languages);
}
if (TextUtils.isEmpty(info.product)) {
info.product = getString(connection, desc[15], languageCount, languages);
}
if (TextUtils.isEmpty(info.serial)) {
info.serial = getString(connection, desc[16], languageCount, languages);
}
}
} finally {
connection.close();
}
}
if (TextUtils.isEmpty(info.manufacturer)) {
info.manufacturer = USBVendorId.vendorName(device.getVendorId());
}
if (TextUtils.isEmpty(info.manufacturer)) {
info.manufacturer = String.format("%04x", device.getVendorId());
}
if (TextUtils.isEmpty(info.product)) {
info.product = String.format("%04x", device.getProductId());
}
}
return info;
}
/**
* control class
* never reuse the instance when it closed
*/
public static final class UsbControlBlock implements Cloneable {
private final WeakReference<USBMonitor> mWeakMonitor;
private final WeakReference<UsbDevice> mWeakDevice;
protected UsbDeviceConnection mConnection;
protected final UsbDeviceInfo mInfo;
private final int mBusNum;
private final int mDevNum;
private final SparseArray<SparseArray<UsbInterface>> mInterfaces = new SparseArray<SparseArray<UsbInterface>>();
/**