blob: 20581ab12a2a5c41f562a79973ea9cf45804e50b [file] [log] [blame]
Ben Chan4f6444a2013-05-29 13:21:37 -07001// Copyright (c) 2013 The Chromium OS 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 MIST_USB_MANAGER_H_
6#define MIST_USB_MANAGER_H_
7
8#include <base/basictypes.h>
Ben Chan3cb21b82013-05-29 17:01:16 -07009#include <base/compiler_specific.h>
Ben Chan4f6444a2013-05-29 13:21:37 -070010#include <base/memory/scoped_vector.h>
Ben Chan3cb21b82013-05-29 17:01:16 -070011#include <base/message_loop.h>
Ben Chan4f6444a2013-05-29 13:21:37 -070012
13#include "mist/usb_error.h"
14
15struct libusb_context;
16
17namespace mist {
18
Ben Chan3cb21b82013-05-29 17:01:16 -070019class EventDispatcher;
Ben Chan4f6444a2013-05-29 13:21:37 -070020class UsbDevice;
21
22// A USB manager for managing a USB session created by libusb 1.0.
Ben Chan3cb21b82013-05-29 17:01:16 -070023class UsbManager : public MessageLoopForIO::Watcher {
Ben Chan4f6444a2013-05-29 13:21:37 -070024 public:
Ben Chan3cb21b82013-05-29 17:01:16 -070025 // Constructs a UsbManager object by taking a raw pointer to an
26 // EventDispatcher as |dispatcher|. The ownership of |dispatcher| is not
27 // transferred, and thus it should outlive this object.
28 explicit UsbManager(EventDispatcher* dispatcher);
29
30 virtual ~UsbManager();
Ben Chan4f6444a2013-05-29 13:21:37 -070031
32 // Initializes a USB session via libusb. Returns true on success.
33 bool Initialize();
34
35 // Sets the debug level of libusb to |level|.
36 void SetDebugLevel(int level);
37
38 // Gets the list of USB devices currently attached to the system. Returns true
39 // on success. |devices| is always cleared before being updated. The returned
40 // UsbDevice objects become invalid, and thus should not be held, beyond the
41 // lifetime of this object.
42 bool GetDevices(ScopedVector<UsbDevice>* devices);
43
44 const UsbError& error() const { return error_; }
45
46 private:
Ben Chan3cb21b82013-05-29 17:01:16 -070047 static void OnPollFileDescriptorAdded(int file_descriptor,
48 short events, // NOLINT
49 void* user_data);
50 static void OnPollFileDescriptorRemoved(int file_descriptor, void* user_data);
51
52 // Starts watching the file descriptors for libusb events. Returns true on
53 // success.
54 bool StartWatchingPollFileDescriptors();
55
56 // Handles libusb events in non-blocking mode.
57 void HandleEventsNonBlocking();
58
59 // Implements MessageLoopForIO::Watcher.
60 virtual void OnFileCanReadWithoutBlocking(int file_descriptor) OVERRIDE;
61 virtual void OnFileCanWriteWithoutBlocking(int file_descriptor) OVERRIDE;
62
63 EventDispatcher* const dispatcher_;
Ben Chan4f6444a2013-05-29 13:21:37 -070064 libusb_context* context_;
65 UsbError error_;
66
67 DISALLOW_COPY_AND_ASSIGN(UsbManager);
68};
69
70} // namespace mist
71
72#endif // MIST_USB_MANAGER_H_