1 /*
2  * Copyright (C) 2015 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 #include <android-base/unique_fd.h>
18 #include <jni.h>
19 
20 #include <memory>
21 #include <vector>
22 
23 namespace android {
24 namespace uhid {
25 
26 class DeviceCallback {
27 public:
28     DeviceCallback(JNIEnv* env, jobject callback);
29     ~DeviceCallback();
30 
31     void onDeviceOpen();
32     void onDeviceGetReport(uint32_t requestId, uint8_t reportId);
33     void onDeviceSetReport(uint32_t id, uint8_t rType, const std::vector<uint8_t>& data);
34     void onDeviceOutput(uint8_t rType, const std::vector<uint8_t>& data);
35     void onDeviceError();
36 
37 private:
38     JNIEnv* getJNIEnv();
39     jobject mCallbackObject;
40     JavaVM* mJavaVM;
41 };
42 
43 class Device {
44 public:
45     static std::unique_ptr<Device> open(int32_t id, const char* name, int32_t vid, int32_t pid,
46                                         uint16_t bus, const std::vector<uint8_t>& descriptor,
47                                         std::unique_ptr<DeviceCallback> callback);
48 
49     ~Device();
50 
51     void sendReport(const std::vector<uint8_t>& report) const;
52     void sendSetReportReply(uint32_t id, bool success) const;
53     void sendGetFeatureReportReply(uint32_t id, const std::vector<uint8_t>& report) const;
54     void close();
55     int handleEvents(int events);
56 
57 private:
58     Device(int32_t id, android::base::unique_fd fd, std::unique_ptr<DeviceCallback> callback);
59     int32_t mId;
60     android::base::unique_fd mFd;
61     std::unique_ptr<DeviceCallback> mDeviceCallback;
62 };
63 
64 
65 } // namespace uhid
66 } // namespace android
67