Tizen.System.PlatformConfig.dll #common #mobile #mobile-emul #tv #ivi #wearable
Tizen.System.Storage.dll #common #mobile #mobile-emul #tv #ivi #wearable
Tizen.System.SystemSettings.dll #common #mobile #mobile-emul #tv #ivi #wearable
+Tizen.System.Usb.dll #common #mobile #mobile-emul
Tizen.Tapi.dll
Tizen.Telephony.dll #mobile #mobile-emul #ivi #wearable
Tizen.Tracer.dll #common #mobile #mobile-emul #tv #ivi #wearable
Tizen.System.MediaKey
Tizen.System.PlatformConfig
Tizen.System.Storage
+Tizen.System.Usb
Tizen.System.SystemSettings
Tizen.Telephony
Tizen.Tracer
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_set_config")]
+ internal static extern ErrorCode SetAsActive(this UsbConfigHandle /* usb_host_config_h */ configuration);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_config_get_num_interfaces")]
+ internal static extern ErrorCode GetNumInterfaces(this UsbConfigHandle /* usb_host_config_h */ config, out int numInterfaces);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_config_is_self_powered")]
+ internal static extern ErrorCode IsSelfPowered(this UsbConfigHandle /* usb_host_config_h */ config, out bool selfPowered);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_config_support_remote_wakeup")]
+ internal static extern ErrorCode SupportRemoteWakeup(this UsbConfigHandle /* usb_host_config_h */ config, out bool remoteWakeup);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_config_get_max_power")]
+ internal static extern ErrorCode GetMaxPower(this UsbConfigHandle /* usb_host_config_h */ config, out int maxPower);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_config_str")]
+ internal static extern ErrorCode GetConfigStr(this UsbConfigHandle /* usb_host_config_h */ config, ref int length, byte[] data);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_config_get_interface")]
+ internal static extern ErrorCode GetInterface(this UsbConfigHandle /* usb_host_config_h */ config, int interfaceIndex, out UsbInterfaceHandle /* usb_host_interface_h */ usbInterface);
+
+ internal class UsbConfigHandle : SafeUsbHandle
+ {
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_config_destroy")]
+ internal static extern ErrorCode ConfigDestroy(UsbConfigHandle /* usb_host_config_h */ config);
+
+ public UsbConfigHandle(IntPtr handle) : base(handle) { }
+ public override void Destroy()
+ {
+ ConfigDestroy(this).ThrowIfFailed("Failed to destroy native HostConfig handle");
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+internal static partial class Interop
+{
+ internal const int MaxStringDescriptorSize = 255;
+ internal const int MaxPortNumberCount = 8; // As per the USB 3.0 specs, the current maximum limit for the depth is 7
+ internal static partial class Libraries
+ {
+ public const string Usb = "libcapi-system-usbhost.so.0";
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal enum HotplugEventType
+ {
+ Attach, // USB_HOST_HOTPLUG_EVENT_ATTACH
+ Detach, // USB_HOST_HOTPLUG_EVENT_DETACH
+ Any, // USB_HOST_HOTPLUG_EVENT_ANY
+ }
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void HostHotplugCallback(IntPtr /* usb_host_device_h */ dev, IntPtr /* void */ userData);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_set_hotplug_cb")]
+ internal static extern ErrorCode SetHotplugCb(this UsbContextHandle /* usb_host_context_h */ ctx, HostHotplugCallback cb, HotplugEventType /* usb_host_hotplug_event_e */ hostEvent, IntPtr /* void */ userData, out HostHotplugHandle /* usb_host_hotplug_h */ handle);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_unset_hotplug_cb")]
+ internal static extern ErrorCode UnsetHotplugCb(this HostHotplugHandle /* usb_host_hotplug_h */ handle);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_get_device_list")]
+ internal static extern ErrorCode GetDeviceList(this UsbContextHandle /* usb_host_context_h */ ctx, out IntPtr /* usb_host_device_h */ devs, out int length);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_open_with_vid_pid")]
+ internal static extern ErrorCode OpenWithVidPid(this UsbContextHandle /* usb_host_context_h */ ctx, int vendorId, int productId, out HostDeviceHandle /* usb_host_device_h */ deviceHandle);
+
+ internal class UsbContextHandle : SafeUsbHandle
+ {
+ private IntPtr nativeDevListPtr = IntPtr.Zero;
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_create")]
+ internal static extern ErrorCode Create(out IntPtr /* usb_host_context_h */ ctx);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_destroy")]
+ internal static extern ErrorCode Destroy(UsbContextHandle /* usb_host_context_h */ ctx);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_free_device_list")]
+ internal static extern ErrorCode FreeDeviceList(IntPtr deviceList, bool unrefDevices);
+
+ internal UsbContextHandle()
+ {
+ Create(out handle).ThrowIfFailed("Failed to create native context handle");
+ }
+
+ public override void Destroy()
+ {
+ if (nativeDevListPtr != IntPtr.Zero)
+ {
+ FreeDeviceList(nativeDevListPtr, true).ThrowIfFailed("Failed to free native device list");
+ nativeDevListPtr = IntPtr.Zero;
+ }
+ Destroy(this).ThrowIfFailed("Failed to destroy native context handle");
+ }
+
+ internal List<HostDeviceHandle> GetDeviceList()
+ {
+ if (nativeDevListPtr != IntPtr.Zero)
+ {
+ FreeDeviceList(nativeDevListPtr, true).ThrowIfFailed("Failed to free native device list");
+ nativeDevListPtr = IntPtr.Zero;
+ }
+
+ int length;
+ ErrorCode err = this.GetDeviceList(out nativeDevListPtr, out length);
+ err.ThrowIfFailed("Failed to get device list for the context");
+
+ List<HostDeviceHandle> deviceList = new List<HostDeviceHandle>();
+ IntPtr[] nativeDevList = new IntPtr[length];
+ Marshal.Copy(nativeDevListPtr, nativeDevList, 0, length);
+
+ foreach (var devHandle in nativeDevList)
+ {
+ deviceList.Add(new HostDeviceHandle(devHandle));
+ }
+
+ return deviceList;
+ }
+ }
+
+ internal class HostHotplugHandle
+ {
+ private IntPtr _handle;
+ public HostHotplugHandle(IntPtr handle) { _handle = handle; }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_ref_device")]
+ internal static extern ErrorCode RefDevice(this HostDeviceHandle /* usb_host_device_h */ dev);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_unref_device")]
+ internal static extern ErrorCode UnrefDevice(this HostDeviceHandle /* usb_host_device_h */ dev);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_open")]
+ internal static extern ErrorCode Open(this HostDeviceHandle /* usb_host_device_h */ dev);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_close")]
+ internal static extern ErrorCode Close(this HostDeviceHandle /* usb_host_device_h */ dev);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_bus_number")]
+ internal static extern ErrorCode GetBusNumber(this HostDeviceHandle /* usb_host_device_h */ dev, out int busNumber);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_address")]
+ internal static extern ErrorCode GetAddress(this HostDeviceHandle /* usb_host_device_h */ dev, out int deviceAddress);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_port_numbers")]
+ internal static extern ErrorCode GetPortNumbers(this HostDeviceHandle /* usb_host_device_h */ dev, [MarshalAs(UnmanagedType.SysInt, SizeParamIndex = 2)] [In, Out] int[] portNumbers, int portNumbersLen, out int portsCount);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_config")]
+ internal static extern ErrorCode GetConfig(this HostDeviceHandle /* usb_host_device_h */ dev, int configIndex, out UsbConfigHandle /* usb_host_config_h */ config);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_get_active_config")]
+ internal static extern ErrorCode GetActiveConfig(this HostDeviceHandle /* usb_host_device_h */ dev, out UsbConfigHandle /* usb_host_config_h */ config);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_bcd_usb")]
+ internal static extern ErrorCode GetBcdUsb(this HostDeviceHandle /* usb_host_device_h */ dev, out int bcdUsb);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_class")]
+ internal static extern ErrorCode GetClass(this HostDeviceHandle /* usb_host_device_h */ dev, out int deviceClass);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_sub_class")]
+ internal static extern ErrorCode GetSubClass(this HostDeviceHandle /* usb_host_device_h */ dev, out int subclass);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_protocol")]
+ internal static extern ErrorCode GetProtocol(this HostDeviceHandle /* usb_host_device_h */ dev, out int protocol);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_max_packet_size_0")]
+ internal static extern ErrorCode GetMaxPacketSize0(this HostDeviceHandle /* usb_host_device_h */ dev, out int maxPacketSize);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_id_vendor")]
+ internal static extern ErrorCode GetIdVendor(this HostDeviceHandle /* usb_host_device_h */ dev, out int vendorId);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_id_product")]
+ internal static extern ErrorCode GetIdProduct(this HostDeviceHandle /* usb_host_device_h */ dev, out int productId);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_bcd_device")]
+ internal static extern ErrorCode GetBcdDevice(this HostDeviceHandle /* usb_host_device_h */ dev, out int deviceBcd);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_num_configurations")]
+ internal static extern ErrorCode GetNumConfigurations(this HostDeviceHandle /* usb_host_device_h */ dev, out int numConfigurations);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_is_device_opened")]
+ internal static extern ErrorCode IsOpened(this HostDeviceHandle /* usb_host_device_h */ dev, out bool isOpened);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_manufacturer_str")]
+ internal static extern ErrorCode GetManufacturerStr(this HostDeviceHandle /* usb_host_device_h */ dev, ref int length, byte[] data);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_product_str")]
+ internal static extern ErrorCode GetProductStr(this HostDeviceHandle /* usb_host_device_h */ dev, ref int length, byte[] data);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_device_get_serial_number_str")]
+ internal static extern ErrorCode GetSerialNumberStr(this HostDeviceHandle /* usb_host_device_h */ dev, ref int length, byte[] data);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_control_transfer")]
+ internal static extern ErrorCode ControlTransfer(this HostDeviceHandle /* usb_host_device_h */ dev, byte requestType, byte request, ushort value, ushort index, byte[] data, ushort length, uint timeout, out int transferred);
+
+ internal class HostDeviceHandle : SafeUsbHandle
+ {
+ internal HostDeviceHandle(IntPtr handle) : base(handle) { }
+
+ public override void Destroy()
+ {
+ //this.UnrefDevice();
+ }
+
+ internal IEnumerable<int> Ports()
+ {
+ int actualPortsCount;
+ int[] portList = new int[MaxPortNumberCount];
+ var err = this.GetPortNumbers(portList, portList.Length, out actualPortsCount);
+ err.ThrowIfFailed("Failed to get device port list");
+ return portList.Take(actualPortsCount);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal enum EndpointDirection
+ {
+ In, // USB_HOST_DIRECTION_IN
+ Out, // USB_HOST_DIRECTION_OUT
+ InOut,
+ }
+
+ internal enum TransferType
+ {
+ Control, // USB_HOST_TRANSFER_TYPE_CONTROL
+ Isochronous, // USB_HOST_TRANSFER_TYPE_ISOCHRONOUS
+ Bulk, // USB_HOST_TRANSFER_TYPE_BULK
+ Interrupt, // USB_HOST_TRANSFER_TYPE_INTERRUPT
+ }
+
+ internal enum SynchronizationType
+ {
+ None, // USB_HOST_ISO_SYNC_TYPE_NONE
+ Async, // USB_HOST_ISO_SYNC_TYPE_ASYNC
+ Adaptive, // USB_HOST_ISO_SYNC_TYPE_ADAPTIVE
+ Sync, // USB_HOST_ISO_SYNC_TYPE_SYNC
+ }
+
+ internal enum UsageType
+ {
+ Data, // USB_HOST_USAGE_TYPE_DATA
+ Feedback, // USB_HOST_USAGE_TYPE_FEEDBACK
+ Implicit, // USB_HOST_USAGE_TYPE_IMPLICIT
+ }
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_endpoint_get_number")]
+ internal static extern ErrorCode GetNumber(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, out int number);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_endpoint_get_direction")]
+ internal static extern ErrorCode GetDirection(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, out EndpointDirection /* usb_host_endpoint_direction_e */ direction);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_endpoint_get_transfer_type")]
+ internal static extern ErrorCode GetTransferType(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, out TransferType /* usb_host_transfer_type_e */ transferType);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_endpoint_get_synch_type")]
+ internal static extern ErrorCode GetSynchType(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, out SynchronizationType /* usb_host_iso_sync_type_e */ synchType);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_endpoint_get_usage_type")]
+ internal static extern ErrorCode GetUsageType(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, out UsageType /* usb_host_usage_type_e */ usageType);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_endpoint_get_max_packet_size")]
+ internal static extern ErrorCode GetMaxPacketSize(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, out int maxPacketSize);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_endpoint_get_interval")]
+ internal static extern ErrorCode GetInterval(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, out int interval);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_transfer")]
+ internal static extern ErrorCode Transfer(this UsbEndpointHandle /* usb_host_endpoint_h */ ep, byte[] data, int length, out int transferred, uint timeout);
+
+ internal class UsbEndpointHandle
+ {
+ private IntPtr _handle;
+ public UsbEndpointHandle(IntPtr handle){ _handle = handle; }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Runtime.CompilerServices;
+using Tizen;
+
+internal static partial class Interop
+{
+ internal enum ErrorCode
+ {
+ None = Tizen.Internals.Errors.ErrorCode.None,
+ IoError = Tizen.Internals.Errors.ErrorCode.IoError,
+ InvalidParameter = Tizen.Internals.Errors.ErrorCode.InvalidParameter,
+ PermissionDenied = Tizen.Internals.Errors.ErrorCode.PermissionDenied,
+ NoSuchDevice = Tizen.Internals.Errors.ErrorCode.NoSuchDevice,
+ ResourceBusy = Tizen.Internals.Errors.ErrorCode.ResourceBusy,
+ TimedOut = Tizen.Internals.Errors.ErrorCode.TimedOut,
+ BrokenPipe = Tizen.Internals.Errors.ErrorCode.BrokenPipe,
+ InterruptedSysCall = Tizen.Internals.Errors.ErrorCode.InterruptedSysCall,
+ OutOfMemory = Tizen.Internals.Errors.ErrorCode.OutOfMemory,
+ NotSupported = Tizen.Internals.Errors.ErrorCode.NotSupported,
+ Unknown = Tizen.Internals.Errors.ErrorCode.Unknown,
+
+ NotFound = -0x024B0000 | 0x01, // USB_HOST_ERROR_NOT_FOUND,
+ Overflow = -0x024B0000 | 0x02, // USB_HOST_ERROR_OVERFLOW
+ DeviceNotOpened = -0x024B0000 | 0x03, // USB_HOST_ERROR_DEVICE_NOT_OPENED
+ }
+}
+
+internal static class ErrorCodeExtensions
+{
+ private const string LogTag = "Tizen.System.Usb";
+
+ internal static bool IsSuccess(this Interop.ErrorCode err)
+ {
+ return err == Interop.ErrorCode.None;
+ }
+
+ internal static bool IsFailed(this Interop.ErrorCode err)
+ {
+ return !err.IsSuccess();
+ }
+
+ /// <summary>
+ /// Utility method to check for error, returns false if failed and print warning messages
+ /// </summary>
+ /// <returns>true in case of no error, false otherwise</returns>
+ internal static bool WarnIfFailed(this Interop.ErrorCode err, string msg, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0)
+ {
+ if (err.IsFailed())
+ {
+ Log.Debug(LogTag, $"{msg}, err: {err.ToString()}", file, func, line);
+ return false;
+ }
+ return true;
+ }
+
+ /// <summary>
+ /// Utility method to check for error, returns false if failed and throw exception
+ /// </summary>
+ /// <returns>true in case of no error</returns>
+ internal static bool ThrowIfFailed(this Interop.ErrorCode err, string msg, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0)
+ {
+ if (err.IsFailed())
+ {
+ Log.Error(LogTag, $"{msg}, err: {err.ToString()}", file, func, line);
+ throw err.GetException(msg);
+ }
+ return true;
+ }
+
+ internal static Exception GetException(this Interop.ErrorCode err, string message)
+ {
+ string errMessage = $"{message}, err: {err.ToString()}";
+ switch (err)
+ {
+ //case Interop.ErrorCode.None:
+ case Interop.ErrorCode.PermissionDenied:
+ return new UnauthorizedAccessException(errMessage);
+ case Interop.ErrorCode.InvalidParameter:
+ return new ArgumentException(errMessage);
+ case Interop.ErrorCode.TimedOut:
+ return new TimeoutException(errMessage);
+ case Interop.ErrorCode.OutOfMemory:
+ return new OutOfMemoryException(errMessage);
+ case Interop.ErrorCode.NotSupported:
+ return new NotSupportedException(errMessage);
+
+ case Interop.ErrorCode.IoError:
+ case Interop.ErrorCode.NoSuchDevice:
+ case Interop.ErrorCode.ResourceBusy:
+ case Interop.ErrorCode.BrokenPipe:
+ case Interop.ErrorCode.InterruptedSysCall:
+ case Interop.ErrorCode.Unknown:
+
+ case Interop.ErrorCode.NotFound:
+ case Interop.ErrorCode.Overflow:
+ case Interop.ErrorCode.DeviceNotOpened:
+
+ default: return new InvalidOperationException(errMessage);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_claim_interface")]
+ internal static extern ErrorCode ClaimInterface(this UsbInterfaceHandle /* usb_host_interface_h */ usbInterface, bool force);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_release_interface")]
+ internal static extern ErrorCode ReleaseInterface(this UsbInterfaceHandle /* usb_host_interface_h */ usbInterface);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_interface_get_number")]
+ internal static extern ErrorCode GetNumber(this UsbInterfaceHandle /* usb_host_interface_h */ usbInterface, out int number);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_interface_get_num_endpoints")]
+ internal static extern ErrorCode GetNumEndpoints(this UsbInterfaceHandle /* usb_host_interface_h */ usbInterface, out int numEndpoints);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_interface_get_endpoint")]
+ internal static extern ErrorCode GetEndpoint(this UsbInterfaceHandle /* usb_host_interface_h */ usbInterface, int epIndex, out UsbEndpointHandle /* usb_host_endpoint_h */ ep);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_interface_set_altsetting")]
+ internal static extern ErrorCode SetAltsetting(this UsbInterfaceHandle /* usb_host_interface_h */ usbInterface, int altsetting);
+
+ [DllImport(Libraries.Usb, EntryPoint = "usb_host_interface_get_str")]
+ internal static extern ErrorCode GetStr(this UsbInterfaceHandle /* usb_host_interface_h */ usbInterface, ref int length, byte[] data);
+
+
+ internal class UsbInterfaceHandle
+ {
+ private IntPtr _handle;
+ public UsbInterfaceHandle(IntPtr handle) { _handle = handle; }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+
+internal static partial class Interop
+{
+ public delegate ErrorCode GetterMethod<T>(out T value);
+ public delegate ErrorCode GetterPtrMethod(out IntPtr value);
+ public delegate ErrorCode GetDescriptorString(ref int length, byte[] data);
+ public delegate ErrorCode SetterMethod<T>(T value);
+
+ internal static T NativeGet<T>(GetterMethod<T> getter, [CallerMemberName] string propertyName = "")
+ {
+ T value;
+ var err = getter(out value);
+ if (err.IsSuccess())
+ {
+ return value;
+ }
+
+ err.ThrowIfFailed($"Native getter for {propertyName} failed");
+ return default(T);
+ }
+
+ internal static string DescriptorString(GetDescriptorString getter, string language = "us-ascii", [CallerMemberName] string propertyName = "")
+ {
+ int len = MaxStringDescriptorSize;
+ byte[] data = new byte[len];
+ getter(ref len, data).ThrowIfFailed($"Native setter for {propertyName} failed");
+ return Encoding.GetEncoding(language).GetString(data, 0, len);
+ }
+
+ internal static void NativeSet<T>(SetterMethod<T> setter, T value, [CallerMemberName] string propertyName = "")
+ {
+ setter(value).ThrowIfFailed($"Native setter for {propertyName} failed");
+ }
+
+ internal abstract class SafeUsbHandle : SafeHandle
+ {
+ public abstract void Destroy();
+ public SafeUsbHandle() : base(IntPtr.Zero, true) { }
+ public SafeUsbHandle(IntPtr handle) : base(handle, true) { }
+ public override bool IsInvalid { get { return handle == IntPtr.Zero; } }
+ protected override bool ReleaseHandle()
+ {
+ Destroy();
+ SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+}
--- /dev/null
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Tizen\Tizen.csproj" />
+ <ProjectReference Include="..\Tizen.Log\Tizen.Log.csproj" />
+ </ItemGroup>
+
+</Project>
--- /dev/null
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.26730.12
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tizen.System.Usb", "Tizen.System.Usb.csproj", "{BD16760E-860F-4A33-B6BD-3D623D790B8A}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tizen", "..\Tizen\Tizen.csproj", "{820488D0-54EB-4E52-9B22-CD3D3F201197}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tizen.Log", "..\Tizen.Log\Tizen.Log.csproj", "{FBB9D5C4-FD76-496E-B4AE-C42FEC10CE31}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {BD16760E-860F-4A33-B6BD-3D623D790B8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {BD16760E-860F-4A33-B6BD-3D623D790B8A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {BD16760E-860F-4A33-B6BD-3D623D790B8A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {BD16760E-860F-4A33-B6BD-3D623D790B8A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {820488D0-54EB-4E52-9B22-CD3D3F201197}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {820488D0-54EB-4E52-9B22-CD3D3F201197}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {820488D0-54EB-4E52-9B22-CD3D3F201197}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {820488D0-54EB-4E52-9B22-CD3D3F201197}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FBB9D5C4-FD76-496E-B4AE-C42FEC10CE31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FBB9D5C4-FD76-496E-B4AE-C42FEC10CE31}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FBB9D5C4-FD76-496E-B4AE-C42FEC10CE31}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FBB9D5C4-FD76-496E-B4AE-C42FEC10CE31}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {7AD16E0C-813B-4304-9356-B8282AF4224E}
+ EndGlobalSection
+EndGlobal
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Enumeration of transfer direction for Endpoints.
+ /// </summary>
+ public enum EndpointDirection
+ {
+ /// <summary>
+ /// IN direction
+ /// </summary>
+ In = Interop.EndpointDirection.In,
+ /// <summary>
+ /// OUT direction
+ /// </summary>
+ Out = Interop.EndpointDirection.Out,
+ /// <summary>
+ /// Bi-directional
+ /// </summary>
+ InOut = Interop.EndpointDirection.InOut,
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Event arguments for Hot Plugged event for USB devices.
+ /// </summary>
+ public class HotPluggedEventArgs : EventArgs
+ {
+ internal HotPluggedEventArgs(UsbDevice device, HotplugEventType type)
+ {
+ Device = device;
+ EventType = type;
+ }
+
+ /// <summary>
+ /// USB Device
+ /// </summary>
+ public UsbDevice Device { get; }
+
+ /// <summary>
+ /// Event Type
+ /// </summary>
+ public HotplugEventType EventType { get; }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Enumeration of hot plugged event type for USB devices.
+ /// </summary>
+ public enum HotplugEventType
+ {
+ /// <summary>
+ /// USB device is attached
+ /// </summary>
+ Attach = Interop.HotplugEventType.Attach,
+ /// <summary>
+ /// USB device is detached
+ /// </summary>
+ Detach = Interop.HotplugEventType.Detach,
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Enumeration of isochronous endpoint's synchronization type.
+ /// </summary>
+ public enum SynchronizationType
+ {
+ /// <summary>
+ /// Asynchronous
+ /// </summary>
+ Asynchronous = Interop.SynchronizationType.Async,
+ /// <summary>
+ /// Adaptive
+ /// </summary>
+ Adaptive = Interop.SynchronizationType.Adaptive,
+ /// <summary>
+ /// Synchronous
+ /// </summary>
+ Synchronous = Interop.SynchronizationType.Sync,
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Enumeration of an endpoint's usage type.
+ /// </summary>
+ public enum UsageType
+ {
+ /// <summary>
+ /// Data endpoint
+ /// </summary>
+ Data = Interop.UsageType.Data,
+ /// <summary>
+ /// Feedback endpoint
+ /// </summary>
+ Feedback = Interop.UsageType.Feedback,
+ /// <summary>
+ /// Implicit feedback Data endpoint
+ /// </summary>
+ Implicit = Interop.UsageType.Implicit,
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// USB Bulk Endpoint class.
+ /// </summary>
+ public class UsbBulkEndpoint : UsbEndpoint
+ {
+ internal UsbBulkEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle) : base(parent, handle)
+ {
+ }
+
+ /// <summary>
+ /// Performs a USB transfer on given endpoint. Direction of transfer is determined by the endpoint.
+ /// </summary>
+ /// <param name="buffer">Suitably-sized data buffer for either input or output (depending on endpoint).</param>
+ /// <param name="length">
+ /// For writes, the number of bytes from data to be sent, for reads the maximum number of bytes to receive
+ /// into the data buffer.
+ /// </param>
+ /// <param name="timeout">
+ /// Time (in milliseconds) that this function should wait for before giving up due to no response being
+ /// received(for an unlimited timeout 0 value should be used).
+ /// </param>
+ /// <returns>Number of bytes actually transferred.</returns>
+ /// <exception cref="InvalidOperationException">Throws exception if device is disconnected or not opened for operation.</exception>
+ /// <exception cref="TimeoutException">Throws exception if transfer timed-out.</exception>
+ public int Transfer(byte[] buffer, int length, uint timeout)
+ {
+ return TransferImpl(buffer, length, timeout);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+using System;
+using System.Collections.Generic;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Class to manage USB Configuration.
+ /// </summary>
+ public class UsbConfiguration : IDisposable
+ {
+ internal readonly Interop.UsbConfigHandle _handle;
+ private readonly UsbDevice _parent;
+ private Dictionary<int, UsbInterface> _interfaces;
+
+ internal UsbConfiguration(UsbDevice parent, Interop.UsbConfigHandle handle)
+ {
+ _parent = parent;
+ _handle = handle;
+ }
+
+ /// <summary>
+ /// Checks if device is self-powered in given configuration.
+ /// </summary>
+ public bool IsSelfPowered
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<bool>(_handle.IsSelfPowered);
+ }
+ }
+
+ /// <summary>
+ /// Checks if device in given configuration supports remote wakeup.
+ /// </summary>
+ public bool SupportRemoteWakeup
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<bool>(_handle.SupportRemoteWakeup);
+ }
+ }
+
+ /// <summary>
+ /// Gets maximum power required in given configuration, in mA.
+ /// </summary>
+ public int MaximumPowerRequired
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<int>(_handle.GetMaxPower);
+ }
+ }
+
+ /// <summary>
+ /// Dictionary mapping interfaces Ids to interface instances for given configuration.
+ /// </summary>
+ public IReadOnlyDictionary<int, UsbInterface> Interfaces
+ {
+ get
+ {
+ ThrowIfDisposed();
+ if (_interfaces == null)
+ {
+ _interfaces = new Dictionary<int, UsbInterface>();
+ int count = Interop.NativeGet<int>(_handle.GetNumInterfaces);
+ for (int i = 0; i < count; ++i)
+ {
+ Interop.UsbInterfaceHandle handle;
+ _handle.GetInterface(i, out handle);
+ UsbInterface usbInterface = new UsbInterface(this, handle);
+ _interfaces.Add(usbInterface.Id, usbInterface);
+ }
+ }
+ return _interfaces;
+ }
+ }
+
+ /// <summary>
+ /// Configuration string.
+ /// </summary>
+ public string ConfigurationString
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.DescriptorString(_handle.GetConfigStr);
+ }
+ }
+
+ /// <summary>
+ /// Set this configuration as active configuration for the device.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">
+ /// Throws exception if device is disconnected or not opened for operation or busy as its interfaces are currently claimed.
+ /// </exception>
+ public void SetAsActive()
+ {
+ ThrowIfDisposed();
+ _handle.SetAsActive();
+ }
+
+ internal void ThrowIfDisposed()
+ {
+ if (disposedValue) throw new ObjectDisposedException("Configuration is already disposed");
+ _parent.ThrowIfDisposed();
+ }
+
+ #region IDisposable Support
+ private bool disposedValue = false;
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!disposedValue)
+ {
+ _handle.Dispose();
+ disposedValue = true;
+ }
+ }
+
+ ~UsbConfiguration()
+ {
+ Dispose(false);
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+ #endregion
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// USB Control Endpoint class.
+ /// </summary>
+ public class UsbControlEndpoint : UsbEndpoint
+ {
+ private readonly UsbDevice _device;
+
+ internal UsbControlEndpoint(UsbDevice device) : base(null, null)
+ {
+ _device = device;
+ }
+
+ /// <summary>
+ /// Gets number of this endpoint.
+ /// </summary>
+ public new int Id
+ {
+ get
+ {
+ return 0;
+ }
+ }
+
+ /// <summary>
+ /// Gets direction of this endpoint.
+ /// </summary>
+ public new EndpointDirection Direction
+ {
+ get
+ {
+ return EndpointDirection.InOut;
+ }
+ }
+
+ /// <summary>
+ /// Gets max packet size of given endpoint.
+ /// </summary>
+ public new int MaxPacketSize
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetMaxPacketSize0);
+ }
+ }
+
+ /// <summary>
+ /// Performs a control transaction on endpoint zero for this device.
+ /// </summary>
+ /// <param name="requestType">bmRequestType type field for the setup packet.</param>
+ /// <param name="request">bRequest field for the setup packet.</param>
+ /// <param name="value">wValue field for the setup packet.</param>
+ /// <param name="index">wIndex field for the setup packet.</param>
+ /// <param name="data">Suitably-sized data buffer for either input or output, (depending on direction bits within bmRequestType).</param>
+ /// <param name="length">wLength field for the setup packet. The data buffer should be at least this size.</param>
+ /// <param name="timeout">
+ /// Time (in milliseconds) that this function should wait for, before giving up due to no response being received
+ /// (for an unlimited timeout 0 value should be used).
+ /// </param>
+ /// <returns>Transferred Number of transferred bytes.</returns>
+ /// <exception cref="InvalidOperationException">Throws exception if device is disconnected or not opened for operation.</exception>
+ /// <exception cref="TimeoutException">Throws exception if transfer timed-out.</exception>
+ public int Transfer(byte requestType, byte request, ushort value, ushort index, byte[] data, ushort length, uint timeout)
+ {
+ _device.ThrowIfDisposed();
+ if (_device.IsOpened == false) throw new InvalidOperationException("Device must be opened for operation first");
+
+ int transferred;
+ var err = _device._handle.ControlTransfer(requestType, request, value, index, data, length, timeout, out transferred);
+ err.ThrowIfFailed("Failed during control transfer");
+ return transferred;
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Class to manage USB host devices. This class contains operations for enumerating, opening and closing devices.
+ /// </summary>
+ public class UsbDevice : IDisposable
+ {
+ internal readonly Interop.HostDeviceHandle _handle;
+ private readonly UsbManager _parent;
+ private Dictionary<int, UsbConfiguration> _configurations;
+
+ internal UsbDevice(UsbManager parent, Interop.HostDeviceHandle handle)
+ {
+ _parent = parent;
+ _handle = handle;
+ }
+
+ /// <summary>
+ /// Number of the bus, this device is connected to.
+ /// </summary>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public int BusId {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<int>(_handle.GetBusNumber);
+ }
+ }
+
+ /// <summary>
+ /// Address of device on the bus.
+ /// </summary>
+ public int Address
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<int>(_handle.GetAddress);
+ }
+ }
+
+ /// <summary>
+ /// List of available port numbers from a device.
+ /// </summary>
+ public IEnumerable<int> Ports
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return _handle.Ports();
+ }
+ }
+
+ /// <summary>
+ /// Checks if device is opened.
+ /// </summary>
+ public bool IsOpened
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<bool>(_handle.IsOpened);
+ }
+ }
+
+ /// <summary>
+ /// Control endpoint (endpoint 0).
+ /// </summary>
+ public UsbControlEndpoint ControlEndpoint
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return new UsbControlEndpoint(this);
+ }
+ }
+
+ /// <summary>
+ /// Active configuration for the device.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">Throws exception if device is disconnected.</exception>
+ public UsbConfiguration ActiveConfiguration
+ {
+ get
+ {
+ ThrowIfDisposed();
+ Interop.UsbConfigHandle configHandle = Interop.NativeGet<Interop.UsbConfigHandle>(_handle.GetActiveConfig);
+ return _configurations.Values.Where(config => config._handle == configHandle).First();
+ }
+ }
+
+ /// <summary>
+ /// Dictionary mapping configuration Ids to configuration instances for this device.
+ /// </summary>
+ public IReadOnlyDictionary<int, UsbConfiguration> Configurations
+ {
+ get
+ {
+ ThrowIfDisposed();
+ if (_configurations == null)
+ {
+ _configurations = new Dictionary<int, UsbConfiguration>();
+ int count = Interop.NativeGet<int>(_handle.GetNumConfigurations);
+ for (int i = 0; i < count; ++i)
+ {
+ Interop.UsbConfigHandle configHandle;
+ _handle.GetConfig(i, out configHandle);
+ _configurations.Add(i, new UsbConfiguration(this, configHandle));
+ }
+ }
+ return _configurations;
+ }
+ }
+
+ /// <summary>
+ /// Device information such as version, class, subclass etc.
+ /// </summary>
+ public UsbDeviceInformation DeviceInformation
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return new UsbDeviceInformation(this);
+ }
+ }
+
+ /// <summary>
+ /// String associated with device.
+ /// </summary>
+ public UsbDeviceStrings Strings
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return new UsbDeviceStrings(this, "us-ascii");
+ }
+ }
+
+ /// <summary>
+ /// Opens device, which allows performing operations on it.
+ /// </summary>
+ /// <exception cref="OutOfMemoryException">Throws exception in case of insufficient memory.</exception>
+ /// <exception cref="InvalidOperationException">Throws exception if device is disconnected.</exception>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public void Open()
+ {
+ ThrowIfDisposed();
+ _handle.Open().ThrowIfFailed("Failed to open device for use");
+ }
+
+ /// <summary>
+ /// Closes device for operations.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">Throws exception if device is not opened for operation.</exception>
+ public void Close()
+ {
+ ThrowIfDisposed();
+ if (IsOpened == false) throw new InvalidOperationException("Device must be opened for operation first");
+
+ _handle.Close();
+ }
+
+ internal void ThrowIfDisposed()
+ {
+ if (disposedValue) throw new ObjectDisposedException("USB Device is already disposed");
+ _parent.ThrowIfDisposed();
+ }
+
+ #region IDisposable Support
+ private bool disposedValue = false;
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!disposedValue)
+ {
+ if (IsOpened)
+ {
+ Close();
+ }
+ foreach(var config in _configurations.Values) {
+ config.Dispose();
+ }
+ _configurations.Clear();
+ _handle.Dispose();
+ disposedValue = true;
+ }
+ }
+
+ ~UsbDevice()
+ {
+ Dispose(false);
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+ #endregion
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Device information for USB device.
+ /// </summary>
+ public class UsbDeviceInformation
+ {
+ private readonly UsbDevice _device;
+
+ internal UsbDeviceInformation(UsbDevice device)
+ {
+ _device = device;
+ }
+
+ /// <summary>
+ /// USB specification release number as binary-coded decimal.
+ /// </summary>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public int UsbVersion
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetBcdUsb);
+ }
+ }
+
+ /// <summary>
+ /// Gets device class.
+ /// </summary>
+ public int Class
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetClass);
+ }
+ }
+
+ /// <summary>
+ /// Gets device sub class.
+ /// </summary>
+ public int Subclass
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetSubClass);
+ }
+ }
+
+ /// <summary>
+ /// Gets device protocol.
+ /// </summary>
+ public int Protocol
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetProtocol);
+ }
+ }
+
+ /// <summary>
+ /// Gets vendor id.
+ /// </summary>
+ public int VendorId
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetIdVendor);
+ }
+ }
+
+ /// <summary>
+ /// Gets product id.
+ /// </summary>
+ public int ProductId
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetIdProduct);
+ }
+ }
+
+ /// <summary>
+ /// Gets device release number in binary-coded decimal.
+ /// </summary>
+ public int DeviceVersion
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.NativeGet<int>(_device._handle.GetBcdDevice);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// String information for USB device.
+ /// </summary>
+ public class UsbDeviceStrings
+ {
+ private readonly UsbDevice _device;
+ private string _language;
+
+ internal UsbDeviceStrings(UsbDevice device, string language)
+ {
+ _device = device;
+ _language = language;
+ }
+
+ /// <summary>
+ /// Gets string describing device manufacturer.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">Throws exception if device is disconnected or not opened for operation.</exception>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public string Manufacturer
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.DescriptorString(_device._handle.GetManufacturerStr, _language);
+ }
+ }
+
+ /// <summary>
+ /// Gets product string of device
+ /// </summary>
+ /// <exception cref="InvalidOperationException">Throws exception if device is not opened for operation.</exception>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public string Product
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.DescriptorString(_device._handle.GetProductStr, _language);
+ }
+ }
+
+ /// <summary>
+ /// Gets serial number of a device.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">Throws exception if device is not opened for operation.</exception>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public string Serial
+ {
+ get
+ {
+ _device.ThrowIfDisposed();
+ return Interop.DescriptorString(_device._handle.GetSerialNumberStr, _language);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// USB Endpoint class.
+ /// </summary>
+ public class UsbEndpoint
+ {
+ internal readonly Interop.UsbEndpointHandle _handle;
+ protected readonly UsbInterface _parent;
+
+ internal UsbEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle)
+ {
+ _parent = parent;
+ _handle = handle;
+ }
+
+ /// <summary>
+ /// Gets number of this endpoint.
+ /// </summary>
+ public int Id
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<int>(_handle.GetNumber);
+ }
+ }
+
+ /// <summary>
+ /// Gets direction of this endpoint.
+ /// </summary>
+ public EndpointDirection Direction
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return (EndpointDirection)Interop.NativeGet<Interop.EndpointDirection>(_handle.GetDirection);
+ }
+ }
+
+ /// <summary>
+ /// Gets max packet size of given endpoint.
+ /// </summary>
+ public int MaxPacketSize
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<int>(_handle.GetMaxPacketSize);
+ }
+ }
+
+ internal void ThrowIfDisposed()
+ {
+ if (_handle == null) throw new InvalidOperationException("Incompatible endpoint handle");
+ _parent?.ThrowIfDisposed();
+ }
+
+ protected int TransferImpl(byte[] buffer, int length, uint timeout)
+ {
+ ThrowIfDisposed();
+ int transferred;
+ _handle.Transfer(buffer, length, out transferred, timeout).ThrowIfFailed("Transfer failed");
+ return transferred;
+ }
+
+ internal static UsbEndpoint EndpointFactory(UsbInterface parent, Interop.UsbEndpointHandle handle)
+ {
+ Interop.TransferType transferType;
+ handle.GetTransferType(out transferType).ThrowIfFailed("Failed to get transfer type from endpoint");
+ switch(transferType)
+ {
+ case Interop.TransferType.Bulk: return new UsbBulkEndpoint(parent, handle);
+ case Interop.TransferType.Interrupt: return new UsbInterruptEndpoint(parent, handle);
+ case Interop.TransferType.Isochronous: return new UsbIsochronousEndpoint(parent, handle);
+ default: return new UsbEndpoint(parent, handle);
+ }
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System.Collections.Generic;
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// Class to manage USB Interfaces.
+ /// </summary>
+ public class UsbInterface
+ {
+ internal readonly Interop.UsbInterfaceHandle _handle;
+ private readonly UsbConfiguration _parent;
+ private Dictionary<int, UsbEndpoint> _endpoints;
+ private bool _isClaimed;
+
+ internal UsbInterface(UsbConfiguration parent, Interop.UsbInterfaceHandle handle)
+ {
+ _parent = parent;
+ _handle = handle;
+ }
+
+ /// <summary>
+ /// Gets number of given interface.
+ /// </summary>
+ public int Id
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<int>(_handle.GetNumber);
+ }
+ }
+
+ /// <summary>
+ /// Sets alternative setting. Use index of new alternative setting for given interface.
+ /// </summary>
+ public int AlternateSetting
+ {
+ set
+ {
+ ThrowIfDisposed();
+ Interop.NativeSet(_handle.SetAltsetting, value);
+ }
+ }
+
+ /// <summary>
+ /// Dictionary mapping endpoint Ids to endpoint instances for given interface.
+ /// </summary>
+ public IReadOnlyDictionary<int, UsbEndpoint> Endpoints
+ {
+ get
+ {
+ ThrowIfDisposed();
+ if (_endpoints == null)
+ {
+ _endpoints = new Dictionary<int, UsbEndpoint>();
+ int count = Interop.NativeGet<int>(_handle.GetNumEndpoints);
+ for (int i = 0; i < count; ++i)
+ {
+ Interop.UsbEndpointHandle handle;
+ _handle.GetEndpoint(i, out handle);
+ UsbEndpoint endpoint = UsbEndpoint.EndpointFactory(this, handle);
+ _endpoints.Add(endpoint.Id, endpoint);
+ }
+ }
+ return _endpoints;
+ }
+ }
+
+
+ /// <summary>
+ /// Gets string describing an interface.
+ /// </summary>
+ /// <returns></returns>
+ public string InterfaceString()
+ {
+ ThrowIfDisposed();
+ return Interop.DescriptorString(_handle.GetStr);
+ }
+
+ /// <summary>
+ /// Claims interface on a device. Interface must be claimed first to perform I/O operations.
+ /// </summary>
+ /// <param name="force">Set to true to auto detach kernel driver, false otherwise.</param>
+ /// <exception cref="InvalidOperationException">
+ /// Throws exception if device is disconnected or not opened for operation or another program or driver has claimed the interface.
+ /// </exception>
+ public void Claim(bool force)
+ {
+ ThrowIfDisposed();
+ if (_isClaimed == true) return;
+ _handle.ClaimInterface(force).ThrowIfFailed("Failed to claim interface");
+ _isClaimed = true;
+ }
+
+
+ /// <summary>
+ /// Releases previously claimed interface.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">Throws exception if device is disconnected or not opened for operation.</exception>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public void Release()
+ {
+ ThrowIfDisposed();
+ if (_isClaimed == false) return;
+ _handle.ReleaseInterface().ThrowIfFailed("Failed to release interface");
+ _isClaimed = false;
+ }
+
+ internal void ThrowIfDisposed()
+ {
+ _parent.ThrowIfDisposed();
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// USB Interrupt Endpoint class.
+ /// </summary>
+ public class UsbInterruptEndpoint : UsbEndpoint
+ {
+ internal UsbInterruptEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle) : base(parent, handle)
+ {
+ }
+
+ /// <summary>
+ /// Gets interval for polling endpoint for data transfers, in frame counts (refer to USB protocol specification).
+ /// </summary>
+ public int PollingInterval
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return Interop.NativeGet<int>(_handle.GetInterval);
+ }
+ }
+
+ /// <summary>
+ /// Performs a USB transfer on given endpoint. Direction of transfer is determined by the endpoint.
+ /// </summary>
+ /// <param name="buffer">Suitably-sized data buffer for either input or output (depending on endpoint).</param>
+ /// <param name="length">
+ /// For writes, the number of bytes from data to be sent, for reads the maximum number of bytes to receive
+ /// into the data buffer.
+ /// </param>
+ /// <param name="timeout">
+ /// Time (in milliseconds) that this function should wait for before giving up due to no response being
+ /// received(for an unlimited timeout 0 value should be used).
+ /// </param>
+ /// <returns>Number of bytes actually transferred.</returns>
+ /// <exception cref="InvalidOperationException">Throws exception if device is disconnected or not opened for operation.</exception>
+ /// <exception cref="TimeoutException">Throws exception if transfer timed-out.</exception>
+ public int Transfer(byte[] buffer, int length, uint timeout)
+ {
+ return TransferImpl(buffer, length, timeout);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// USB Isochronous Endpoint class.
+ /// </summary>
+ public class UsbIsochronousEndpoint : UsbEndpoint
+ {
+ internal UsbIsochronousEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle) : base(parent, handle)
+ {
+ }
+
+ /// <summary>
+ /// Gets synchronization type of this endpoint.
+ /// </summary>
+ public SynchronizationType SynchronizationType
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return (SynchronizationType)Interop.NativeGet<Interop.SynchronizationType>(_handle.GetSynchType);
+ }
+ }
+
+ /// <summary>
+ /// Gets usage type of this endpoint.
+ /// </summary>
+ public UsageType UsageType
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return (UsageType)Interop.NativeGet<Interop.UsageType>(_handle.GetUsageType);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Tizen.System.Usb
+{
+ /// <summary>
+ /// USB Manager class.
+ /// </summary>
+ public class UsbManager : IDisposable
+ {
+ private readonly Interop.UsbContextHandle _context;
+ private readonly Interop.HostHotplugHandle _hotpluggedHandle;
+ private List<UsbDevice> _devices = new List<UsbDevice>();
+
+ /// <summary>
+ /// USB Manager Constructor.
+ /// </summary>
+ public UsbManager()
+ {
+ _context = new Interop.UsbContextHandle();
+ _devices = _context.GetDeviceList().Select(devHandle => new UsbDevice(this, devHandle)).ToList();
+ _context.SetHotplugCb(HostHotplugCallback, Interop.HotplugEventType.Any,
+ IntPtr.Zero, out _hotpluggedHandle).ThrowIfFailed("Failed to set hot plugged callback");
+ }
+
+ /// <summary>
+ /// This function returns list of USB devices attached to system.
+ /// </summary>
+ /// <exception cref="NotSupportedException">Throws exception if USB host feature is not enabled.</exception>
+ /// <exception cref="OutOfMemoryException">Throws exception in case of insufficient memory.</exception>
+ /// <exception cref="UnauthorizedAccessException">Throws exception if user has insufficient permission on device.</exception>
+ public IEnumerable<UsbDevice> AvailableDevices
+ {
+ get
+ {
+ ThrowIfDisposed();
+ return _devices;
+ }
+ }
+
+ /// <summary>
+ /// Event handler for events when a USB device is attached or detached.
+ /// </summary>
+ public event EventHandler<HotPluggedEventArgs> DeviceHotPlugged;
+
+ internal void HostHotplugCallback(IntPtr devHandle, IntPtr userData)
+ {
+ Interop.HostDeviceHandle handle = new Interop.HostDeviceHandle(devHandle);
+ UsbDevice device = _devices.Where(dev => dev._handle == handle).FirstOrDefault();
+ if (device == null)
+ {
+ device = new UsbDevice(this, handle);
+ _devices.Add(device);
+
+ if (DeviceHotPlugged != null)
+ {
+ DeviceHotPlugged.Invoke(this, new HotPluggedEventArgs(device, HotplugEventType.Attach));
+ }
+ }
+ else
+ {
+ if (DeviceHotPlugged != null)
+ {
+ DeviceHotPlugged.Invoke(this, new HotPluggedEventArgs(device, HotplugEventType.Detach));
+ }
+
+ _devices.Remove(device);
+ // do we need to dispose device here ?
+ }
+ }
+
+ internal void ThrowIfDisposed()
+ {
+ if (disposedValue) throw new ObjectDisposedException("USB Context is already disposed");
+ }
+
+ #region IDisposable Support
+ private bool disposedValue = false;
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!disposedValue)
+ {
+ _hotpluggedHandle.UnsetHotplugCb();
+ _context.Dispose();
+ disposedValue = true;
+ }
+ }
+
+ ~UsbManager()
+ {
+ Dispose(false);
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+ #endregion
+ }
+}