Exemple #1
0
        public HeliosDevice(IUsbDevice usbDevice)
        {
            this.usbDevice = usbDevice;

            interruptEndpointReader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep03, 32, EndpointType.Interrupt);
            interruptEndpointWriter = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep06, EndpointType.Interrupt);
            bulkEndpointWriter      = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep02, EndpointType.Bulk);
        }
        private void _Init(bool throwErrors)
        {
            Dispose();

            _device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(_VENDOR_ID, _PRODUCT_ID1)) as IUsbDevice;
            if (_device == null)
            {
                _device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(_VENDOR_ID, _PRODUCT_ID2)) as IUsbDevice;
            }
            if (_device == null)
            {
                _device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(_VENDOR_ID, _PRODUCT_ID3)) as IUsbDevice;
            }
            if (_device == null)
            {
                if (throwErrors)
                {
                    throw new InvalidOperationException("Wireless receiver not found");
                }
            }
            else
            {
                _device.ClaimInterface(1);
                _device.SetConfiguration(1);

                _responses = new Dictionary <int, List <byte[]> >();
                var now = DateTime.Now;
                for (int i = 0; i < _NUMBER_OF_SLOTS; i++)
                {
                    var slot = new ReceiverSlot();

                    slot.DataWriter = _device.OpenEndpointWriter(_GetWriteEndpoint((i * 2) + 1));
                    slot.DataReader = _device.OpenEndpointReader(_GetReadEndpoint((i * 2) + 1));
                    slot.DataReader.DataReceived       += DataReader_DataReceived;
                    slot.DataReader.DataReceivedEnabled = true;
                    slot.HeadsetWriter = _device.OpenEndpointWriter(_GetWriteEndpoint((i * 2) + 2));
                    slot.HeadsetReader = _device.OpenEndpointReader(_GetReadEndpoint((i * 2) + 2));
                    slot.HeadsetReader.DataReceived       += HeadsetReader_DataReceived;
                    slot.HeadsetReader.DataReceivedEnabled = true;

                    _slots.Add(i + 1, slot);

                    _RefreshSlot(i + 1);
                }

                _refreshSlotsThread = new Thread(new ThreadStart(_RefreshSlots));
                _refreshSlotsThread.IsBackground = true;
                _refreshSlotsThread.Start();
            }
        }
Exemple #3
0
        /// <summary>
        /// Performs initialisation tasks required before enabling printing.
        /// </summary>
        /// <exception cref="DC.PrintingServices.PrinterNotFoundException">No printer can be found with the specified vendor id and product id.</exception>
        public void Initialise()
        {
            // Create a USB device finder for finding the printer.
            _deviceFinder = new UsbDeviceFinder(this.VendorID, this.ProductID);

            // Find and open a connection to the printer.
            _printer = UsbDevice.OpenUsbDevice(_deviceFinder);

            _printerUSBDevice = _printer as IUsbDevice;

            if (_printerUSBDevice != null)
            {
                // ANDREW LING [28 Feburary 2014]: Make the configuration and interface settings configurable.
                _printerUSBDevice.SetConfiguration(1);
                _printerUSBDevice.ClaimInterface(0);
            }
            else
            {
                // The printer cannot be located.

                // ANDREW LING [28 February 2014]: TODO: Log when the printer cannot be located.
                // ANDREW LING [28 February 2014]: TODO: Display an error message on screen when the printer cannot be located.

                throw new PrinterNotFoundException(this.VendorID, this.ProductID);
            }

            // ANDREW LING [28 February 2014]: TODO: Make the write end point ID configurable.
            _writer = _printerUSBDevice.OpenEndpointWriter(WriteEndpointID.Ep02);

            // Mark that the initialisation tasks have been completed.
            _initialised = true;
        }
Exemple #4
0
        public override bool Open()
        {
            try
            {
                UsbDeviceFinder MyUsbFinder   = new UsbDeviceFinder(((UsbConfigModel)Configuration).PID, ((UsbConfigModel)Configuration).VID);
                UsbRegistry     myUsbRegistry = UsbDevice.AllWinUsbDevices.Find(MyUsbFinder);

                if (myUsbRegistry is null)
                {
                    return(false);
                }
                // Open this usb device.

                _dev = UsbDevice.OpenUsbDevice(MyUsbFinder) as IUsbDevice;

                _dev.SetConfiguration(1);

                _dev.ClaimInterface(0);
                _writer = _dev.OpenEndpointWriter(WriteEndpointID.Ep01);
                _reader = _dev.OpenEndpointReader(ReadEndpointID.Ep01);
            }
            catch (Exception exp)
            {
                throw new Exception(exp.ToString());
            }
            return(true);
        }
Exemple #5
0
    void Setup()
    {
        if (UsbDev != null)
        {
            return;
        }

        UsbDev = FindDevice();

        if (!UsbDev.SetConfiguration(1))
        {
            throw new M4ATXException("Failed to set device config");
        }

        if (!UsbDev.ClaimInterface(0))
        {
            throw new M4ATXException("Failed to claim interface #0");
        }

        if (!UsbDev.SetAltInterface(0))
        {
            throw new M4ATXException("Failed to set alternate interface to 0");
        }

        Writer = UsbDev.OpenEndpointWriter(WriteEndpointID.Ep01);
        Reader = UsbDev.OpenEndpointReader(ReadEndpointID.Ep01);
    }
        public bool Reset()
        {
            bool ret = true;

            Close();

            //Start message thread
            _messageThread = new Thread(new ThreadStart(_SendMessages));
            _messageThread.IsBackground = true;
            _messageThread.Start();

            //Find device
            _device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(_VENDOR_ID, _PRODUCT_ID)) as IUsbDevice;

            if (_device != null)
            {
                //Set up the incoming and outgoing endpoints

                _reader = _device.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep03);
                _reader.DataReceived       += _reader_DataReceived;
                _reader.DataReceivedEnabled = true;

                lock (_writerLock)
                {
                    _writer = _device.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep02);
                }
            }
            else
            {
                ret = false;
            }

            return(ret);
        }
Exemple #7
0
        public UsbDevStream(IUsbDevice dev, WriteEndpointID writePipe, ReadEndpointID readPipe)
        {
            device    = dev;
            WritePipe = writePipe;
            ReadPipe  = readPipe;

            writer = device.OpenEndpointWriter(writePipe);
            reader = device.OpenEndpointReader(readPipe);

            Flush();
        }
Exemple #8
0
 private void SendData(byte[] data)
 {
     using (var writer = dev.OpenEndpointWriter(WriteEndpointID.Ep01))
     {
         int       transferred;
         ErrorCode ec = writer.Write(data, 10000, out transferred);
         if (ec != ErrorCode.None)
         {
             throw new Exception("Data not transferred! (Send) Error: " + ec.ToString() + " : " + LibUsbDotNet.UsbDevice.LastErrorString);
         }
         if (transferred != data.Length)
         {
             throw new Exception("Data not fully transferred! (Send)");
         }
     }
 }
        public void OnInitialize(USBSimulatorDevice device)
        {
            _device = device;

            //Fill the endpoint list as completely as we can
            Endpoints = new List <EndpointInformation>();
            int transferred;
            var configuration = new byte[255];
            int index         = 0;

            if (_forwardee.GetDescriptor(0x02, 0x00, 0x00, configuration, 255, out transferred))
            {
                //NOTE: Only supporting one configuration
                int totalLength = configuration[2] | (configuration[3] << 8);
                while (index < totalLength)
                {
                    if (configuration[index + 1] == 0x05)
                    {
                        //This is an endpoint descriptor
                        int endpoint = configuration[index + 2] & 0x7F;

                        if ((configuration[index + 2] & 0x80) > 0)
                        {
                            //Incoming endpoint
                            _readers.Add(endpoint, _forwardee.OpenEndpointReader(_GetReadEndpointId(endpoint)));
                            _readers[endpoint].DataReceived       += DeviceForwarder_DataReceived;
                            _readers[endpoint].DataReceivedEnabled = true;
                            Endpoints.Add(new EndpointInformation(endpoint, EndpointInformation.EndpointDirection.Incoming,
                                                                  (EndpointInformation.EndpointType)configuration[index + 3], configuration[index + 4] | (configuration[index + 5] << 8)));
                        }
                        else
                        {
                            //Outgoing endpoint
                            _writers.Add(endpoint, _forwardee.OpenEndpointWriter(_GetWriteEndpointId(endpoint)));
                            Endpoints.Add(new EndpointInformation(endpoint, EndpointInformation.EndpointDirection.Outgoing,
                                                                  (EndpointInformation.EndpointType)configuration[index + 3], configuration[index + 4] | (configuration[index + 5] << 8)));
                        }
                    }

                    index += configuration[index];
                }
            }
        }
        public Switch()
        {
            Console.WriteLine("Connecting to Switch");
            this.LibUsbContext = new UsbContext();
            var usbDeviceCollection = LibUsbContext.List();

            NX = usbDeviceCollection.FirstOrDefault(d => d.ProductId == PID && d.VendorId == VID);

            if (NX == null)
            {
                throw new Exception("Unable to find Switch. Ensure Switch is connected and USB Install is open.");
            }

            NX.Open();
            NX.ClaimInterface(NX.Configs[0].Interfaces[0].Number);

            Writer = NX.OpenEndpointWriter(WriteEndpointID.Ep01);
            Reader = NX.OpenEndpointReader(ReadEndpointID.Ep01);
        }
Exemple #11
0
        public void Open()
        {
            if (!Driver.IsOpen)
            {
                Driver.Open();
                IUsbDevice wholeUsbDevice = Driver as IUsbDevice;
                if (wholeUsbDevice is not null)
                {
                    wholeUsbDevice.Open();
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
                //Get the first config number of the interface
                Driver.ClaimInterface(Driver.Configs[0].Interfaces[0].Number);
                EndpointWriter = Driver.OpenEndpointWriter(WriteEndpointID.Ep01);
                EndpointReader = Driver.OpenEndpointReader(ReadEndpointID.Ep01);

                DeviceInfo.Manufacturer = Driver.Info.Manufacturer;
                DeviceInfo.Product      = Driver.Info.Product;
                DeviceInfo.SerialNumber = Driver.Info.SerialNumber;
            }
            DeviceInfo.Ready = Driver.IsOpen;
        }
Exemple #12
0
 public UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID)
 {
     return(_device.OpenEndpointWriter(writeEndpointID));
 }
Exemple #13
0
        public PSVR()
        {
            LibUsbDotNet.Main.UsbDeviceFinder find = new LibUsbDotNet.Main.UsbDeviceFinder(0x054C, 0x09AF);
            var device = LibUsbDotNet.UsbDevice.OpenUsbDevice(find);

            if (device == null)
            {
                throw new InvalidOperationException("No device found");
            }

            dev = (IUsbDevice)device;

            for (int ifa = 0; ifa < device.Configs[0].InterfaceInfoList.Count; ifa++)
            {
                var iface = device.Configs[0].InterfaceInfoList[ifa];

                if (iface.Descriptor.InterfaceID == 5)
                {
                    dev.SetConfiguration(1);

                    var res = dev.ClaimInterface(5);
                    res = dev.ClaimInterface(4);

                    writer = dev.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep04);

                    reader = dev.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep03, 64);
                    reader.DataReceived       += Reader_DataReceived;
                    reader.DataReceivedEnabled = true;
                    //reader.
                    //Task.Run(() =>
                    //{

                    //    byte[] buffer = new byte[1];

                    //    while (dev != null)
                    //    {
                    //        int len;

                    //        var data = reader.Read(buffer, 10000, out len);


                    //        if (len != 64)
                    //            continue;

                    //        if (SensorDataUpdate == null)
                    //            return;

                    //        var rep = parse(buffer);

                    //        SensorDataUpdate(this, new PSVRSensorEventArgs { SensorData = rep.sensor });
                    //    }

                    //});

                    aliveTimer = new Timer(is_alive);
                    aliveTimer.Change(2000, 2000);

                    return;
                }
            }

            throw new InvalidOperationException("Device does not match descriptor");
        }
        public static void Main(string[] args)
        {
            Error ec = Error.Success;

            using (UsbContext context = new UsbContext())
            {
                try
                {
                    // Find and open the usb device.
                    MyUsbDevice = context.Find(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.
                    var reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

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

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

                    Error       ecWrite;
                    Error       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 != Error.Success)
                        {
                            throw new Exception("Submit Async Read Failed.");
                        }

                        ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, 100, out usbWriteTransfer);
                        if (ecWrite != Error.Success)
                        {
                            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} Error:{1}", transferredIn, ecRead);
                        Console.WriteLine("Write :{0} Error:{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 != Error.Success ? 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;
                    }

                    // Wait for user input..
                    Console.ReadKey();
                }
            }
        }
        public void Print(String print)
        {
            //t();
            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
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface
                    wholeUsbDevice.ClaimInterface(1);
                }
                int    count = 0;
                byte[] data  = new byte[256];


                //var controlPacket = new UsbSetupPacket();
                //controlPacket.Request = 0xA0;
                //controlPacket.RequestType = 64;
                //controlPacket.Value =  0x07F92;
                //controlPacket.Index = 0;

                //int written;

                // MyUsbDevice.ControlTransfer(ref controlPacket, data, data.Length, out written);


                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
                int bytesWritten;
                writer.Write(new byte[] { 0x1B, 0x40 }, 2000, out bytesWritten);

                //ec = writer.Write(new byte[] { 0x1D, 0x68, 0x70 }, 2000, out bytesWritten);
                //ec = writer.Write(new byte[] { 0x1D, 0x77, 0x02, 0x1D, 0x48, 0x03, 0x1D, 0x6B, 0x06 }, 2000, out bytesWritten);
                //ec = writer.Write(Encoding.Default.GetBytes("A1234567890A"), 2000, out bytesWritten); // надпись штрихкода
                //ec = writer.Write(new byte[] { 0x00, 0x56, 0x30 }, 2000, out bytesWritten);
                //ec = writer.Write(new byte[] { 0x09 }, 2000, out bytesWritten); ec = writer.Write(new byte[] { 0x09 }, 2000, out bytesWritten);


                ec = writer.Write(Encoding.Default.GetBytes(print + "\x0A"), 2000, out bytesWritten);



                //ec = writer.Write(new byte[] { 0x09 }, 2000, out bytesWritten);
                if (ec != ErrorCode.None)
                {
                }


                UsbSetupPacket packet = new UsbSetupPacket((byte)UsbRequestType.TypeVendor, (byte)1, (short)0, 0, 0);
                int            temp1;
                byte[]         temp2 = Encoding.Default.GetBytes("Hello");
                MyUsbDevice.ControlTransfer(ref packet, temp2, 0, out temp1);


                // open read endpoint
                using (var write = wholeUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep04, EndpointType.Interrupt))
                {
                    write.Write(new byte[] { 0x10, 0x04, 0x01 }, 2000, out count);
                }
                //using(var read = wholeUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01, 64, EndpointType.Bulk))
                //      {
                //          read.Read(data, 50, out count);
                //      }

                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(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

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

                // Wait for user input..
                //     Console.ReadKey();
            }
        }
Exemple #16
0
        public static void Main(string[] args)
        {
            var ec = Error.Success;

            using (var context = new UsbContext())
            {
                try
                {
                    // Find and open the usb device.
                    MyUsbDevice = context.Find(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.
                    var 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.
                    var reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);

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

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

                    if (!string.IsNullOrEmpty(cmdLine))
                    {
                        ec = writer.Write(Encoding.Default.GetBytes(cmdLine), 2000, out var bytesWritten);
                        if (ec != Error.Success)
                        {
                            throw new Exception($"The command line {cmdLine} failed with an error of {ec}.");
                        }

                        var readBuffer = new byte[1024];
                        while (ec == Error.Success)
                        {
                            // 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 var 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 != Error.Success ? 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.
                            var wholeUsbDevice = MyUsbDevice as IUsbDevice;
                            if (!ReferenceEquals(wholeUsbDevice, null))
                            {
                                // Release interface #0.
                                wholeUsbDevice.ReleaseInterface(0);
                            }

                            MyUsbDevice.Close();
                        }
                        MyUsbDevice = null;
                    }

                    // Wait for user input..
                    Console.ReadKey();
                }
            }
        }
        public void connectReceiver()
        {
            // Connect to the Xbox Wireless Receiver and register the endpoint
            // readers/writers as necessary.
            try
            {
                // Open the Xbox Wireless Receiver as a USB device
                // VendorID 0x045e, ProductID 0x0719
                wirelessReceiver = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x045E, 0x0719)) as IUsbDevice;

                // If primary IDs not found attempt secondary IDs
                // VendorID 0x045e, Product ID 0x0291
                if (wirelessReceiver == null)
                {
                    wirelessReceiver = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x045E, 0x0291)) as IUsbDevice;
                }

                // If secondary IDs not found report the error
                if (wirelessReceiver == null)
                {
                    parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                        "ERROR: Wireless Receiver Not Found.");
                }
                else
                {
                    // Set the Configuration, Claim the Interface
                    wirelessReceiver.ClaimInterface(1);
                    wirelessReceiver.SetConfiguration(1);

                    // Log if the Wireless Receiver was connected to successfully
                    if (wirelessReceiver.IsOpen)
                    {
                        receiverAttached = true;
                        parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                            "Xbox 360 Wireless Receiver Connected.");

                        // Connect Bulk Endpoint Readers/Writers and register the receiving event handler
                        // Controller 1
                        epReaders[0] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep01);
                        epWriters[0] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep01);
                        epReaders[0].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[0].processDataPacket);
                        epReaders[0].DataReceivedEnabled = true;
                        xboxControllers[0].registerEndpointWriter(epWriters[0]);

                        // Controller 2
                        epReaders[1] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep03);
                        epWriters[1] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep03);
                        epReaders[1].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[1].processDataPacket);
                        epReaders[1].DataReceivedEnabled = true;
                        xboxControllers[1].registerEndpointWriter(epWriters[1]);

                        // Controller 3
                        epReaders[2] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep05);
                        epWriters[2] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep05);
                        epReaders[2].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[2].processDataPacket);
                        epReaders[2].DataReceivedEnabled = true;
                        xboxControllers[2].registerEndpointWriter(epWriters[2]);

                        // Controller 4
                        epReaders[3] = wirelessReceiver.OpenEndpointReader(ReadEndpointID.Ep07);
                        epWriters[3] = wirelessReceiver.OpenEndpointWriter(WriteEndpointID.Ep07);
                        epReaders[3].DataReceived       += new EventHandler <EndpointDataEventArgs>(xboxControllers[3].processDataPacket);
                        epReaders[3].DataReceivedEnabled = true;
                        xboxControllers[3].registerEndpointWriter(epWriters[3]);

                        parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                            "Searching for Controllers...Press the Guide Button Now.");
                    }
                }
            }
            catch
            {
                parentWindow.Invoke(new logCallback(parentWindow.logMessage),
                                    "ERROR: Problem Connecting to Wireless Receiver.");
            }
        }
        public bool Reset()
        {
            bool ret = true;

              Close();

              //Start message thread
              _messageThread = new Thread(new ThreadStart(_SendMessages));
              _messageThread.IsBackground = true;
              _messageThread.Start();

              //Find device
              _device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(_VENDOR_ID, _PRODUCT_ID)) as IUsbDevice;

              if (_device != null)
              {
            //Set up the incoming and outgoing endpoints

            _reader = _device.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep03);
            _reader.DataReceived += _reader_DataReceived;
            _reader.DataReceivedEnabled = true;

            lock (_writerLock)
            {
              _writer = _device.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep02);
            }
              }
              else
            ret = false;

              return ret;
        }