Close() public abstract method

Closes the UsbDevice and disposes any ActiveEndpoints.
public abstract Close ( ) : bool
return bool
        /// <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();
            }
        }
Beispiel #2
0
        public void Thu()
        {
            ErrorCode        ec = ErrorCode.None;
            UsbRegDeviceList lu = LibUsbDotNet.UsbDevice.AllDevices;

            MyUsbFinder = new UsbDeviceFinder(1614, 33024);
            LibUsbDotNet.UsbDevice MyUsbDevice = null;
            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                //MyUsbDevice = lu[0].Device;
                // 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
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface
                    wholeUsbDevice.ClaimInterface(1);
                }

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

                // open write endpoint0123456789
                UsbEndpointWriter writer =
                    MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);

                // write data, read data
                int bytesWritten;
                //ec = writer.Write(new byte[] { 0x00, 0x03, 0x00, 0x00, 0x00,
                // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 2000, out bytesWritten);

                //if (ec != ErrorCode.None)
                //    throw new Exception(UsbDevice.LastErrorString);
                ec = ErrorCode.None;

                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.
                    //  PrintHex(readBuffer, 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
                            wholeUsbDevice.ReleaseInterface(1);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();
                }
            }
        }
Beispiel #3
0
        //
        //переделать всё
        //
        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();
                }
            }
        }
        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();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();
                }

                // Wait for user input..
                Console.ReadKey();
            }
        }
Beispiel #5
0
        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();
            }
        }
        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();
            }
        }
        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();
            }
        }
Beispiel #8
0
        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;
            }
        }
Beispiel #9
0
        public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0F44, 0xEF12); //Polhemus Patriot

        #endregion Fields

        #region Methods

        public static void Main(string[] args)
        {
            byte[] writeBuffer;
            byte[] readBuffer;
            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);
                }

                //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();

                }
            }
        }
        /// <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();
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            ErrorCode errorCode = ErrorCode.None;

            try
            {
                UsbRegDeviceList regList = UsbDevice.AllDevices.FindAll(MyUsbFinder);
                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))
                {
                    // 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();
        }