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, const char* uniq, int32_t vid,
46                                         int32_t pid, uint16_t bus,
47                                         const std::vector<uint8_t>& descriptor,
48                                         std::unique_ptr<DeviceCallback> callback);
49 
50     ~Device();
51 
52     void sendReport(const std::vector<uint8_t>& report) const;
53     void sendSetReportReply(uint32_t id, bool success) const;
54     void sendGetFeatureReportReply(uint32_t id, const std::vector<uint8_t>& report) const;
55     void close();
56     int handleEvents(int events);
57 
58 private:
59     Device(int32_t id, android::base::unique_fd fd, std::unique_ptr<DeviceCallback> callback);
60     int32_t mId;
61     android::base::unique_fd mFd;
62     std::unique_ptr<DeviceCallback> mDeviceCallback;
63 };
64 
65 
66 } // namespace uhid
67 } // namespace android
68