当前位置: 首页>>代码示例>>C#>>正文


C# UsbDevice.Close方法代码示例

本文整理汇总了C#中LibUsbDotNet.UsbDevice.Close方法的典型用法代码示例。如果您正苦于以下问题:C# UsbDevice.Close方法的具体用法?C# UsbDevice.Close怎么用?C# UsbDevice.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在LibUsbDotNet.UsbDevice的用法示例。


在下文中一共展示了UsbDevice.Close方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CrazyradioDriver

        /// <summary>
        ///     Creates and initializes an instance of a Crazyradio USB dongle driver.
        /// </summary>
        /// <param name="crazyradioUsbDevice"> The UsbDevice to use in this driver. </param>
        public CrazyradioDriver(UsbDevice crazyradioUsbDevice)
        {
            Log.Debug("Received UsbDevice to use in CrazyradioDriver.");

            if (crazyradioUsbDevice == null)
            {
                Log.Error("UsbDevice is null.");
                throw new ArgumentNullException("crazyradioUsbDevice");
            }

            _crazyradioUsbDevice = crazyradioUsbDevice;

            if (IsCrazyradioUsbDongle(_crazyradioUsbDevice))
            {
                Log.Debug("UsbDevice is in fact a Crazyradio USB dongle.");

                CheckFirmwareVersion();
            }
            else
            {
                const string message = "UsbDevice is not a Crazyradio USB dongle.";
                Log.Error(message);
                throw new CrazyradioDriverException(message);
            }

            if (_crazyradioUsbDevice.IsOpen)
            {
                Log.Debug("UsbDevice is open. Closing until user opens to prevent inconsistent driver state.");

                _crazyradioUsbDevice.Close();
            }
        }
开发者ID:chungInShing,项目名称:CrazyflieDotNet,代码行数:36,代码来源:CrazyradioDriver.cs

示例2: connect

        //
        //переделать всё
        //
        private void connect()
        {
            if (comboBox1.SelectedIndex != -1)
                MyUsbFinder = new UsbDeviceFinder(Convert.ToInt32(devices_libusb[comboBox1.SelectedIndex].VID, 16),
                    Convert.ToInt32(devices_libusb[comboBox1.SelectedIndex].PID, 16));
            DataPoint temp = new DataPoint();
            ErrorCode ec = ErrorCode.None;
            try
            {
                //открываем поток
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }

                //читает 1ый эндпоинт
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader((ReadEndpointID)comboBox2.SelectedItem);

                byte[] readBuffer = new byte[1024];
                int bytesRead;

                //Возвращает данные или ошибку, если через 5 секунд ничего не было возвращено
                ec = reader.Read(readBuffer, 5000, out bytesRead);

                if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
                try
                {
                    if (trying)
                    {
                        temp.SetValueXY(i,
                            Convert.ToDouble(Encoding.Default.GetString(readBuffer, 0, bytesRead).Replace('.', ',')));
                        i++;
                        chart1.Series[0].Points.Add(temp);
                        data.Add(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                    }
                }
                catch
                {
                    trying = false;
                }
                textBox2.AppendText(Encoding.Default.GetString(readBuffer, 0, bytesRead));
            }
            catch (Exception ex)
            {
                //кидает ошибку и останавливает таймер при ошибке
                timer1.Stop();
                MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                //закрывает поток
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;
                    UsbDevice.Exit();
                }
            }
        }
开发者ID:Tradition-junior,项目名称:usb_monitor,代码行数:77,代码来源:Form1.cs

示例3: Main

        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;
            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                // If this is a "whole" usb device (libusb-win32, linux libusb)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                // open write endpoint 1.
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // the write test data.
                string testWriteString = "ABCDEFGH";

                ErrorCode ecWrite;
                ErrorCode ecRead;
                int transferredOut;
                int transferredIn;
                UsbTransfer usbWriteTransfer;
                UsbTransfer usbReadTransfer;
                byte[] bytesToSend = Encoding.Default.GetBytes(testWriteString);
                byte[] readBuffer = new byte[1024];
                int testCount = 0;
                do
                {
                    // Create and submit transfer
                    ecRead = reader.SubmitAsyncTransfer(readBuffer, 0, readBuffer.Length, 100, out usbReadTransfer);
                    if (ecRead != ErrorCode.None) throw new Exception("Submit Async Read Failed.");

                    ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, 100, out usbWriteTransfer);
                    if (ecWrite != ErrorCode.None)
                    {
                        usbReadTransfer.Dispose();
                        throw new Exception("Submit Async Write Failed.");
                    }

                    WaitHandle.WaitAll(new WaitHandle[] { usbWriteTransfer.AsyncWaitHandle, usbReadTransfer.AsyncWaitHandle },200,false);
                    if (!usbWriteTransfer.IsCompleted) usbWriteTransfer.Cancel();
                    if (!usbReadTransfer.IsCompleted) usbReadTransfer.Cancel();

                    ecWrite = usbWriteTransfer.Wait(out transferredOut);
                    ecRead = usbReadTransfer.Wait(out transferredIn);

                    usbWriteTransfer.Dispose();
                    usbReadTransfer.Dispose();

                    Console.WriteLine("Read  :{0} ErrorCode:{1}", transferredIn, ecRead);
                    Console.WriteLine("Write :{0} ErrorCode:{1}", transferredOut, ecWrite);
                    Console.WriteLine("Data  :" + Encoding.Default.GetString(readBuffer, 0, transferredIn));
                    testCount++;
                } while (testCount < 5);
                Console.WriteLine("\r\nDone!\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
//.........这里部分代码省略.........
开发者ID:CoreCompat,项目名称:LibUsbDotNet,代码行数:101,代码来源:ReadWriteAsync.cs

示例4: Main

        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                // it exposes an IUsbDevice interface. If not (WinUSB) the
                // 'wholeUsbDevice' variable will be null indicating this is
                // an interface of a device; it does not require or support
                // configuration and interface selection.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                byte[] readBuffer = new byte[1024];
                while (ec == ErrorCode.None)
                {
                    int bytesRead;

                    // If the device hasn't sent data in the last 5 seconds,
                    // a timeout error (ec = IoTimedOut) will occur.
                    ec = reader.Read(readBuffer, 5000, out bytesRead);

                    if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
                    Console.WriteLine("{0} bytes read", bytesRead);

                    // Write that output to the console.
                    Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                }

                Console.WriteLine("\r\nDone!\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();

                }

                // Wait for user input..
                Console.ReadKey();
            }
        }
开发者ID:CoreCompat,项目名称:LibUsbDotNet,代码行数:87,代码来源:ReadOnly.cs

示例5: Main

        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                // If this is a "whole" usb device (libusb-win32, linux libusb)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                // open write endpoint 1.
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // Remove the exepath/startup filename text from the begining of the CommandLine.
                string cmdLine = Regex.Replace(
                    Environment.CommandLine, "^\".+?\"^.*? |^.*? ", "", RegexOptions.Singleline);

                if (!String.IsNullOrEmpty(cmdLine))
                {
                    int bytesWritten;
                    ec = writer.Write(Encoding.Default.GetBytes(cmdLine), 2000, out bytesWritten);
                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

                    byte[] readBuffer = new byte[1024];
                    while (ec == ErrorCode.None)
                    {
                        int bytesRead;

                        // If the device hasn't sent data in the last 100 milliseconds,
                        // a timeout error (ec = IoTimedOut) will occur.
                        ec = reader.Read(readBuffer, 100, out bytesRead);

                        if (bytesRead == 0) throw new Exception("No more bytes!");

                        // Write that output to the console.
                        Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                    }

                    Console.WriteLine("\r\nDone!\r\n");
                }
                else
                    throw new Exception("Nothing to do.");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();

                }

                // Wait for user input..
                Console.ReadKey();
            }
//.........这里部分代码省略.........
开发者ID:CharlesVerschuur,项目名称:LibUsbDotNet,代码行数:101,代码来源:ReadWrite.cs

示例6: Main

        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                // it exposes an IUsbDevice interface. If not (WinUSB) the
                // 'wholeUsbDevice' variable will be null indicating this is
                // an interface of a device; it does not require or support
                // configuration and interface selection.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                // open write endpoint 1.
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                // Remove the exepath/startup filename text from the begining of the CommandLine.
                string cmdLine = Regex.Replace(
                    Environment.CommandLine, "^\".+?\"^.*? |^.*? ", "", RegexOptions.Singleline);

                if (!String.IsNullOrEmpty(cmdLine))
                {
                    reader.DataReceived += (OnRxEndPointData);
                    reader.DataReceivedEnabled = true;

                    int bytesWritten;
                    ec = writer.Write(Encoding.Default.GetBytes(cmdLine), 2000, out bytesWritten);
                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

                    LastDataEventDate = DateTime.Now;
                    while ((DateTime.Now - LastDataEventDate).TotalMilliseconds < 100)
                    {
                    }

                    // Always disable and unhook event when done.
                    reader.DataReceivedEnabled = false;
                    reader.DataReceived -= (OnRxEndPointData);

                    Console.WriteLine("\r\nDone!\r\n");
                }
                else
                    throw new Exception("Nothing to do.");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }
                        MyUsbDevice.Close();
                    }
                }
                MyUsbDevice = null;

                // Free usb resources
                UsbDevice.Exit();

                // Wait for user input..
                Console.ReadKey();
            }
        }
开发者ID:CoreCompat,项目名称:LibUsbDotNet,代码行数:97,代码来源:ReadWriteEventDriven.cs

示例7: Start

        public void Start()
        {
            var USBFinder = new UsbDeviceFinder(0x057E, 0x0337);
            GCNAdapter = UsbDevice.OpenUsbDevice(USBFinder);

            gcn1DZ = new ControllerDeadZones();

            if (GCNAdapter != null)
            {
                int transferLength;
                
                writer = GCNAdapter.OpenEndpointWriter(WriteEndpointID.Ep02);

                //prompt controller to start sending
                writer.Write(Convert.ToByte((char)19), 10, out transferLength);

                try
                {
                    if (!JoystickHelper.checkJoystick(ref gcn1, 1)) { SystemHelper.CreateJoystick(1); }

                    if (gcn1Enabled && gcn1.AcquireVJD(1))
                    {
                        gcn1ok = true;
                        gcn1.ResetAll();
                    }
                }
                catch (Exception ex)
                {
                    DriverLog(null, new Logging.LogEventArgs("Error: " + ex.ToString()));
                    if (ex.Message.Contains("HRESULT: 0x8007000B"))
                    {
                        DriverLog(null, new Logging.LogEventArgs("Error: vJoy driver mismatch. Did you install the wrong version (x86/x64)?"));
                        Driver.run = false;
                        return;
                    }
                }

                if (noEventMode)
                {
                    DriverLog(null, new Logging.LogEventArgs("Driver successfully started, entering input loop."));
                    run = true;

                    while (run)
                    {
                        if (gcn1ok)
                        {
                            JoystickHelper.setJoystick(ref gcn1, Bot.Instance.State, 1, gcn1DZ);
                        }
                    }

                    if (GCNAdapter != null)
                    {
                        if (GCNAdapter.IsOpen)
                        {
                            if (!ReferenceEquals(wholeGCNAdapter, null))
                            {
                                wholeGCNAdapter.ReleaseInterface(0);
                            }
                            GCNAdapter.Close();
                        }
                        GCNAdapter = null;
                        UsbDevice.Exit();
                        DriverLog(null, new Logging.LogEventArgs("Closing driver thread..."));
                    }
                    DriverLog(null, new Logging.LogEventArgs("Driver thread has been stopped."));
                }
                else
                {
                    DriverLog(null, new Logging.LogEventArgs("Driver successfully started, entering input loop."));
                    //using  Interrupt request instead of looping behavior.
                    reader.DataReceivedEnabled = true;
                    reader.DataReceived += reader_DataReceived;
                    reader.ReadBufferSize = 37;
                    reader.ReadThreadPriority = System.Threading.ThreadPriority.Highest;
                    run = true;
                }
            }
            else
            {
                DriverLog(null, new Logging.LogEventArgs("GCN Adapter not detected."));
                Driver.run = false;
            }
        }
开发者ID:nawns,项目名称:lundgren,代码行数:83,代码来源:Driver.cs

示例8: UsbDeviceFinder


//.........这里部分代码省略.........
                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                //Polhemus uses EndPoint 2 for both read and write
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);

                while (true)
                {
                    Console.Write("New command: ");
                    string cmdLine = Console.ReadLine();
                    if (cmdLine == "") break;
                    if (cmdLine.Substring(0, 1) == "^") //control code
                    {
                        int ib = Encoding.ASCII.GetBytes(cmdLine.Substring(1, 1))[0];
                        writeBuffer = new byte[cmdLine.Length];
                        writeBuffer[0] = (byte)(ib & 0x1F); //calculate control code
                        if (cmdLine.Length > 2) //then there are arguments
                        {
                            byte[] arg = Encoding.ASCII.GetBytes(cmdLine.Substring(2)); //get arguments
                            for (int i = 0; i < arg.Length; i++) //and place in buffer
                                writeBuffer[i + 1] = arg[i];
                        }
                        writeBuffer[writeBuffer.Length - 1] = 0x0D; //CR
                    }
                    else //straight ASCII string command
                        writeBuffer = Encoding.ASCII.GetBytes(cmdLine +
                            ((cmdLine != "P") ? "\r" : ""));

                    int bytesWritten;
                    ec = writer.Write(writeBuffer, 1000, out bytesWritten);
                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

                    readBuffer = new byte[1024];
                    while (ec == ErrorCode.None)
                    {
                        int bytesRead;

                        // If the device hasn't sent data in the last 100 milliseconds,
                        // a timeout error (ec = IoTimedOut) will occur.
                        ec = reader.Read(readBuffer, 100, out bytesRead);

                        if (bytesRead == 0) break;

                        // Write that output to the console.
                        Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                        int byteCount = 1;
                        for (int i = 0; i < bytesRead; i++, byteCount++)
                        {
                            Console.Write(readBuffer[i].ToString("X2"));
                            if (byteCount >= 16)
                            {
                                byteCount = 0;
                                Console.Write(Environment.NewLine);
                            }
                            else
                                Console.Write(" ");
                        }
                        if (byteCount != 0) Console.Write(Environment.NewLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                Console.Read();
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();

                }
            }
        }
开发者ID:DOPS-CCI,项目名称:CCI_project,代码行数:101,代码来源:ReadWrite.cs

示例9: ServiceWorkerThread

        /// <summary> 
        /// The method performs the main function of the service. It runs on  
        /// a thread pool worker thread. 
        /// </summary> 
        /// <param name="state"></param> 
        private void ServiceWorkerThread(object state)
        {
            GetIDs();
            ErrorCode ec = ErrorCode.None;
            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

                byte[] readBuffer = new byte[1024];
                int bytesRead = 0;

                // Periodically check if the service is stopping.
                while (!this.stopping)
                {
                    //Thread.Sleep(2000);  // Simulate some lengthy operations.
                    ec = reader.Read(readBuffer, 30000, out bytesRead);
                    if (bytesRead > 0)
                    {
                        string trackString = Encoding.Default.GetString(readBuffer, 0, bytesRead);
                        string[] words = trackString.Split('?');
                        System.IO.StreamWriter fileReader2 = new System.IO.StreamWriter(trackFile, true);

                        if (words.Length > 0)
                        {
                            //Console.WriteLine();
                            string[] track1 = words[0].Split('%');
                            if (track1.Length > 1 && track1[1].Length > 0)
                            {
                                fileReader2.WriteLine(track1[1]);
                                //Console.WriteLine(track1[1]);
                            }
                        }
                        if (words.Length > 1)
                        {
                            string[] track2 = words[1].Split(';');
                            if (track2.Length > 1 && track2[1].Length > 0)
                            {
                                fileReader2.WriteLine(track2[1]);
                                //Console.WriteLine(track2[1]);
                            }
                        }
                        if (words.Length > 2)
                        {
                            string[] track3 = words[2].Split(';');
                            if (track3.Length > 1 && track3[1].Length > 0)
                            {
                                fileReader2.WriteLine(track3[1]);
                                //Console.WriteLine(track3[1]);
                            }
                        }
                        fileReader2.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(logFile, true);
                file.WriteLine();
                file.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                file.Close();
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }
                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;
                    UsbDevice.Exit();
                }
            }
            // Signal the stopped event.
            this.stoppedEvent.Set();
        }
开发者ID:vinayakkankanwadi,项目名称:CardReader,代码行数:99,代码来源:CardReader.cs

示例10: Main


//.........这里部分代码省略.........
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                UsbSetupPacket packet = new UsbSetupPacket(
                    (byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor),
                    (byte)0x12,
                    (short)0xc8,
                    (0x02 * 0x100) + 0x0a,
                    0);
                var buffer = new byte[] { 0x65, 0x0C, 0x02, 0xFF, 0x00, 0x00, 0x00, 0x00 };

                UsbInterfaceInfo usbInterfaceInfo = null;
                UsbEndpointInfo usbEndpointInfo = null;
                byte recipient = (byte)UsbRequestType.TypeVendor;
                var rubyPacket = new UsbSetupPacket(recipient, 0x0A, (byte)0x0c, 0x04, 0x01);

               // UsbEndpointBase.LookupEndpointInfo(MyUsbDevice.Configs[0], MyUsbDevice.ActiveEndpoints[0].EndpointInfo,
                 //                                  out usbInterfaceInfo, out usbEndpointInfo);
                int temp3;
                var RubyTransfer = MyUsbDevice.ControlTransfer(ref rubyPacket, null, 0, out temp3);
                // 0x21, 0x09, 0x0635, 0x000, "\x65\x0C#{data}\xFF\x00\x00\x00\x00", 0

                //int temp1;
                //var result1 = MyUsbDevice.ControlTransfer(ref packet, new byte[2], 8, out temp1);

                //packet = new UsbSetupPacket((byte)UsbRequestType.TypeVendor, (byte)0x12, (short)0x0C0A, (short)0x0200, 0x000);
                //int temp2;
                //var result2 = MyUsbDevice.ControlTransfer(ref packet, null, 0, out temp2);

                Console.WriteLine(string.Format("Result 1 : {0} - Length: {1}", RubyTransfer, temp3));
                //Console.WriteLine(string.Format("Result 2 : {0}", result2));

                //usb_control_msg(led->udev,
                //      usb_sndctrlpipe(led->udev, 0),
                //      0x12,
                //      0xc8,
                //      (0x02 * 0x100) + 0x0a,
                //      (0x00 * 0x100) + color,
                //      buffer,
                //      8,
                //      2 * HZ);

                // Then turn the LED on
                //Packet.Recipient = 8;
                //Packet.DeviceModel = 18;
                //Packet.Length = 0;
                //Packet.MajorCmd = 10;
                //Packet.MinorCmd = 12;
                ////switch (Color)
                ////{
                ////    case GREENLED: Packet.DataLSB = 1; break;
                ////    case REDLED: Packet.DataLSB = 2; break;
                ////    case BLUELED: Packet.DataLSB = 4; break;
                ////}
                //Packet.DataLSB = 4; // blue
                //Packet.DataMSB = 0;

            } catch(Exception e)
            {
                Console.WriteLine(e.Message);
            } finally
            {
                if (MyUsbDevice != null)
                {
                    if(endpointReader != null)
                        endpointReader.Abort();
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the
                        // 'wholeUsbDevice' variable will be null indicating this is
                        // an interface of a device; it does not require or support
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();

                }
            }

            Console.ReadKey();
        }
开发者ID:cprieto,项目名称:usblamp,代码行数:101,代码来源:Program.cs


注:本文中的LibUsbDotNet.UsbDevice.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。