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();
38 // Adds a new UsbDevice to the devices_ map based on the given libusb device.
39 scoped_refptr
<UsbDeviceImpl
> AddDevice(PlatformUsbDevice platform_device
);
41 // Handle hotplug events from libusb.
42 static int LIBUSB_CALL
HotplugCallback(libusb_context
* context
,
43 PlatformUsbDevice device
,
44 libusb_hotplug_event event
,
46 // These functions release a reference to the provided platform device.
47 void OnDeviceAdded(PlatformUsbDevice platform_device
);
48 void OnDeviceRemoved(PlatformUsbDevice platform_device
);
50 scoped_refptr
<UsbContext
> context_
;
51 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
52 scoped_refptr
<base::SingleThreadTaskRunner
> ui_task_runner_
;
56 UIThreadHelper
* ui_thread_helper_
;
59 // TODO(reillyg): Figure out a better solution for device IDs.
60 uint32 next_unique_id_
;
62 // When available the device list will be updated when new devices are
63 // connected instead of only when a full enumeration is requested.
64 // TODO(reillyg): Support this on all platforms. crbug.com/411715
65 bool hotplug_enabled_
;
66 libusb_hotplug_callback_handle hotplug_handle_
;
68 // The map from unique IDs to UsbDevices.
69 typedef std::map
<uint32
, scoped_refptr
<UsbDeviceImpl
>> DeviceMap
;
72 // The map from PlatformUsbDevices to UsbDevices.
73 typedef std::map
<PlatformUsbDevice
, scoped_refptr
<UsbDeviceImpl
>>
75 PlatformDeviceMap platform_devices_
;
77 base::WeakPtrFactory
<UsbServiceImpl
> weak_factory_
;
79 DISALLOW_COPY_AND_ASSIGN(UsbServiceImpl
);