/// <summary> /// Sets the USB devices active configuration value. /// </summary> /// <param name="config">The active configuration value. A zero value means the device is not configured and a non-zero value indicates the device is configured.</param> /// <returns>True on success.</returns> /// <remarks> /// A USB device can have several different configurations, but only one active configuration. /// </remarks> public bool SetConfiguration(byte config) { int uTransferLength; UsbSetupPacket setupPkt = new UsbSetupPacket(); setupPkt.RequestType = (byte)UsbEndpointDirection.EndpointOut | (byte)UsbRequestType.TypeStandard | (byte)UsbRequestRecipient.RecipDevice; setupPkt.Request = (byte)UsbStandardRequest.SetConfiguration; setupPkt.Value = config; setupPkt.Index = 0; setupPkt.Length = 0; bool bSuccess = ControlTransfer(ref setupPkt, null, 0, out uTransferLength); if (bSuccess) { mCurrentConfigValue = config; } else { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetConfiguration", this); } return(bSuccess); }
public override ErrorCode Submit() { int iTransferred; ErrorCode eReturn = ErrorCode.Success; if (mTransferCancelEvent.WaitOne(0, false)) { return(ErrorCode.IoCancelled); } if (!mTransferCompleteEvent.WaitOne(0, UsbConstants.EXIT_CONTEXT)) { return(ErrorCode.ResourceBusy); } mHasWaitBeenCalled = false; mTransferCompleteEvent.Reset(); Overlapped.ClearAndSetEvent(mTransferCompleteEvent.SafeWaitHandle.DangerousGetHandle()); int ret = EndpointBase.PipeTransferSubmit(NextBufPtr, RequestCount, out iTransferred, mIsoPacketSize, Overlapped.GlobalOverlapped); if (ret != 0 && ret != (int)UsbStatusClodes.ErrorIoPending) { mTransferCompleteEvent.Set(); UsbError usbErr = UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "PipeTransferSubmit", EndpointBase); eReturn = usbErr.ErrorCode; } return(eReturn); }
///<summary> /// Opens the USB device handle. ///</summary> ///<returns> ///True if the device is already opened or was opened successfully. ///False if the device does not exists or is no longer valid. ///</returns> public override bool Open() { if (IsOpen) { return(true); } SafeFileHandle sfhDev; bool bSuccess = WinUsbAPI.OpenDevice(out sfhDev, mDevicePath); if (bSuccess) { SafeWinUsbInterfaceHandle handle = new SafeWinUsbInterfaceHandle(); if ((bSuccess = WinUsbAPI.WinUsb_Initialize(sfhDev, ref handle))) { mSafeDevHandle = sfhDev; mUsbHandle = handle; mPowerPolicies = new PowerPolicies(this); } else { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open:Initialize", typeof(UsbDevice)); } } else { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open", typeof(UsbDevice)); } return(bSuccess); }
/// <summary> /// Opens a WinUsb directly from the user supplied device path. /// </summary> /// <param name="devicePath">Device path (symbolic link) of the WinUsb device to open.</param> /// <param name="usbDevice">Returns an opened WinUsb device on success, null on failure.</param> /// <returns>True on success.</returns> public static bool Open(string devicePath, out WinUsbDevice usbDevice) { usbDevice = null; SafeFileHandle sfhDev; bool bSuccess = WinUsbAPI.OpenDevice(out sfhDev, devicePath); if (bSuccess) { SafeWinUsbInterfaceHandle handle = new SafeWinUsbInterfaceHandle(); bSuccess = WinUsbAPI.WinUsb_Initialize(sfhDev, ref handle); if (bSuccess) { usbDevice = new WinUsbDevice(WinUsbApi, sfhDev, handle, devicePath); } else { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open:Initialize", typeof(UsbDevice)); } } else { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open", typeof(UsbDevice)); } return(bSuccess); }
/// <summary> /// Gets a descriptor from the device. See <see cref="DescriptorType"/> for more information. /// </summary> /// <param name="descriptorType">The descriptor type ID to retrieve; this is usually one of the <see cref="DescriptorType"/> enumerations.</param> /// <param name="index">Descriptor index.</param> /// <param name="langId">Descriptor language id.</param> /// <param name="buffer">Memory to store the returned descriptor in.</param> /// <param name="bufferLength">Length of the buffer parameter in bytes.</param> /// <param name="transferLength">The number of bytes transferred to buffer upon success.</param> /// <returns>True on success.</returns> public override bool GetDescriptor(byte descriptorType, byte index, short langId, IntPtr buffer, int bufferLength, out int transferLength) { transferLength = 0; bool bSuccess = false; bool wasOpen = IsOpen; if (!wasOpen) { Open(); } if (!IsOpen) { return(false); } int ret = MonoUsbApi.GetDescriptor((MonoUsbDeviceHandle)mUsbHandle, descriptorType, index, buffer, (ushort)bufferLength); if (ret < 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "GetDescriptor Failed", this); } else { bSuccess = true; transferLength = ret; } if (!wasOpen && IsOpen) { Close(); } return(bSuccess); }
/// <summary> /// Submits the transfer. /// </summary> /// <remarks> /// This functions submits the USB transfer and return immediately. /// </remarks> /// <returns> /// <see cref="ErrorCode.Success"/> if the submit succeeds, /// otherwise one of the other <see cref="ErrorCode"/> codes. /// </returns> public override ErrorCode Submit() { if (mTransferCancelEvent.WaitOne(0)) { return(ErrorCode.IoCancelled); } if (!mTransferCompleteEvent.WaitOne(0)) { return(ErrorCode.ResourceBusy); } mTransfer.PtrBuffer = NextBufPtr; mTransfer.Length = RequestCount; mTransferCompleteEvent.Reset(); int ret = (int)mTransfer.Submit(); if (ret < 0) { mTransferCompleteEvent.Set(); UsbError usbErr = UsbError.Error(ErrorCode.MonoApiError, ret, "SubmitTransfer", EndpointBase); return(usbErr.ErrorCode); } return(ErrorCode.Success); }
/// <summary> /// Refreshes the <see cref="MonoUsbProfile"/> list. /// </summary> /// <remarks> /// <para>This is your entry point into finding a USB device to operate.</para> /// <para>This return value of this function indicates the number of devices in the resultant list.</para> /// <para>The <see cref="MonoUsbProfileList"/> has a crude form of built-in device notification that works on all platforms. By adding an event handler to the <see cref="AddRemoveEvent"/> changes in the device profile list are reported when <see cref="Refresh"/> is called.</para> /// </remarks> /// <param name="sessionHandle">A valid <see cref="MonoUsbSessionHandle"/>.</param> /// <returns>The number of devices in the outputted list, or <see cref="MonoUsbError.ErrorNoMem"/> on memory allocation failure.</returns> /// <example> /// <code source="..\MonoLibUsb\MonoUsb.ShowInfo\ShowInfo.cs" lang="cs"/> /// </example> public int Refresh(MonoUsbSessionHandle sessionHandle) { lock (LockProfileList) { MonoUsbProfileList newList = new MonoUsbProfileList(); MonoUsbProfileListHandle monoUSBProfileListHandle; int ret = MonoUsbApi.GetDeviceList(sessionHandle, out monoUSBProfileListHandle); if (ret < 0 || monoUSBProfileListHandle.IsInvalid) { #if LIBUSBDOTNET UsbError.Error(ErrorCode.MonoApiError, ret, "Refresh:GetDeviceList Failed", this); #else System.Diagnostics.Debug.Print("libusb_get_device_list failed:{0} {1}", (MonoUsbError)ret, MonoUsbApi.StrError((MonoUsbError)ret)); #endif return(ret); } int stopCount = ret; foreach (MonoUsbProfileHandle deviceProfileHandle in monoUSBProfileListHandle) { newList.mList.Add(new MonoUsbProfile(deviceProfileHandle)); stopCount--; if (stopCount <= 0) { break; } } syncWith(newList); monoUSBProfileListHandle.Close(); return(ret); } }
/// <summary> /// Gets a list of <see cref="WinUsbRegistry"/> classes for the specified interface guid. /// </summary> /// <param name="deviceInterfaceGuid">The DeviceInterfaceGUID to search for.</param> /// <param name="deviceRegistryList">A list of device paths associated with the <paramref name="deviceInterfaceGuid"/>.</param> /// <returns>True of one or more device paths was found.</returns> /// <remarks> /// Each <see cref="WinUsbRegistry"/> in the <paramref name="deviceRegistryList"/> represents a seperate WinUSB device (interface). /// </remarks> public static bool GetWinUsbRegistryList(Guid deviceInterfaceGuid, out List <WinUsbRegistry> deviceRegistryList) { deviceRegistryList = new List <WinUsbRegistry>(); int devicePathIndex = 0; SetupApi.SP_DEVICE_INTERFACE_DATA interfaceData = SetupApi.SP_DEVICE_INTERFACE_DATA.Empty; SetupApi.DeviceInterfaceDetailHelper detailHelper; SetupApi.SP_DEVINFO_DATA devInfoData = SetupApi.SP_DEVINFO_DATA.Empty; // [1] IntPtr deviceInfo = SetupApi.SetupDiGetClassDevs(ref deviceInterfaceGuid, null, IntPtr.Zero, SetupApi.DICFG.PRESENT | SetupApi.DICFG.DEVICEINTERFACE); if (deviceInfo != IntPtr.Zero) { while ((SetupApi.SetupDiEnumDeviceInterfaces(deviceInfo, null, ref deviceInterfaceGuid, devicePathIndex, ref interfaceData))) { int length = 1024; detailHelper = new SetupApi.DeviceInterfaceDetailHelper(length); bool bResult = SetupApi.SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, detailHelper.Handle, length, out length, ref devInfoData); if (bResult) { WinUsbRegistry regInfo = new WinUsbRegistry(); SetupApi.getSPDRPProperties(deviceInfo, ref devInfoData, regInfo.mDeviceProperties); // Use the actual winusb device path for SYMBOLIC_NAME_KEY. This will be used to open the device. regInfo.mDeviceProperties.Add(SYMBOLIC_NAME_KEY, detailHelper.DevicePath); #if VERY_DEBUG Debug.WriteLine(detailHelper.DevicePath); #endif regInfo.mDeviceInterfaceGuids = new Guid[] { deviceInterfaceGuid }; StringBuilder sbDeviceID = new StringBuilder(1024); if (SetupApi.CM_Get_Device_ID(devInfoData.DevInst, sbDeviceID, sbDeviceID.Capacity, 0) == SetupApi.CR.SUCCESS) { regInfo.mDeviceProperties[DEVICE_ID_KEY] = sbDeviceID.ToString(); } deviceRegistryList.Add(regInfo); } devicePathIndex++; } } if (devicePathIndex == 0) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetDevicePathList", typeof(SetupApi)); } if (deviceInfo != IntPtr.Zero) { SetupApi.SetupDiDestroyDeviceInfoList(deviceInfo); } return(devicePathIndex > 0); }
internal bool GetPipePolicy(PipePolicyType policyType, ref int valueLength, IntPtr pBuffer) { bool bSuccess = WinUsbAPI.WinUsb_GetPipePolicy(mUsbHandle, mEpNum, policyType, ref valueLength, pBuffer); if (!bSuccess) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetPipePolicy", this); } return(bSuccess); }
/// <summary> /// Sets an alternate interface for the most recent claimed interface. /// </summary> /// <param name="alternateID">The alternate interface to select for the most recent claimed interface See <see cref="ClaimInterface"/>.</param> /// <returns>True on success.</returns> public bool SetAltInterface(int alternateID) { int ret = MonoUsbApi.SetInterfaceAltSetting((MonoUsbDeviceHandle)mUsbHandle, mClaimedInteface, alternateID); if (ret != 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "SetAltInterface Failed", this); return(false); } return(true); }
/// <summary> /// Releases an interface that was previously claimed with <see cref="ClaimInterface"/>. /// </summary> /// <param name="interfaceID">The interface to release.</param> /// <returns>True on success.</returns> public bool ReleaseInterface(int interfaceID) { int ret = MonoUsbApi.ReleaseInterface((MonoUsbDeviceHandle)mUsbHandle, interfaceID); if (ret != 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "ReleaseInterface Failed", this); return(false); } return(true); }
internal bool SetPowerPolicy(PowerPolicyType policyType, int valueLength, IntPtr pBuffer) { bool bSuccess = WinUsbAPI.WinUsb_SetPowerPolicy(mUsbHandle, policyType, valueLength, pBuffer); if (!bSuccess) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetPowerPolicy", this); } return(bSuccess); }
/// <summary> /// Claims the specified interface of the device. /// </summary> /// <param name="interfaceID">The interface to claim.</param> /// <returns>True on success.</returns> public bool ClaimInterface(int interfaceID) { int ret = MonoUsbApi.ClaimInterface((MonoUsbDeviceHandle)mUsbHandle, interfaceID); if (ret != 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "ClaimInterface Failed", this); return(false); } mClaimedInteface = interfaceID; return(true); }
/// <summary> /// Sets the USB devices active configuration value. /// </summary> /// <param name="config">The active configuration value. A zero value means the device is not configured and a non-zero value indicates the device is configured.</param> /// <returns>True on success.</returns> /// <remarks> /// A USB device can have several different configurations, but only one active configuration. /// </remarks> public bool SetConfiguration(byte config) { int ret = MonoUsbApi.SetConfiguration((MonoUsbDeviceHandle)mUsbHandle, config); if (ret != 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "SetConfiguration Failed", this); return(false); } mCurrentConfigValue = config; return(true); }
/// <summary> /// Sets an alternate interface for the most recent claimed interface. /// </summary> /// <param name="alternateID">The alternate interface to select for the most recent claimed interface See <see cref="ClaimInterface"/>.</param> /// <returns>True on success.</returns> public bool SetAltInterface(int interfaceID, int alternateID) { int ret = MonoUsbApi.SetInterfaceAltSetting((MonoUsbDeviceHandle)mUsbHandle, interfaceID, alternateID); if (ret != 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "SetAltInterface Failed", this); return(false); } UsbAltInterfaceSettings[interfaceID & (UsbConstants.MAX_DEVICES - 1)] = (byte)alternateID; return(true); }
public override ErrorCode Wait(out int transferredCount, bool cancel) { if (mHasWaitBeenCalled) { throw new UsbException(this, "Repeated calls to wait with a submit is not allowed."); } transferredCount = 0; bool bSuccess; // Temporarily release the transfer lock while we wait for something to happen. int iWait = WaitHandle.WaitAny(new WaitHandle[] { mTransferCompleteEvent, mTransferCancelEvent }, mTimeout, UsbConstants.EXIT_CONTEXT); if (iWait == WaitHandle.WaitTimeout && !cancel) { return(ErrorCode.IoTimedOut); } mHasWaitBeenCalled = true; if (iWait != 0) { bSuccess = EndpointBase.mUsbApi.AbortPipe(EndpointBase.Handle, EndpointBase.EpNum); bool bTransferComplete = mTransferCompleteEvent.WaitOne(100, UsbConstants.EXIT_CONTEXT); mTransferCompleteEvent.Set(); if (!bSuccess || !bTransferComplete) { ErrorCode ec = bSuccess ? ErrorCode.Win32Error : ErrorCode.CancelIoFailed; UsbError.Error(ec, Marshal.GetLastWin32Error(), "Wait:AbortPipe Failed", this); return(ec); } if (iWait == WaitHandle.WaitTimeout) { return(ErrorCode.IoTimedOut); } return(ErrorCode.IoCancelled); } try { bSuccess = EndpointBase.mUsbApi.GetOverlappedResult(EndpointBase.Handle, Overlapped.GlobalOverlapped, out transferredCount, true); if (!bSuccess) { UsbError usbErr = UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetOverlappedResult", EndpointBase); return(usbErr.ErrorCode); } return(ErrorCode.None); } catch { return(ErrorCode.UnknownError); } }
internal static bool UsbIOSync(SafeHandle dev, int code, Object inBuffer, int inSize, IntPtr outBuffer, int outSize, out int ret) { SafeOverlapped deviceIoOverlapped = new SafeOverlapped(); ManualResetEvent hEvent = new ManualResetEvent(false); deviceIoOverlapped.Init(hEvent.GetSafeWaitHandle().DangerousGetHandle()); ret = 0; if (!Kernel32.DeviceIoControlAsObject(dev, code, inBuffer, inSize, outBuffer, outSize, ref ret, deviceIoOverlapped.GlobalOverlapped)) { int iError = Marshal.GetLastWin32Error(); if (iError != ERROR_IO_PENDING) { // Don't log errors for these control codes. do { if (code == LibUsbIoCtl.GET_REG_PROPERTY) { break; } if (code == LibUsbIoCtl.GET_CUSTOM_REG_PROPERTY) { break; } UsbError.Error(ErrorCode.Win32Error, iError, String.Format("DeviceIoControl code {0:X8} failed:{1}", code, Kernel32.FormatSystemMessage(iError)), typeof(LibUsbDriverIO)); } while (false); #if !NETSTANDARD1_5 && !NETSTANDARD1_6 hEvent.Close(); #else hEvent.Dispose(); #endif return(false); } } if (Kernel32.GetOverlappedResult(dev, deviceIoOverlapped.GlobalOverlapped, out ret, true)) { #if !NETSTANDARD1_5 && !NETSTANDARD1_6 hEvent.Close(); #else hEvent.Dispose(); #endif return(true); } UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetOverlappedResult failed.\nIoCtlCode:" + code, typeof(LibUsbDriverIO)); #if !NETSTANDARD1_5 && !NETSTANDARD1_6 hEvent.Close(); #else hEvent.Dispose(); #endif return(false); }
/// <summary> /// Gets a <see cref="IUsbInterfaceDescriptor"/> for the specified AlternateInterfaceNumber, /// </summary> /// <param name="alternateInterfaceNumber">The alternate interface index for the <see cref="IUsbInterfaceDescriptor"/> to retrieve. </param> /// <param name="usbAltInterfaceDescriptor">The <see cref="IUsbInterfaceDescriptor"/> for the specified AlternateInterfaceNumber.</param> /// <returns>True on success.</returns> public bool QueryInterfaceSettings(byte alternateInterfaceNumber, ref IUsbInterfaceDescriptor usbAltInterfaceDescriptor) { bool bSuccess; UsbInterfaceDescriptor usbInterfaceDescriptor = new UsbInterfaceDescriptor(); bSuccess = WinUsbAPI.WinUsb_QueryInterfaceSettings(Handle, alternateInterfaceNumber, usbInterfaceDescriptor); if (!bSuccess) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "QueryInterfaceSettings", this); } usbAltInterfaceDescriptor = usbInterfaceDescriptor; return(bSuccess); }
///<summary> /// Opens the USB device handle. ///</summary> ///<returns> ///True if the device is already opened or was opened successfully. ///False if the device does not exists or is no longer valid. ///</returns> public override bool Open() { if (IsOpen) { return(true); } mUsbHandle = LibUsbDriverIO.OpenDevice(mDeviceFilename); if (!IsOpen) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "LibUsbDevice.Open Failed", this); return(false); } return(true); }
/// <summary> /// Wait for the transfer to complete, timeout, or get cancelled. /// </summary> /// <param name="transferredCount">The number of bytes transferred on <see cref="ErrorCode.Success"/>.</param> /// <param name="cancel">Not used for libusb-1.0. Transfers are always cancelled on timeout or error.</param> /// <returns><see cref="ErrorCode.Success"/> if the transfer completes successfully, otherwise one of the other <see cref="ErrorCode"/> codes.</returns> public override ErrorCode Wait(out int transferredCount, bool cancel) { transferredCount = 0; int ret = 0; MonoUsbError monoError; ErrorCode ec; int iWait = WaitHandle.WaitAny(new WaitHandle[] { mTransferCompleteEvent, mTransferCancelEvent }, Timeout.Infinite, UsbConstants.EXIT_CONTEXT); switch (iWait) { case 0: // TransferCompleteEvent if (mTransfer.Status == MonoUsbTansferStatus.TransferCompleted) { transferredCount = mTransfer.ActualLength; return(ErrorCode.Success); } string s; monoError = MonoUsbApi.MonoLibUsbErrorFromTransferStatus(mTransfer.Status); ec = MonoUsbApi.ErrorCodeFromLibUsbError((int)monoError, out s); UsbError.Error(ErrorCode.MonoApiError, (int)monoError, "Wait:" + s, EndpointBase); return(ec); case 1: // TransferCancelEvent ret = (int)mTransfer.Cancel(); bool bTransferComplete = mTransferCompleteEvent.WaitOne(100, UsbConstants.EXIT_CONTEXT); mTransferCompleteEvent.Set(); if (ret != 0 || !bTransferComplete) { ec = ret == 0 ? ErrorCode.CancelIoFailed : ErrorCode.MonoApiError; UsbError.Error(ec, ret, String.Format("Wait:Unable to cancel transfer or the transfer did not return after it was cancelled. Cancelled:{0} TransferCompleted:{1}", (MonoUsbError)ret, bTransferComplete), EndpointBase); return(ec); } return(ErrorCode.IoCancelled); default: // Critical failure timeout mTransfer.Cancel(); ec = ((EndpointBase.mEpNum & (byte)UsbCtrlFlags.Direction_In) > 0) ? ErrorCode.ReadFailed : ErrorCode.WriteFailed; mTransferCompleteEvent.Set(); UsbError.Error(ec, ret, String.Format("Wait:Critical timeout failure! The transfer callback function was not called within the allotted time."), EndpointBase); return(ec); } }
private MonoUsbError GetDeviceDescriptor(out MonoUsbDeviceDescriptor monoUsbDeviceDescriptor) { MonoUsbError ec = MonoUsbError.Success; monoUsbDeviceDescriptor = new MonoUsbDeviceDescriptor(); //Console.WriteLine("MonoUsbProfile:GetDeviceDescriptor"); ec = (MonoUsbError)MonoUsbApi.GetDeviceDescriptor(mMonoUSBProfileHandle, monoUsbDeviceDescriptor); if (ec != MonoUsbError.Success) { #if LIBUSBDOTNET UsbError.Error(ErrorCode.MonoApiError, (int)ec, "GetDeviceDescriptor Failed", this); #endif monoUsbDeviceDescriptor = null; } return(ec); }
/// <summary> /// Gets the USB devices active configuration value. /// </summary> /// <param name="config">The active configuration value. A zero value means the device is not configured and a non-zero value indicates the device is configured.</param> /// <returns>True on success.</returns> public override bool GetConfiguration(out byte config) { config = 0; int iconfig = 0; int ret = MonoUsbApi.GetConfiguration((MonoUsbDeviceHandle)mUsbHandle, ref iconfig); if (ret != 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "GetConfiguration Failed", this); return(false); } config = (byte)iconfig; mCurrentConfigValue = config; return(true); }
/// <summary> /// sets the alternate interface number for the previously claimed interface. <see cref="IUsbDevice.ClaimInterface"/> /// </summary> /// <param name="alternateID">The alternate interface number.</param> /// <returns>True on success.</returns> public bool SetAltInterface(int alternateID) { bool bSuccess; bSuccess = WinUsbAPI.WinUsb_SetCurrentAlternateSetting(mUsbHandle, (byte)alternateID); if (!bSuccess) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetCurrentAlternateSetting", this); } else { UsbAltInterfaceSettings[0] = (byte)alternateID; } return(bSuccess); }
/// <summary> /// Creates, fills and submits an asynchronous <see cref="UsbTransfer"/> context. /// </summary> /// <remarks> /// <note type="tip">This is a non-blocking asynchronous transfer function. This function returns immediately after the context is created and submitted.</note> /// </remarks> /// <param name="buffer">A caller-allocated buffer for the data that is transferred.</param> /// <param name="offset">Position in buffer that transferring begins.</param> /// <param name="length">Number of bytes, starting from thr offset parameter to transfer.</param> /// <param name="timeout">Maximum time to wait for the transfer to complete.</param> /// <param name="transferContext">On <see cref="ErrorCode.Success"/>, a new transfer context.</param> /// <returns><see cref="ErrorCode.Success"/> if the transfer context was created and <see cref="UsbTransfer.Submit"/> succeeded.</returns> /// <seealso cref="SubmitAsyncTransfer(object,int,int,int,out LibUsbDotNet.Main.UsbTransfer)"/> /// <seealso cref="NewAsyncTransfer"/> public virtual ErrorCode SubmitAsyncTransfer(IntPtr buffer, int offset, int length, int timeout, out UsbTransfer transferContext) { transferContext = CreateTransferContext(); transferContext.Fill(buffer, offset, length, timeout); ErrorCode ec = transferContext.Submit(); if (ec != ErrorCode.None) { transferContext.Dispose(); transferContext = null; UsbError.Error(ec, 0, "SubmitAsyncTransfer Failed", this); } return(ec); }
/// <summary> /// Resets the data toggle and clears the stall condition on an enpoint. /// </summary> /// <returns>True on success.</returns> public virtual bool Reset() { if (mIsDisposed) { throw new ObjectDisposedException(GetType().Name); } bool bSuccess = mUsbApi.ResetPipe(mUsbHandle, EpNum); if (!bSuccess) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "ResetPipe", this); } return(bSuccess); }
/// <summary> /// Cancels pending transfers and clears the halt condition on an enpoint. /// </summary> /// <returns>True on success.</returns> public override bool Reset() { if (IsDisposed) { throw new ObjectDisposedException(GetType().Name); } Abort(); int ret = MonoUsbApi.ClearHalt((MonoUsbDeviceHandle)Device.Handle, EpNum); if (ret < 0) { UsbError.Error(ErrorCode.MonoApiError, ret, "Endpoint Reset Failed", this); return(false); } return(true); }
/// <summary> /// Gets the device speed. /// </summary> /// <param name="deviceSpeed">The device speed.</param> /// <returns>True on success.</returns> public bool QueryDeviceSpeed(out DeviceSpeedTypes deviceSpeed) { deviceSpeed = DeviceSpeedTypes.Undefined; byte[] buf = new byte[1]; int uTransferLength = 1; bool bSuccess = WinUsbAPI.WinUsb_QueryDeviceInformation(mUsbHandle, DeviceInformationTypes.DeviceSpeed, ref uTransferLength, buf); if (bSuccess) { deviceSpeed = (DeviceSpeedTypes)buf[0]; } else { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "QueryDeviceInformation:QueryDeviceSpeed", this); } return(bSuccess); }
/// <summary> /// Gets an interface associated with this <see cref="WinUsbDevice"/>. /// </summary> /// <param name="associatedInterfaceIndex">The index to retrieve. (0 = next interface, 1= interface after next, etc.).</param> /// <param name="usbDevice">A new <see cref="WinUsbDevice"/> class for the specified AssociatedInterfaceIndex.</param> /// <returns>True on success.</returns> public bool GetAssociatedInterface(byte associatedInterfaceIndex, out WinUsbDevice usbDevice) { usbDevice = null; IntPtr pHandle = IntPtr.Zero; bool bSuccess = WinUsbAPI.WinUsb_GetAssociatedInterface(mUsbHandle, associatedInterfaceIndex, ref pHandle); if (bSuccess) { SafeWinUsbInterfaceHandle tempHandle = new SafeWinUsbInterfaceHandle(pHandle); usbDevice = new WinUsbDevice(mUsbApi, null, tempHandle, mDevicePath); } if (!bSuccess) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetAssociatedInterface", this); } return(bSuccess); }
private static ErrorCode GetConfigs(MonoUsbDevice usbDevice, out List <UsbConfigInfo> configInfoListRtn) { configInfoListRtn = new List <UsbConfigInfo>(); UsbError usbError = null; List <MonoUsbConfigDescriptor> configList = new List <MonoUsbConfigDescriptor>(); int iConfigs = usbDevice.Info.Descriptor.ConfigurationCount; for (int iConfig = 0; iConfig < iConfigs; iConfig++) { MonoUsbConfigHandle nextConfigHandle; int ret = MonoUsbApi.GetConfigDescriptor(usbDevice.mMonoUSBProfile.ProfileHandle, (byte)iConfig, out nextConfigHandle); Debug.Print("GetConfigDescriptor:{0}", ret); if (ret != 0 || nextConfigHandle.IsInvalid) { usbError = UsbError.Error(ErrorCode.MonoApiError, ret, String.Format("GetConfigDescriptor Failed at index:{0}", iConfig), usbDevice); return(usbError.ErrorCode); } try { MonoUsbConfigDescriptor nextConfig = new MonoUsbConfigDescriptor(); Marshal.PtrToStructure(nextConfigHandle.DangerousGetHandle(), nextConfig); UsbConfigInfo nextConfigInfo = new UsbConfigInfo(usbDevice, nextConfig); configInfoListRtn.Add(nextConfigInfo); } catch (Exception ex) { UsbError.Error(ErrorCode.InvalidConfig, Marshal.GetLastWin32Error(), ex.ToString(), usbDevice); } finally { if (!nextConfigHandle.IsInvalid) { nextConfigHandle.Close(); } } } return(ErrorCode.Success); }
public static bool SetupDiGetDeviceRegistryProperty(out byte[] regBytes, IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, SPDRP Property) { regBytes = null; byte[] tmp = new byte[1024]; int iReqSize; RegistryValueKind regValueType; if (!SetupDiGetDeviceRegistryProperty(DeviceInfoSet, ref DeviceInfoData, Property, out regValueType, tmp, tmp.Length, out iReqSize)) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetupDiGetDeviceRegistryProperty", typeof(SetupApi)); return(false); } regBytes = new byte[iReqSize]; Array.Copy(tmp, regBytes, regBytes.Length); return(true); }