Пример #1
0
        /// <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);
        }
Пример #2
0
        /// <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);
            }
        }
Пример #3
0
        /// <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);
        }
        /// <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);
        }
Пример #5
0
        ///<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);
        }
        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);
        }
Пример #7
0
        /// <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);
        }
Пример #8
0
 private void UsbDeviceOnUsbErrorEvent(object sender, UsbError usbError)
 {
     Main.SendDebug(String.Format("A USB Error Occured: {0}", usbError));
     if (Device == null || !Device.IsOpen)
     {
         throw new DeviceError(DeviceError.ErrorLevels.DeviceCrashed);
     }
 }
Пример #9
0
 private void UsbDevice_UsbErrorEvent(object sender, UsbError e)
 {
     LogLine("usb error: " + e.ToString());
     if (Settings.Default.UsbErrorIcon != MessageBoxIcon.None)
     {
         MessageBox.Show("UsbError: " + e.ToString(), "Error", MessageBoxButtons.OK, Settings.Default.UsbErrorIcon);
     }
 }
Пример #10
0
        /// <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);
        }
Пример #11
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);
        }
Пример #12
0
        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);
        }
Пример #13
0
        /// <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);
        }
Пример #14
0
        /// <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);
        }
Пример #15
0
        void OnUsbError(object sender, UsbError e)
        {
            if (suppressErrors)
            {
                return;
            }

            string prefix = String.Format("Driver.OnUsbError: sender {0}", sender.GetType());

            if (sender is UsbEndpointBase)
            {
                logger.error("{0} [UsbEndPointBase]: Win32ErrorNumber {1} ({2}): {3}",
                             prefix, e.Win32ErrorNumber, e.Win32ErrorString, e.Description);

                // Magic number 31 came from here: http://libusbdotnet.sourceforge.net/V2/html/718df290-f19a-9033-3a26-1e8917adf15d.htm
                if (e.Win32ErrorNumber == 31)
                {
                    UsbDevice usb = sender as UsbDevice;
                    if (usb.IsOpen)
                    {
                        UsbEndpointBase baseDevice = sender as UsbEndpointBase;
                        // UsbEndpointInfo uei = baseDevice.EndpointInfo;
                        // LibUsbDotNet.Descriptors.UsbEndpointDescriptor ued = uei.Descriptor;
                        logger.error("{0} [UsbEndPointBase]: usb device still open on endpoint {1}", prefix, baseDevice.EpNum);

                        if (baseDevice.Reset())
                        {
                            // docs say to set e.Handled = true here, but UsbError has no such field;
                            // was commented out here:
                            // https://github.com/GeorgeHahn/LibUsbDotNet/blob/master/LibWinUsb/UsbDevice.Error.cs#L49
                            return;
                        }
                    }
                }
            }
            else if (sender is UsbTransfer)
            {
                logger.error("{0} [UsbTransfer]: Win32ErrorNumber {1} ({2}): {3}",
                             prefix, e.Win32ErrorNumber, e.Win32ErrorString, e.Description);
                UsbEndpointBase ep = ((UsbTransfer)sender).EndpointBase;
                logger.error("{0} [UsbTransfer]: Endpoint = 0x{1:x2}", prefix, ep.EpNum);
            }
            else if (sender is Type)
            {
                Type t = sender as Type;
                logger.error("{0} [Type]: type = {1}", prefix, t.Name);
            }
            else
            {
                logger.error("{0} [other]: {1}", prefix, e.ToString());
                // is there anything we should DO here, other than logging it?
            }
        }
Пример #16
0
        /// <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);
        }
Пример #17
0
        /// <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);
        }
Пример #18
0
        /// <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);
        }
        internal static UsbError Error(ErrorCode errorCode, int ret, string description, object sender)
        {
            string win32Error = String.Empty;

            if (errorCode == ErrorCode.MonoApiError)
            {
                win32Error = ((Error)ret) + ":" + MonoUsbApi.StrError((Error)ret);
            }

            UsbError err = new UsbError(errorCode, ret, win32Error, description, sender);

            return(err);
        }
Пример #20
0
        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);
            }
        }
Пример #21
0
        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);
        }
Пример #22
0
        internal static void Error(object sender, string description, string functionName, int ret)
        {
            UsbError e = new UsbError(sender, description, functionName, ret);
            EventHandler <UsbError> temp = OnUsbError;

            if (temp != null)
            {
                temp(sender, e);
            }
            else
            {
                Debug.Print(e.ToString());
            }
        }
Пример #23
0
        /// <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);
        }
Пример #24
0
        ///<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);
        }
Пример #25
0
        /// <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);
            }
        }
Пример #26
0
        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);
        }
Пример #27
0
        /// <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);
        }
Пример #28
0
        /// <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);
        }
Пример #29
0
        /// <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);
        }
Пример #30
0
        /// <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);
        }