1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "UsbHostManagerJNI"
18 #include <nativehelper/JNIHelp.h>
19 #include <stdlib.h>
20 #include <usbhost/usbhost.h>
21 #include <usbhost/usbhost_jni.h>
22 
23 #include "jni.h"
24 #include "utils/Log.h"
25 
26 static const int USB_CONTROL_TRANSFER_TIMEOUT_MS = 200;
27 
28 // com.android.server.usb.descriptors
29 extern "C" {
Java_com_android_server_usb_descriptors_UsbDescriptorParser_getRawDescriptors_1native(JNIEnv * env,jobject thiz,jstring deviceAddr)30 jbyteArray JNICALL Java_com_android_server_usb_descriptors_UsbDescriptorParser_getRawDescriptors_1native(
31         JNIEnv* env, jobject thiz, jstring deviceAddr) {
32     const char *deviceAddrStr = env->GetStringUTFChars(deviceAddr, NULL);
33     struct usb_device* device = usb_device_open(deviceAddrStr);
34     env->ReleaseStringUTFChars(deviceAddr, deviceAddrStr);
35 
36     if (!device) {
37         ALOGE("usb_device_open failed");
38         return NULL;
39     }
40 
41     int fd = usb_device_get_fd(device);
42     jbyteArray descriptors = usb_jni_read_descriptors(env, fd);
43     usb_device_close(device);
44     return descriptors;
45 }
46 
Java_com_android_server_usb_descriptors_UsbDescriptorParser_getDescriptorString_1native(JNIEnv * env,jobject thiz,jstring deviceAddr,jint stringId)47 jstring JNICALL Java_com_android_server_usb_descriptors_UsbDescriptorParser_getDescriptorString_1native(
48         JNIEnv* env, jobject thiz, jstring deviceAddr, jint stringId) {
49 
50     const char *deviceAddrStr = env->GetStringUTFChars(deviceAddr, NULL);
51     struct usb_device* device = usb_device_open(deviceAddrStr);
52     env->ReleaseStringUTFChars(deviceAddr, deviceAddrStr);
53 
54     if (!device) {
55         ALOGE("usb_device_open failed");
56         return NULL;
57     }
58 
59     int fd = usb_device_get_fd(device);
60     if (fd < 0) {
61         ALOGE("usb_device_get_fd failed");
62         usb_device_close(device);
63         return NULL;
64     }
65 
66     char* data = usb_device_get_string(device, stringId, USB_CONTROL_TRANSFER_TIMEOUT_MS);
67 
68     jstring j_str = NULL;
69 
70     if (data != NULL) {
71         j_str = env->NewStringUTF(data);
72         free(data);
73     }
74 
75     usb_device_close(device);
76 
77     return j_str;
78 }
79 
80 } // extern "C"
81