1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #ifndef LIBUSB_SERIAL_H 16 #define LIBUSB_SERIAL_H 17 18 #include <libusb.h> 19 #include <unordered_map> 20 #include <mutex> 21 #include <atomic> 22 #include <thread> 23 #include <string> 24 #include <vector> 25 26 #include "v1_0/serial_types.h" 27 28 namespace OHOS { 29 namespace HDI { 30 namespace Usb { 31 namespace Serial { 32 namespace V1_0 { 33 34 class LibusbSerial { 35 public: 36 static LibusbSerial &GetInstance(); 37 int32_t SerialOpen(int32_t num); 38 int32_t SerialClose(int32_t num); 39 int32_t SerialGetPortList(std::vector<SerialPort>& portIds); 40 int32_t SerialRead(int32_t portId, std::vector<uint8_t>& data, uint32_t size, uint32_t timeout); 41 int32_t SerialWrite(int32_t portId, const std::vector<uint8_t>& data, uint32_t size, uint32_t timeout); 42 int32_t SerialGetAttribute(int32_t portId, struct SerialAttribute& attribute); 43 int32_t SerialSetAttribute(int32_t portId, const struct SerialAttribute& attribute); 44 45 private: 46 // DeviceHandleInfo struct to hold device info 47 typedef struct DeviceHandleInfo { 48 int num; 49 libusb_device_handle* handle; 50 bool isOpen; 51 uint8_t outputEndpointAddr; 52 uint8_t intputEndpointAddr; 53 int32_t interface; 54 } DeviceHandleInfo; 55 56 LibusbSerial(); 57 ~LibusbSerial(); 58 int32_t GetApiVersion(); 59 int GetEndPoint(DeviceHandleInfo* deviceHandleInfo); 60 void EventHandlingThread(); 61 int32_t GetPortIdByDevice(libusb_device* device); 62 static int32_t HotplugCallback(libusb_context* ctx, libusb_device* device, 63 libusb_hotplug_event event, void* user_data); 64 int32_t HandleDeviceArrival(libusb_device* device); 65 void HandleDeviceRemoval(libusb_device* device); 66 libusb_device_handle* GetDeviceHandle(int portId); 67 libusb_device* GetDevice(int portId); 68 int32_t GetSerialDeviceInfo(libusb_device* device, libusb_device_handle* handle, DeviceInfo &deviceInfo); 69 void GetExistedDevices(); 70 71 private: 72 libusb_context* ctx_; 73 libusb_hotplug_callback_handle hotplug_handle_; 74 // Map devices by libusb_device* 75 std::unordered_map<libusb_device*, DeviceHandleInfo> devices_; 76 std::mutex map_mutex_; 77 std::mutex writeMutex_; 78 std::atomic<bool> running_; 79 std::thread event_thread_; 80 }; 81 } // V1_0 82 } // Serial 83 } // Usb 84 } // HDI 85 } // OHOS 86 87 #endif // LIBUSB_SERIAL_H