1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CHROME_BROWSER_USB_USB_SERVICE_H_ 6 #define CHROME_BROWSER_USB_USB_SERVICE_H_ 7 8 #include <map> 9 #include <utility> 10 #include <vector> 11 12 #include "base/basictypes.h" 13 #include "base/callback.h" 14 #include "base/memory/ref_counted.h" 15 #include "base/memory/singleton.h" 16 17 namespace base { 18 19 template <class T> class DeleteHelper; 20 21 } // namespace base 22 23 struct InitUsbContextTraits; 24 template <typename T> struct DefaultSingletonTraits; 25 26 typedef struct libusb_device* PlatformUsbDevice; 27 typedef struct libusb_context* PlatformUsbContext; 28 29 class UsbContext; 30 class UsbDevice; 31 32 // The USB service handles creating and managing an event handler thread that is 33 // used to manage and dispatch USB events. It is also responsible for device 34 // discovery on the system, which allows it to re-use device handles to prevent 35 // competition for the same USB device. 36 class UsbService { 37 public: 38 typedef scoped_ptr<std::vector<scoped_refptr<UsbDevice> > > 39 ScopedDeviceVector; 40 41 // Must be called on FILE thread. 42 // Returns NULL when failed to initialized. 43 static UsbService* GetInstance(); 44 45 scoped_refptr<UsbDevice> GetDeviceById(uint32 unique_id); 46 47 // Get all of the devices attached to the system, inserting them into 48 // |devices|. Clears |devices| before use. The result will be sorted by id 49 // in increasing order. Must be called on FILE thread. 50 void GetDevices(std::vector<scoped_refptr<UsbDevice> >* devices); 51 52 private: 53 friend struct InitUsbContextTraits; 54 friend struct DefaultSingletonTraits<UsbService>; 55 friend class base::DeleteHelper<UsbService>; 56 57 explicit UsbService(PlatformUsbContext context); 58 virtual ~UsbService(); 59 60 // Return true if |device|'s vendor and product identifiers match |vendor_id| 61 // and |product_id|. 62 static bool DeviceMatches(scoped_refptr<UsbDevice> device, 63 const uint16 vendor_id, 64 const uint16 product_id); 65 66 // Enumerate USB devices from OS and Update devices_ map. 67 void RefreshDevices(); 68 69 scoped_refptr<UsbContext> context_; 70 71 // TODO(ikarienator): Figure out a better solution. 72 uint32 next_unique_id_; 73 74 // The map from PlatformUsbDevices to UsbDevices. 75 typedef std::map<PlatformUsbDevice, scoped_refptr<UsbDevice> > DeviceMap; 76 DeviceMap devices_; 77 78 DISALLOW_COPY_AND_ASSIGN(UsbService); 79 }; 80 81 #endif // CHROME_BROWSER_USB_USB_SERVICE_H_ 82