From e5e1972ee6abfddb1b5212e79093bc23525f2cf4 Mon Sep 17 00:00:00 2001 From: Dinesh Dwivedi Date: Mon, 18 Sep 2017 12:02:50 +0200 Subject: [PATCH] [TCSACR-93] Add USB Host C# API MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Change-Id: I8c27da29e84f141ecd5ad7acd0b8a8f1d4dc2dfd Signed-off-by: Paweł Szewczyk --- pkg/PlatformFileList.txt | 1 + pkg/PublicModuleList.txt | 1 + .../Interop/Interop.Configuration.cs | 54 +++++ src/Tizen.System.Usb/Interop/Interop.Constants.cs | 24 +++ src/Tizen.System.Usb/Interop/Interop.Context.cs | 104 ++++++++++ src/Tizen.System.Usb/Interop/Interop.Device.cs | 111 +++++++++++ src/Tizen.System.Usb/Interop/Interop.Endpoint.cs | 81 ++++++++ src/Tizen.System.Usb/Interop/Interop.ErrorCode.cs | 117 +++++++++++ src/Tizen.System.Usb/Interop/Interop.Interface.cs | 50 +++++ .../Interop/Interop.SafeUsbHandle.cs | 68 +++++++ src/Tizen.System.Usb/Tizen.System.Usb.csproj | 12 ++ src/Tizen.System.Usb/Tizen.System.Usb.sln | 37 ++++ src/Tizen.System.Usb/Usb/EndpointDirection.cs | 37 ++++ src/Tizen.System.Usb/Usb/HotPluggedEventArgs.cs | 42 ++++ src/Tizen.System.Usb/Usb/HotplugEventType.cs | 33 +++ src/Tizen.System.Usb/Usb/SynchronizationType.cs | 37 ++++ src/Tizen.System.Usb/Usb/UsageType.cs | 37 ++++ src/Tizen.System.Usb/Usb/UsbBulkEndpoint.cs | 50 +++++ src/Tizen.System.Usb/Usb/UsbConfiguration.cs | 152 ++++++++++++++ src/Tizen.System.Usb/Usb/UsbControlEndpoint.cs | 94 +++++++++ src/Tizen.System.Usb/Usb/UsbDevice.cs | 221 +++++++++++++++++++++ src/Tizen.System.Usb/Usb/UsbDeviceInformation.cs | 118 +++++++++++ src/Tizen.System.Usb/Usb/UsbDeviceStrings.cs | 77 +++++++ src/Tizen.System.Usb/Usb/UsbEndpoint.cs | 98 +++++++++ src/Tizen.System.Usb/Usb/UsbInterface.cs | 131 ++++++++++++ src/Tizen.System.Usb/Usb/UsbInterruptEndpoint.cs | 62 ++++++ src/Tizen.System.Usb/Usb/UsbIsochronousEndpoint.cs | 52 +++++ src/Tizen.System.Usb/Usb/UsbManager.cs | 119 +++++++++++ 28 files changed, 2020 insertions(+) mode change 100644 => 100755 pkg/PublicModuleList.txt create mode 100644 src/Tizen.System.Usb/Interop/Interop.Configuration.cs create mode 100644 src/Tizen.System.Usb/Interop/Interop.Constants.cs create mode 100644 src/Tizen.System.Usb/Interop/Interop.Context.cs create mode 100644 src/Tizen.System.Usb/Interop/Interop.Device.cs create mode 100644 src/Tizen.System.Usb/Interop/Interop.Endpoint.cs create mode 100644 src/Tizen.System.Usb/Interop/Interop.ErrorCode.cs create mode 100644 src/Tizen.System.Usb/Interop/Interop.Interface.cs create mode 100644 src/Tizen.System.Usb/Interop/Interop.SafeUsbHandle.cs create mode 100755 src/Tizen.System.Usb/Tizen.System.Usb.csproj create mode 100755 src/Tizen.System.Usb/Tizen.System.Usb.sln create mode 100644 src/Tizen.System.Usb/Usb/EndpointDirection.cs create mode 100644 src/Tizen.System.Usb/Usb/HotPluggedEventArgs.cs create mode 100644 src/Tizen.System.Usb/Usb/HotplugEventType.cs create mode 100644 src/Tizen.System.Usb/Usb/SynchronizationType.cs create mode 100644 src/Tizen.System.Usb/Usb/UsageType.cs create mode 100644 src/Tizen.System.Usb/Usb/UsbBulkEndpoint.cs create mode 100644 src/Tizen.System.Usb/Usb/UsbConfiguration.cs create mode 100644 src/Tizen.System.Usb/Usb/UsbControlEndpoint.cs create mode 100755 src/Tizen.System.Usb/Usb/UsbDevice.cs create mode 100755 src/Tizen.System.Usb/Usb/UsbDeviceInformation.cs create mode 100755 src/Tizen.System.Usb/Usb/UsbDeviceStrings.cs create mode 100644 src/Tizen.System.Usb/Usb/UsbEndpoint.cs create mode 100755 src/Tizen.System.Usb/Usb/UsbInterface.cs create mode 100755 src/Tizen.System.Usb/Usb/UsbInterruptEndpoint.cs create mode 100644 src/Tizen.System.Usb/Usb/UsbIsochronousEndpoint.cs create mode 100644 src/Tizen.System.Usb/Usb/UsbManager.cs diff --git a/pkg/PlatformFileList.txt b/pkg/PlatformFileList.txt index a77b7cb..8672592 100644 --- a/pkg/PlatformFileList.txt +++ b/pkg/PlatformFileList.txt @@ -74,6 +74,7 @@ Tizen.System.MediaKey.dll #common #mobile #mobile-emul 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 diff --git a/pkg/PublicModuleList.txt b/pkg/PublicModuleList.txt old mode 100644 new mode 100755 index f128d43..a7ddc1b --- a/pkg/PublicModuleList.txt +++ b/pkg/PublicModuleList.txt @@ -68,6 +68,7 @@ Tizen.System.Information Tizen.System.MediaKey Tizen.System.PlatformConfig Tizen.System.Storage +Tizen.System.Usb Tizen.System.SystemSettings Tizen.Telephony Tizen.Tracer diff --git a/src/Tizen.System.Usb/Interop/Interop.Configuration.cs b/src/Tizen.System.Usb/Interop/Interop.Configuration.cs new file mode 100644 index 0000000..9bf5d8f --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.Configuration.cs @@ -0,0 +1,54 @@ +/* + * 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 diff --git a/src/Tizen.System.Usb/Interop/Interop.Constants.cs b/src/Tizen.System.Usb/Interop/Interop.Constants.cs new file mode 100644 index 0000000..0e79720 --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.Constants.cs @@ -0,0 +1,24 @@ +/* + * 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 diff --git a/src/Tizen.System.Usb/Interop/Interop.Context.cs b/src/Tizen.System.Usb/Interop/Interop.Context.cs new file mode 100644 index 0000000..52a2c7e --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.Context.cs @@ -0,0 +1,104 @@ +/* + * 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 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 deviceList = new List(); + 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; } + } +} diff --git a/src/Tizen.System.Usb/Interop/Interop.Device.cs b/src/Tizen.System.Usb/Interop/Interop.Device.cs new file mode 100644 index 0000000..e5f8c28 --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.Device.cs @@ -0,0 +1,111 @@ +/* + * 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 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); + } + } +} diff --git a/src/Tizen.System.Usb/Interop/Interop.Endpoint.cs b/src/Tizen.System.Usb/Interop/Interop.Endpoint.cs new file mode 100644 index 0000000..65536e7 --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.Endpoint.cs @@ -0,0 +1,81 @@ +/* + * 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 diff --git a/src/Tizen.System.Usb/Interop/Interop.ErrorCode.cs b/src/Tizen.System.Usb/Interop/Interop.ErrorCode.cs new file mode 100644 index 0000000..973dc9d --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.ErrorCode.cs @@ -0,0 +1,117 @@ +/* + * 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(); + } + + /// + /// Utility method to check for error, returns false if failed and print warning messages + /// + /// true in case of no error, false otherwise + 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; + } + + /// + /// Utility method to check for error, returns false if failed and throw exception + /// + /// true in case of no error + 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 diff --git a/src/Tizen.System.Usb/Interop/Interop.Interface.cs b/src/Tizen.System.Usb/Interop/Interop.Interface.cs new file mode 100644 index 0000000..5cae2f3 --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.Interface.cs @@ -0,0 +1,50 @@ +/* + * 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 diff --git a/src/Tizen.System.Usb/Interop/Interop.SafeUsbHandle.cs b/src/Tizen.System.Usb/Interop/Interop.SafeUsbHandle.cs new file mode 100644 index 0000000..5c5b5e7 --- /dev/null +++ b/src/Tizen.System.Usb/Interop/Interop.SafeUsbHandle.cs @@ -0,0 +1,68 @@ +/* + * 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(out T value); + public delegate ErrorCode GetterPtrMethod(out IntPtr value); + public delegate ErrorCode GetDescriptorString(ref int length, byte[] data); + public delegate ErrorCode SetterMethod(T value); + + internal static T NativeGet(GetterMethod 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(SetterMethod 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; + } + } +} diff --git a/src/Tizen.System.Usb/Tizen.System.Usb.csproj b/src/Tizen.System.Usb/Tizen.System.Usb.csproj new file mode 100755 index 0000000..1407501 --- /dev/null +++ b/src/Tizen.System.Usb/Tizen.System.Usb.csproj @@ -0,0 +1,12 @@ + + + + netstandard2.0 + + + + + + + + diff --git a/src/Tizen.System.Usb/Tizen.System.Usb.sln b/src/Tizen.System.Usb/Tizen.System.Usb.sln new file mode 100755 index 0000000..e69f601 --- /dev/null +++ b/src/Tizen.System.Usb/Tizen.System.Usb.sln @@ -0,0 +1,37 @@ + +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 diff --git a/src/Tizen.System.Usb/Usb/EndpointDirection.cs b/src/Tizen.System.Usb/Usb/EndpointDirection.cs new file mode 100644 index 0000000..3405fdd --- /dev/null +++ b/src/Tizen.System.Usb/Usb/EndpointDirection.cs @@ -0,0 +1,37 @@ +/* + * 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 +{ + /// + /// Enumeration of transfer direction for Endpoints. + /// + public enum EndpointDirection + { + /// + /// IN direction + /// + In = Interop.EndpointDirection.In, + /// + /// OUT direction + /// + Out = Interop.EndpointDirection.Out, + /// + /// Bi-directional + /// + InOut = Interop.EndpointDirection.InOut, + } +} \ No newline at end of file diff --git a/src/Tizen.System.Usb/Usb/HotPluggedEventArgs.cs b/src/Tizen.System.Usb/Usb/HotPluggedEventArgs.cs new file mode 100644 index 0000000..89c7504 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/HotPluggedEventArgs.cs @@ -0,0 +1,42 @@ +/* + * 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 +{ + /// + /// Event arguments for Hot Plugged event for USB devices. + /// + public class HotPluggedEventArgs : EventArgs + { + internal HotPluggedEventArgs(UsbDevice device, HotplugEventType type) + { + Device = device; + EventType = type; + } + + /// + /// USB Device + /// + public UsbDevice Device { get; } + + /// + /// Event Type + /// + public HotplugEventType EventType { get; } + } +} diff --git a/src/Tizen.System.Usb/Usb/HotplugEventType.cs b/src/Tizen.System.Usb/Usb/HotplugEventType.cs new file mode 100644 index 0000000..358b513 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/HotplugEventType.cs @@ -0,0 +1,33 @@ +/* + * 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 +{ + /// + /// Enumeration of hot plugged event type for USB devices. + /// + public enum HotplugEventType + { + /// + /// USB device is attached + /// + Attach = Interop.HotplugEventType.Attach, + /// + /// USB device is detached + /// + Detach = Interop.HotplugEventType.Detach, + } +} \ No newline at end of file diff --git a/src/Tizen.System.Usb/Usb/SynchronizationType.cs b/src/Tizen.System.Usb/Usb/SynchronizationType.cs new file mode 100644 index 0000000..b523087 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/SynchronizationType.cs @@ -0,0 +1,37 @@ +/* + * 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 +{ + /// + /// Enumeration of isochronous endpoint's synchronization type. + /// + public enum SynchronizationType + { + /// + /// Asynchronous + /// + Asynchronous = Interop.SynchronizationType.Async, + /// + /// Adaptive + /// + Adaptive = Interop.SynchronizationType.Adaptive, + /// + /// Synchronous + /// + Synchronous = Interop.SynchronizationType.Sync, + } +} \ No newline at end of file diff --git a/src/Tizen.System.Usb/Usb/UsageType.cs b/src/Tizen.System.Usb/Usb/UsageType.cs new file mode 100644 index 0000000..eb4af52 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsageType.cs @@ -0,0 +1,37 @@ +/* + * 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 +{ + /// + /// Enumeration of an endpoint's usage type. + /// + public enum UsageType + { + /// + /// Data endpoint + /// + Data = Interop.UsageType.Data, + /// + /// Feedback endpoint + /// + Feedback = Interop.UsageType.Feedback, + /// + /// Implicit feedback Data endpoint + /// + Implicit = Interop.UsageType.Implicit, + } +} \ No newline at end of file diff --git a/src/Tizen.System.Usb/Usb/UsbBulkEndpoint.cs b/src/Tizen.System.Usb/Usb/UsbBulkEndpoint.cs new file mode 100644 index 0000000..0637109 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbBulkEndpoint.cs @@ -0,0 +1,50 @@ +/* + * 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 +{ + /// + /// USB Bulk Endpoint class. + /// + public class UsbBulkEndpoint : UsbEndpoint + { + internal UsbBulkEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle) : base(parent, handle) + { + } + + /// + /// Performs a USB transfer on given endpoint. Direction of transfer is determined by the endpoint. + /// + /// Suitably-sized data buffer for either input or output (depending on endpoint). + /// + /// For writes, the number of bytes from data to be sent, for reads the maximum number of bytes to receive + /// into the data buffer. + /// + /// + /// 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). + /// + /// Number of bytes actually transferred. + /// Throws exception if device is disconnected or not opened for operation. + /// Throws exception if transfer timed-out. + public int Transfer(byte[] buffer, int length, uint timeout) + { + return TransferImpl(buffer, length, timeout); + } + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbConfiguration.cs b/src/Tizen.System.Usb/Usb/UsbConfiguration.cs new file mode 100644 index 0000000..ba9abfb --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbConfiguration.cs @@ -0,0 +1,152 @@ +/* + * 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 +{ + /// + /// Class to manage USB Configuration. + /// + public class UsbConfiguration : IDisposable + { + internal readonly Interop.UsbConfigHandle _handle; + private readonly UsbDevice _parent; + private Dictionary _interfaces; + + internal UsbConfiguration(UsbDevice parent, Interop.UsbConfigHandle handle) + { + _parent = parent; + _handle = handle; + } + + /// + /// Checks if device is self-powered in given configuration. + /// + public bool IsSelfPowered + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.IsSelfPowered); + } + } + + /// + /// Checks if device in given configuration supports remote wakeup. + /// + public bool SupportRemoteWakeup + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.SupportRemoteWakeup); + } + } + + /// + /// Gets maximum power required in given configuration, in mA. + /// + public int MaximumPowerRequired + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.GetMaxPower); + } + } + + /// + /// Dictionary mapping interfaces Ids to interface instances for given configuration. + /// + public IReadOnlyDictionary Interfaces + { + get + { + ThrowIfDisposed(); + if (_interfaces == null) + { + _interfaces = new Dictionary(); + int count = Interop.NativeGet(_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; + } + } + + /// + /// Configuration string. + /// + public string ConfigurationString + { + get + { + ThrowIfDisposed(); + return Interop.DescriptorString(_handle.GetConfigStr); + } + } + + /// + /// Set this configuration as active configuration for the device. + /// + /// + /// Throws exception if device is disconnected or not opened for operation or busy as its interfaces are currently claimed. + /// + 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 diff --git a/src/Tizen.System.Usb/Usb/UsbControlEndpoint.cs b/src/Tizen.System.Usb/Usb/UsbControlEndpoint.cs new file mode 100644 index 0000000..2e1e7d4 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbControlEndpoint.cs @@ -0,0 +1,94 @@ +/* + * 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 +{ + /// + /// USB Control Endpoint class. + /// + public class UsbControlEndpoint : UsbEndpoint + { + private readonly UsbDevice _device; + + internal UsbControlEndpoint(UsbDevice device) : base(null, null) + { + _device = device; + } + + /// + /// Gets number of this endpoint. + /// + public new int Id + { + get + { + return 0; + } + } + + /// + /// Gets direction of this endpoint. + /// + public new EndpointDirection Direction + { + get + { + return EndpointDirection.InOut; + } + } + + /// + /// Gets max packet size of given endpoint. + /// + public new int MaxPacketSize + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetMaxPacketSize0); + } + } + + /// + /// Performs a control transaction on endpoint zero for this device. + /// + /// bmRequestType type field for the setup packet. + /// bRequest field for the setup packet. + /// wValue field for the setup packet. + /// wIndex field for the setup packet. + /// Suitably-sized data buffer for either input or output, (depending on direction bits within bmRequestType). + /// wLength field for the setup packet. The data buffer should be at least this size. + /// + /// 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). + /// + /// Transferred Number of transferred bytes. + /// Throws exception if device is disconnected or not opened for operation. + /// Throws exception if transfer timed-out. + 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; + } + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbDevice.cs b/src/Tizen.System.Usb/Usb/UsbDevice.cs new file mode 100755 index 0000000..f6e37d3 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbDevice.cs @@ -0,0 +1,221 @@ +/* + * 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 +{ + /// + /// Class to manage USB host devices. This class contains operations for enumerating, opening and closing devices. + /// + public class UsbDevice : IDisposable + { + internal readonly Interop.HostDeviceHandle _handle; + private readonly UsbManager _parent; + private Dictionary _configurations; + + internal UsbDevice(UsbManager parent, Interop.HostDeviceHandle handle) + { + _parent = parent; + _handle = handle; + } + + /// + /// Number of the bus, this device is connected to. + /// + /// Throws exception if user has insufficient permission on device. + public int BusId { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.GetBusNumber); + } + } + + /// + /// Address of device on the bus. + /// + public int Address + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.GetAddress); + } + } + + /// + /// List of available port numbers from a device. + /// + public IEnumerable Ports + { + get + { + ThrowIfDisposed(); + return _handle.Ports(); + } + } + + /// + /// Checks if device is opened. + /// + public bool IsOpened + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.IsOpened); + } + } + + /// + /// Control endpoint (endpoint 0). + /// + public UsbControlEndpoint ControlEndpoint + { + get + { + ThrowIfDisposed(); + return new UsbControlEndpoint(this); + } + } + + /// + /// Active configuration for the device. + /// + /// Throws exception if device is disconnected. + public UsbConfiguration ActiveConfiguration + { + get + { + ThrowIfDisposed(); + Interop.UsbConfigHandle configHandle = Interop.NativeGet(_handle.GetActiveConfig); + return _configurations.Values.Where(config => config._handle == configHandle).First(); + } + } + + /// + /// Dictionary mapping configuration Ids to configuration instances for this device. + /// + public IReadOnlyDictionary Configurations + { + get + { + ThrowIfDisposed(); + if (_configurations == null) + { + _configurations = new Dictionary(); + int count = Interop.NativeGet(_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; + } + } + + /// + /// Device information such as version, class, subclass etc. + /// + public UsbDeviceInformation DeviceInformation + { + get + { + ThrowIfDisposed(); + return new UsbDeviceInformation(this); + } + } + + /// + /// String associated with device. + /// + public UsbDeviceStrings Strings + { + get + { + ThrowIfDisposed(); + return new UsbDeviceStrings(this, "us-ascii"); + } + } + + /// + /// Opens device, which allows performing operations on it. + /// + /// Throws exception in case of insufficient memory. + /// Throws exception if device is disconnected. + /// Throws exception if user has insufficient permission on device. + public void Open() + { + ThrowIfDisposed(); + _handle.Open().ThrowIfFailed("Failed to open device for use"); + } + + /// + /// Closes device for operations. + /// + /// Throws exception if device is not opened for operation. + 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 + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbDeviceInformation.cs b/src/Tizen.System.Usb/Usb/UsbDeviceInformation.cs new file mode 100755 index 0000000..a671022 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbDeviceInformation.cs @@ -0,0 +1,118 @@ +/* + * 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 +{ + /// + /// Device information for USB device. + /// + public class UsbDeviceInformation + { + private readonly UsbDevice _device; + + internal UsbDeviceInformation(UsbDevice device) + { + _device = device; + } + + /// + /// USB specification release number as binary-coded decimal. + /// + /// Throws exception if user has insufficient permission on device. + public int UsbVersion + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetBcdUsb); + } + } + + /// + /// Gets device class. + /// + public int Class + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetClass); + } + } + + /// + /// Gets device sub class. + /// + public int Subclass + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetSubClass); + } + } + + /// + /// Gets device protocol. + /// + public int Protocol + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetProtocol); + } + } + + /// + /// Gets vendor id. + /// + public int VendorId + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetIdVendor); + } + } + + /// + /// Gets product id. + /// + public int ProductId + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetIdProduct); + } + } + + /// + /// Gets device release number in binary-coded decimal. + /// + public int DeviceVersion + { + get + { + _device.ThrowIfDisposed(); + return Interop.NativeGet(_device._handle.GetBcdDevice); + } + } + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbDeviceStrings.cs b/src/Tizen.System.Usb/Usb/UsbDeviceStrings.cs new file mode 100755 index 0000000..cc9eb01 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbDeviceStrings.cs @@ -0,0 +1,77 @@ +/* + * 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 +{ + /// + /// String information for USB device. + /// + public class UsbDeviceStrings + { + private readonly UsbDevice _device; + private string _language; + + internal UsbDeviceStrings(UsbDevice device, string language) + { + _device = device; + _language = language; + } + + /// + /// Gets string describing device manufacturer. + /// + /// Throws exception if device is disconnected or not opened for operation. + /// Throws exception if user has insufficient permission on device. + public string Manufacturer + { + get + { + _device.ThrowIfDisposed(); + return Interop.DescriptorString(_device._handle.GetManufacturerStr, _language); + } + } + + /// + /// Gets product string of device + /// + /// Throws exception if device is not opened for operation. + /// Throws exception if user has insufficient permission on device. + public string Product + { + get + { + _device.ThrowIfDisposed(); + return Interop.DescriptorString(_device._handle.GetProductStr, _language); + } + } + + /// + /// Gets serial number of a device. + /// + /// Throws exception if device is not opened for operation. + /// Throws exception if user has insufficient permission on device. + public string Serial + { + get + { + _device.ThrowIfDisposed(); + return Interop.DescriptorString(_device._handle.GetSerialNumberStr, _language); + } + } + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbEndpoint.cs b/src/Tizen.System.Usb/Usb/UsbEndpoint.cs new file mode 100644 index 0000000..022fafd --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbEndpoint.cs @@ -0,0 +1,98 @@ +/* + * 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 +{ + /// + /// USB Endpoint class. + /// + public class UsbEndpoint + { + internal readonly Interop.UsbEndpointHandle _handle; + protected readonly UsbInterface _parent; + + internal UsbEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle) + { + _parent = parent; + _handle = handle; + } + + /// + /// Gets number of this endpoint. + /// + public int Id + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.GetNumber); + } + } + + /// + /// Gets direction of this endpoint. + /// + public EndpointDirection Direction + { + get + { + ThrowIfDisposed(); + return (EndpointDirection)Interop.NativeGet(_handle.GetDirection); + } + } + + /// + /// Gets max packet size of given endpoint. + /// + public int MaxPacketSize + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_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 diff --git a/src/Tizen.System.Usb/Usb/UsbInterface.cs b/src/Tizen.System.Usb/Usb/UsbInterface.cs new file mode 100755 index 0000000..04a9d48 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbInterface.cs @@ -0,0 +1,131 @@ +/* + * 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 +{ + /// + /// Class to manage USB Interfaces. + /// + public class UsbInterface + { + internal readonly Interop.UsbInterfaceHandle _handle; + private readonly UsbConfiguration _parent; + private Dictionary _endpoints; + private bool _isClaimed; + + internal UsbInterface(UsbConfiguration parent, Interop.UsbInterfaceHandle handle) + { + _parent = parent; + _handle = handle; + } + + /// + /// Gets number of given interface. + /// + public int Id + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.GetNumber); + } + } + + /// + /// Sets alternative setting. Use index of new alternative setting for given interface. + /// + public int AlternateSetting + { + set + { + ThrowIfDisposed(); + Interop.NativeSet(_handle.SetAltsetting, value); + } + } + + /// + /// Dictionary mapping endpoint Ids to endpoint instances for given interface. + /// + public IReadOnlyDictionary Endpoints + { + get + { + ThrowIfDisposed(); + if (_endpoints == null) + { + _endpoints = new Dictionary(); + int count = Interop.NativeGet(_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; + } + } + + + /// + /// Gets string describing an interface. + /// + /// + public string InterfaceString() + { + ThrowIfDisposed(); + return Interop.DescriptorString(_handle.GetStr); + } + + /// + /// Claims interface on a device. Interface must be claimed first to perform I/O operations. + /// + /// Set to true to auto detach kernel driver, false otherwise. + /// + /// Throws exception if device is disconnected or not opened for operation or another program or driver has claimed the interface. + /// + public void Claim(bool force) + { + ThrowIfDisposed(); + if (_isClaimed == true) return; + _handle.ClaimInterface(force).ThrowIfFailed("Failed to claim interface"); + _isClaimed = true; + } + + + /// + /// Releases previously claimed interface. + /// + /// Throws exception if device is disconnected or not opened for operation. + /// Throws exception if user has insufficient permission on device. + public void Release() + { + ThrowIfDisposed(); + if (_isClaimed == false) return; + _handle.ReleaseInterface().ThrowIfFailed("Failed to release interface"); + _isClaimed = false; + } + + internal void ThrowIfDisposed() + { + _parent.ThrowIfDisposed(); + } + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbInterruptEndpoint.cs b/src/Tizen.System.Usb/Usb/UsbInterruptEndpoint.cs new file mode 100755 index 0000000..53a4a73 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbInterruptEndpoint.cs @@ -0,0 +1,62 @@ +/* + * 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 +{ + /// + /// USB Interrupt Endpoint class. + /// + public class UsbInterruptEndpoint : UsbEndpoint + { + internal UsbInterruptEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle) : base(parent, handle) + { + } + + /// + /// Gets interval for polling endpoint for data transfers, in frame counts (refer to USB protocol specification). + /// + public int PollingInterval + { + get + { + ThrowIfDisposed(); + return Interop.NativeGet(_handle.GetInterval); + } + } + + /// + /// Performs a USB transfer on given endpoint. Direction of transfer is determined by the endpoint. + /// + /// Suitably-sized data buffer for either input or output (depending on endpoint). + /// + /// For writes, the number of bytes from data to be sent, for reads the maximum number of bytes to receive + /// into the data buffer. + /// + /// + /// 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). + /// + /// Number of bytes actually transferred. + /// Throws exception if device is disconnected or not opened for operation. + /// Throws exception if transfer timed-out. + public int Transfer(byte[] buffer, int length, uint timeout) + { + return TransferImpl(buffer, length, timeout); + } + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbIsochronousEndpoint.cs b/src/Tizen.System.Usb/Usb/UsbIsochronousEndpoint.cs new file mode 100644 index 0000000..1544c43 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbIsochronousEndpoint.cs @@ -0,0 +1,52 @@ +/* + * 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 +{ + /// + /// USB Isochronous Endpoint class. + /// + public class UsbIsochronousEndpoint : UsbEndpoint + { + internal UsbIsochronousEndpoint(UsbInterface parent, Interop.UsbEndpointHandle handle) : base(parent, handle) + { + } + + /// + /// Gets synchronization type of this endpoint. + /// + public SynchronizationType SynchronizationType + { + get + { + ThrowIfDisposed(); + return (SynchronizationType)Interop.NativeGet(_handle.GetSynchType); + } + } + + /// + /// Gets usage type of this endpoint. + /// + public UsageType UsageType + { + get + { + ThrowIfDisposed(); + return (UsageType)Interop.NativeGet(_handle.GetUsageType); + } + } + } +} diff --git a/src/Tizen.System.Usb/Usb/UsbManager.cs b/src/Tizen.System.Usb/Usb/UsbManager.cs new file mode 100644 index 0000000..aba4987 --- /dev/null +++ b/src/Tizen.System.Usb/Usb/UsbManager.cs @@ -0,0 +1,119 @@ +/* + * 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 +{ + /// + /// USB Manager class. + /// + public class UsbManager : IDisposable + { + private readonly Interop.UsbContextHandle _context; + private readonly Interop.HostHotplugHandle _hotpluggedHandle; + private List _devices = new List(); + + /// + /// USB Manager Constructor. + /// + 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"); + } + + /// + /// This function returns list of USB devices attached to system. + /// + /// Throws exception if USB host feature is not enabled. + /// Throws exception in case of insufficient memory. + /// Throws exception if user has insufficient permission on device. + public IEnumerable AvailableDevices + { + get + { + ThrowIfDisposed(); + return _devices; + } + } + + /// + /// Event handler for events when a USB device is attached or detached. + /// + public event EventHandler 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 + } +} -- 2.7.4