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 #pragma once 17 18 #include <functional> 19 #include <memory> 20 21 #include <stdint.h> 22 #include <libusb/libusb.h> 23 #include "common/libs/usbforward/protocol.h" 24 25 namespace usb_forward { 26 27 // TransportRequest represents a libusb asynchronous transport request. 28 // This class encapsulates everything that is necessary to complete 29 // transfer. 30 class TransportRequest final { 31 public: 32 // CallbackType describes what kind of function can receive call when this 33 // asynchronous call is complete. 34 // Parameters passed to callback, in order: 35 // - success indicator (true = success), 36 // - buffer with data (in or out), 37 // - actual length transferred. 38 using CallbackType = std::function<void(bool, const uint8_t*, int32_t)>; 39 40 TransportRequest(std::shared_ptr<libusb_device_handle> device, 41 CallbackType callback, const ControlTransfer& transfer); 42 TransportRequest(std::shared_ptr<libusb_device_handle> device, 43 CallbackType callback, const DataTransfer& transfer); 44 ~TransportRequest() = default; 45 46 uint8_t* Buffer(); 47 48 // Submit sends an asynchronous data exchange requests. 49 // Returns true only if operation was successful. At this point 50 // ownership of this structure is passed to libusb and user 51 // must not release the underlying structure. 52 bool Submit(); 53 54 // Executes corresponding callback with execution results. 55 // This is a static call to ensure that the callback being invoked 56 // can dispose of this instance. 57 static void OnTransferComplete(libusb_transfer* req); 58 59 private: 60 std::shared_ptr<libusb_device_handle> handle_; 61 CallbackType callback_; 62 bool is_control_; 63 std::unique_ptr<libusb_transfer, void (*)(libusb_transfer*)> transfer_; 64 std::unique_ptr<uint8_t[]> buffer_; 65 66 TransportRequest(const TransportRequest& other) = delete; 67 TransportRequest& operator=(const TransportRequest& other) = delete; 68 }; 69 70 } // namespace usb_forward 71