2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 using System.Collections.Generic;
21 namespace Tizen.System.Usb
24 /// USB Manager class.
26 public class UsbManager : IDisposable
28 private readonly Interop.UsbContextHandle _context;
29 private readonly Interop.HostHotplugHandle _hotpluggedHandle;
30 private List<UsbDevice> _devices = new List<UsbDevice>();
33 /// USB Manager Constructor.
37 _context = new Interop.UsbContextHandle();
38 _devices = _context.GetDeviceList().Select(devHandle => new UsbDevice(this, devHandle)).ToList();
39 _context.SetHotplugCb(HostHotplugCallback, Interop.HotplugEventType.Any,
40 IntPtr.Zero, out _hotpluggedHandle).ThrowIfFailed("Failed to set hot plugged callback");
44 /// This function returns list of USB devices attached to system.
46 /// <exception cref="NotSupportedException">Throws exception if USB host feature is not enabled.</exception>
47 /// <exception cref="OutOfMemoryException">Throws exception in case of insufficient memory.</exception>
48 /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
49 public IEnumerable<UsbDevice> AvailableDevices
59 /// Event handler for events when a USB device is attached or detached.
61 public event EventHandler<HotPluggedEventArgs> DeviceHotPlugged;
63 internal void HostHotplugCallback(IntPtr devHandle, IntPtr userData)
65 Interop.HostDeviceHandle handle = new Interop.HostDeviceHandle(devHandle);
66 UsbDevice device = _devices.Where(dev => dev._handle == handle).FirstOrDefault();
69 device = new UsbDevice(this, handle);
72 if (DeviceHotPlugged != null)
74 DeviceHotPlugged.Invoke(this, new HotPluggedEventArgs(device, HotplugEventType.Attach));
79 if (DeviceHotPlugged != null)
81 DeviceHotPlugged.Invoke(this, new HotPluggedEventArgs(device, HotplugEventType.Detach));
84 _devices.Remove(device);
85 // do we need to dispose device here ?
89 internal void ThrowIfDisposed()
91 if (disposedValue) throw new ObjectDisposedException("USB Context is already disposed");
94 #region IDisposable Support
95 private bool disposedValue = false;
97 protected virtual void Dispose(bool disposing)
101 _hotpluggedHandle.UnsetHotplugCb();
103 disposedValue = true;
112 public void Dispose()
115 GC.SuppressFinalize(this);