コード例 #1
0
        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();
            }
        }
コード例 #2
0
ファイル: UsbHelper.cs プロジェクト: jiazy0125/nTestSystem
        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);
        }
コード例 #3
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);
    }
コード例 #4
0
        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);
        }
コード例 #5
0
ファイル: MyRead.cs プロジェクト: tate98/USB
        public static void Main(string[] args)
        {
            using (UsbContext context = new UsbContext())
            {
                // 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.");
                }
                // open read endpoint 1.
                var    reader     = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                byte[] readBuffer = new byte[1024];
                while (true)
                {
                    int bytesRead;
                    reader.Read(readBuffer, 5000, out bytesRead);
                    Console.WriteLine("{0} bytes read", bytesRead);
                    // Write to the console.
                    Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                }
            }
        }
コード例 #6
0
        public async Task <bool> GetDevice(UsbContext context)
        {
            Console.WriteLine("Looking for device ...");
            // Dump all devices and descriptor information to console output.
            foreach (var usbDevice in context.List())
            {
                if (usbDevice.TryOpen())
                {
                    if (usbDevice.Info.Manufacturer == mfrName)
                    {
                        device = usbDevice;
                        if (usbDevice.ClaimInterface(interfaceID))
                        {
                            monitorBuddyDevice = usbDevice;

                            // Console.WriteLine($"Device open, interface 0 claimed: {device.ToString()}");
                            endpointReader = monitorBuddyDevice.OpenEndpointReader(ReadEndpointID.Ep01, endpointBufferSize, EndpointType.Interrupt);

                            return(true);
                        }
                    }
                }
            }

            await Task.Delay(2000);

            return(false);
        }
コード例 #7
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);
        }
コード例 #8
0
        public UsbDevStream(IUsbDevice dev, WriteEndpointID writePipe, ReadEndpointID readPipe)
        {
            device    = dev;
            WritePipe = writePipe;
            ReadPipe  = readPipe;

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

            Flush();
        }
コード例 #9
0
        private void buttonRead_Click(object sender, EventArgs e)
        {
            dev = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x1915, 0x7B));
//            bool success = reg.Open(out dev);
            IUsbDevice wholeUsbDevice = dev as IUsbDevice;

            wholeUsbDevice.SetConfiguration(1);
            wholeUsbDevice.ClaimInterface(0);
            rdr = wholeUsbDevice.OpenEndpointReader((ReadEndpointID)0x81);
            rdr.Flush();
            Read();
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: zrbruce/FlingOS
 private void ReadData(byte[] data)
 {
     using (var reader = dev.OpenEndpointReader(ReadEndpointID.Ep01))
     {
         int       transferred;
         ErrorCode ec = reader.Read(data, 10000, out transferred);
         if (ec != ErrorCode.None)
         {
             throw new Exception("Data not transferred! (Read) Error: " + ec.ToString() + " : " + LibUsbDotNet.UsbDevice.LastErrorString);
         }
         if (transferred != data.Length)
         {
             throw new Exception("Data not fully transferred! (Read)");
         }
     }
 }
コード例 #11
0
ファイル: DeviceForwarder.cs プロジェクト: vebin/USBSimulator
        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];
                }
            }
        }
コード例 #12
0
        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);
        }
コード例 #13
0
ファイル: UsbDriver.cs プロジェクト: rengglian/TestGui
        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;
        }
コード例 #14
0
        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.");
            }
        }
コード例 #15
0
ファイル: ReadWrite.cs プロジェクト: xutao650/LibUsbDotNet
        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();
                }
            }
        }
コード例 #16
0
        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-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.
                    var reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);


                    byte[] readBuffer = new byte[1024];
                    while (ec == Error.Success)
                    {
                        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 != 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();
                }
            }
        }
コード例 #17
0
 public UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID, int readBufferSize)
 {
     return(_device.OpenEndpointReader(readEndpointID, readBufferSize));
 }
コード例 #18
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");
        }
コード例 #19
0
        public void Start()
        {
            lock (_lock)
            {
                UsbRegDeviceList allLibUsbDevices = UsbDevice.AllLibUsbDevices;
                if (allLibUsbDevices.Count > 0)
                {
                    UsbDevice dev;
                    IsOpen = ((LibUsbRegistry)allLibUsbDevices.First()).Open(out dev);
                    _device = dev as IUsbDevice;
                    // Select config
                    bool configuration = _device.SetConfiguration(1);

                    // Claim interface
                    bool claimInterface = _device.ClaimInterface(0);
                    /*bool found = false;
                byte readerId = (byte) ReadEndpointID.Ep01;
                while (!found && (byte)readerId <= (byte)ReadEndpointID.Ep15)
                {
                    _reader = _device.OpenEndpointReader((ReadEndpointID)readerId);
                    byte[] buffer = new byte[1024];
                    int length;
                    ErrorCode ret = _reader.Read(buffer, 100, out length);
                    found = (ret != ErrorCode.Win32Error);
                    readerId++;
                }*/
                    EndPointId = GetEndpoint();
                    _reader = _device.OpenEndpointReader(EndPointId);
                    _thread.Start();
                    //_reader.DataReceivedEnabled = true;
                    //_reader.ReadBufferSize = 8;
                    //_reader.DataReceived += OnReaderDataReceived;
                }
            }
        }
コード例 #20
0
        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;
        }
コード例 #21
0
        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();
                }
            }
        }