1 // Copyright 2015 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.
5 #include "device/usb/usb_service.h"
9 #include "base/memory/weak_ptr.h"
10 #include "base/single_thread_task_runner.h"
11 #include "device/usb/usb_context.h"
12 #include "device/usb/usb_device_impl.h"
13 #include "third_party/libusb/src/libusb/libusb.h"
17 typedef struct libusb_device
* PlatformUsbDevice
;
18 typedef struct libusb_context
* PlatformUsbContext
;
20 class UsbServiceImpl
: public UsbService
{
22 static UsbService
* Create(
23 scoped_refptr
<base::SingleThreadTaskRunner
> ui_task_runner
);
26 explicit UsbServiceImpl(
27 PlatformUsbContext context
,
28 scoped_refptr
<base::SingleThreadTaskRunner
> ui_task_runner
);
29 ~UsbServiceImpl() override
;
31 // device::UsbService implementation
32 scoped_refptr
<UsbDevice
> GetDeviceById(uint32 unique_id
) override
;
33 void GetDevices(std::vector
<scoped_refptr
<UsbDevice
>>* devices
) override
;
35 // Enumerate USB devices from OS and update devices_ map.
36 void RefreshDevices();
39 void RefreshDevicesIfWinUsbDevice(const std::string
& device_path
);
42 // Adds a new UsbDevice to the devices_ map based on the given libusb device.
43 scoped_refptr
<UsbDeviceImpl
> AddDevice(PlatformUsbDevice platform_device
);
45 // Handle hotplug events from libusb.
46 static int LIBUSB_CALL
HotplugCallback(libusb_context
* context
,
47 PlatformUsbDevice device
,
48 libusb_hotplug_event event
,
50 // These functions release a reference to the provided platform device.
51 void OnDeviceAdded(PlatformUsbDevice platform_device
);
52 void OnDeviceRemoved(PlatformUsbDevice platform_device
);
54 scoped_refptr
<UsbContext
> context_
;
55 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
56 scoped_refptr
<base::SingleThreadTaskRunner
> ui_task_runner_
;
60 UIThreadHelper
* ui_thread_helper_
;
63 // TODO(reillyg): Figure out a better solution for device IDs.
64 uint32 next_unique_id_
;
66 // When available the device list will be updated when new devices are
67 // connected instead of only when a full enumeration is requested.
68 // TODO(reillyg): Support this on all platforms. crbug.com/411715
69 bool hotplug_enabled_
;
70 libusb_hotplug_callback_handle hotplug_handle_
;
72 // The map from unique IDs to UsbDevices.
73 typedef std::map
<uint32
, scoped_refptr
<UsbDeviceImpl
>> DeviceMap
;
76 // The map from PlatformUsbDevices to UsbDevices.
77 typedef std::map
<PlatformUsbDevice
, scoped_refptr
<UsbDeviceImpl
>>
79 PlatformDeviceMap platform_devices_
;
81 base::WeakPtrFactory
<UsbServiceImpl
> weak_factory_
;
83 DISALLOW_COPY_AND_ASSIGN(UsbServiceImpl
);