Exemplo n.º 1
0
        internal List<UsbDevice> FindDevices(UsbRegDeviceList devlist)
        {
            List<UsbDevice> units = new List<UsbDevice>();

            foreach (UsbRegistry usb_registry in devlist)
            {
                UsbDevice myUsbDevice;
                if ( usb_registry.Open(out myUsbDevice))
                {
                    units.Add(myUsbDevice);
                }
            }

            return units;
        }
Exemplo n.º 2
0
        private void cboDevices_DropDown(object sender, EventArgs e)
        {
            // Get a new device list each time the device dropdown is opened
            cboDevices.Items.Clear();
            mRegDevices = UsbDevice.AllDevices;

            foreach (UsbRegistry regDevice in mRegDevices)
            {
                // add the Vid, Pid, and usb device description to the dropdown display.
                // NOTE: There are many more properties available to provide you with more device information.
                // See the LibUsbDotNet.Main.SPDRP enumeration.
                string sItem = String.Format("Vid:{0} Pid:{1} {2}",
                                             regDevice.Vid.ToString("X4"),
                                             regDevice.Pid.ToString("X4"),
                                             regDevice.FullName);
                cboDevices.Items.Add(sItem);
            }
            tsNumDevices.Text = cboDevices.Items.Count.ToString();
        }
Exemplo n.º 3
0
        public static void PrintUsbInfo()
        {
            UsbDevice        usbDevice  = null;
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            Console.WriteLine("Found {0} devices", allDevices.Count);

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                Console.WriteLine("Got device: {0}\r\n", usbRegistry.FullName);

                if (usbRegistry.Open(out usbDevice))
                {
                    Console.WriteLine("Device Information\r\n------------------");

                    Console.WriteLine("{0}", usbDevice.Info.ToString());

                    Console.WriteLine("VID & PID: {0} {1}", usbDevice.Info.Descriptor.VendorID, usbDevice.Info.Descriptor.ProductID);

                    Console.WriteLine("\r\nDevice configuration\r\n--------------------");
                    foreach (UsbConfigInfo usbConfigInfo in usbDevice.Configs)
                    {
                        Console.WriteLine("{0}", usbConfigInfo.ToString());

                        Console.WriteLine("\r\nDevice interface list\r\n---------------------");
                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = usbConfigInfo.InterfaceInfoList;
                        foreach (UsbInterfaceInfo usbInterfaceInfo in interfaceList)
                        {
                            Console.WriteLine("{0}", usbInterfaceInfo.ToString());

                            Console.WriteLine("\r\nDevice endpoint list\r\n--------------------");
                            ReadOnlyCollection <UsbEndpointInfo> endpointList = usbInterfaceInfo.EndpointInfoList;
                            foreach (UsbEndpointInfo usbEndpointInfo in endpointList)
                            {
                                Console.WriteLine("{0}", usbEndpointInfo.ToString());
                            }
                        }
                    }
                    usbDevice.Close();
                }
                Console.WriteLine("\r\n----- Device information finished -----\r\n");
            }
        }
        private void UpdateDeviceList()
        {
            _devices = UsbDevice.AllDevices;
            var count = 0;

            dataGridView1.SelectionChanged -= DataGridView1_SelectionChanged;
            dataGridView1.Rows.Clear();
            foreach (UsbRegistry dev in _devices)
            {
                count++;
                var      devinfo    = string.Format("VID_{0:X4} PID_{1:X4} REV_{2:X4}", dev.Vid, dev.Pid, dev.Rev);
                var      mfg        = dev.DeviceProperties.ContainsKey("Mfg") ? dev.DeviceProperties["Mfg"].ToString() : "";
                var      driverType = dev is WinUsbRegistry ? "WinUsb" : "LibUsb";
                string[] row        = { count.ToString(), devinfo, dev.Name, mfg, driverType, dev.SymbolicName };
                dataGridView1.Rows.Add(row);
            }
            dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
            DataGridView1_SelectionChanged(this, null);
        }
Exemplo n.º 5
0
        private void find()
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                UsbDevice tempDevice;
                if (usbRegistry.Open(out tempDevice))
                {
                    if (tempDevice.Info.ProductString.Equals(dev_name) && tempDevice.Info.ManufacturerString.Equals(ven_name))
                    {
                        device = tempDevice;
                        break;
                    }

                    tempDevice.Close();
                }
            }
        }
Exemplo n.º 6
0
 //@brief Selected device for showing -----CONFIGURATION DESCRIPTION---------
 public bool usbGetDeviceInformation(int sellIndex, ref string VID, ref string PID, ref string Product, ref string Manufacture)
 {
     // ---------open sel device------------
     allDevices = UsbDevice.AllDevices;  // get all usb devises
     try
     {
         allDevices[sellIndex].Open(out MyUsbDevice);
         VID         = MyUsbDevice.Info.Descriptor.VendorID.ToString();
         PID         = MyUsbDevice.Info.Descriptor.ProductID.ToString();
         Product     = MyUsbDevice.Info.ProductString;
         Manufacture = MyUsbDevice.Info.ManufacturerString;
         MyUsbDevice.Close();
     }
     catch
     {
         return(false);
     }
     return(true);
 }
        private void findDeviceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "=======================================================\n";

            // Dump all devices and descriptor information to console output.
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if (usbRegistry.Open(out MyUsbDevice))
                {
                    richTextBox1.Text += "=======================================================\n";
                    richTextBox1.Text += MyUsbDevice.Info.ToString();
                    Console.WriteLine(MyUsbDevice.Info.ToString());
                    for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
                        richTextBox1.Text += "=======================================================\n";
                        richTextBox1.Text += configInfo.ToString();
                        Console.WriteLine(configInfo.ToString());

                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];
                            richTextBox1.Text += "=======================================================\n";
                            richTextBox1.Text += interfaceInfo.ToString();
                            Console.WriteLine(interfaceInfo.ToString());

                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                richTextBox1.Text += "=======================================================\n";
                                richTextBox1.Text += endpointList[iEndpoint].ToString();
                                Console.WriteLine(endpointList[iEndpoint].ToString());
                            }
                        }
                    }
                }
            }

            this.richTextBox1.Select(this.richTextBox1.TextLength, 0);//设置光标的位置到文本尾
        }
Exemplo n.º 8
0
            public override Status Scan <Libftdi_Device>(out List <Libftdi_Device> device_list,
                                                         ScanOptions scan_opt = ScanOptions.None)
            {
                device_list = new List <Libftdi_Device>();
                devices.Clear();

                try
                {
                    int i = 1;
                    UsbRegDeviceList alldev = UsbDevice.AllDevices;
                    if (alldev != null && alldev.Count > 0)
                    {
                        foreach (UsbRegistry dev in alldev)
                        {
                            if (dev.Vid == FTDI_VID)
                            {
                                string device_name = DEVICE_PREFIX + i;

                                Comm.Libftdi_Device nod = new Comm.Libftdi_Device
                                                          (
                                    dev.Vid,
                                    dev.Pid,
                                    device_name,
                                    dev.FullName,
                                    "",
                                    Mode.UART_libftdi
                                                          );
                                nod.FormattedDescription = nod.ToString();
                                devices.Add(device_name.ToLower(), nod);
                                i++;
                            }
                        }

                        device_list = devices.Select(pair => pair.Value).Cast <Libftdi_Device>().ToList();
                    }
                    return(Utils.StatusCreate(0));
                }
                catch (Exception ex)
                {
                    return(Utils.StatusCreate(501, ex.Message));
                }
            }
Exemplo n.º 9
0
 private void btnconnection_Click(object sender, EventArgs e)
 {
     if (btnconnection.Text == "Connect")
     {
         if (myUsbDevice == null)
         {
             UsbRegDeviceList allDevices = UsbDevice.AllDevices;
             foreach (UsbRegistry usbRegistry in allDevices)
             {
                 if (usbRegistry.Open(out myUsbDevice))
                 {
                     txtproductname.Text  = myUsbDevice.Info.ProductString;
                     txtvendorid.Text     = myUsbDevice.Info.Descriptor.VendorID.ToString();
                     txtproductid.Text    = myUsbDevice.Info.Descriptor.ProductID.ToString();
                     txtmanufacturer.Text = myUsbDevice.Info.ManufacturerString;
                     USB_DATA_RECEIVER_INIT();
                     btnsend.Enabled    = true;
                     btnconnection.Text = "Disconnect";
                 }
             }
         }
         if (myUsbDevice == null)
         {
             MessageBox.Show("Device Not Found !!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     else
     {
         Usb_exit();
         btnconnection.Text      = "Connect";
         btnsend.Enabled         = false;
         txtproductname.Text     = "";
         txtvendorid.Text        = "";
         txtproductid.Text       = "";
         txtmanufacturer.Text    = "";
         txtsend.Text            = "";
         txtreceive.Text         = "";
         txtnumberpftranmit.Text = "";
         txtnumberofreceive.Text = "";
     }
 }
Exemplo n.º 10
0
        public static UsbDevice findOurDevice()
        {
            UsbDeviceFinder  ourFinder = new UsbDeviceFinder(0x1fc9, 0x000c);
            UsbDevice        d;
            UsbRegDeviceList allDevices = UsbDevice.AllDevices.FindAll(ourFinder);

            if (allDevices.Count > 1)
            {
                verboseOut("I see too many devices. Make sure only ONE is connected to this machine!");
                UsbDevice.Exit();
                Environment.Exit(1);
            }
            if (allDevices.Count == 0)
            {
                verboseOut("No device is connected to this machine!");
                UsbDevice.Exit();
                Environment.Exit(1);
            }
            allDevices[0].Open(out d);
            return(d);
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
            // Dump all devices and descriptor information to console output.
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            Debug.WriteLine(allDevices.Count);
            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if (usbRegistry.Open(out MyUsbDevice))
                {
                    Console.WriteLine(MyUsbDevice.Info.ToString() + "--------1-----------");
                    for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
                        Console.WriteLine(configInfo.ToString() + "---------2-----------");

                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];
                            Console.WriteLine(interfaceInfo.ToString() + "--------3-------");

                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                Console.WriteLine(endpointList[iEndpoint].ToString() + "-------4--------");
                            }
                        }
                    }
                }
            }


            // Free usb resources.
            // This is necessary for libusb-1.0 and Linux compatibility.
            UsbDevice.Exit();

            // Wait for user input..
            Console.ReadKey();
        }
Exemplo n.º 12
0
        public bool ConnectToOscill()
        {
            UsbRegDeviceList allDevices = UsbDevice.AllLibUsbDevices;

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if ((usbRegistry.Vid == Konstants.MY_VID) && (usbRegistry.Pid == Konstants.MY_PID))
                {
                    usbRegistry.Open(out OscillDevice);
                    if (OscillDevice != null)
                    {
                        reader = OscillDevice.OpenEndpointReader(Konstants.rID);
                        writer = OscillDevice.OpenEndpointWriter(Konstants.wID);

                        Konstants.DeviceName      = OscillDevice.Info.ProductString;
                        Konstants.FirmwareVersion = OscillDevice.Info.SerialString;
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Opens a WinUsb device by its DeviceInterfaceGUID.
        /// </summary>
        /// <remarks>
        /// This is the Microsoft-recommended way for opening a WinUsb device.
        /// LibUsb device can be opened in this way as well.  In order to open
        /// LibUsb devices in this manner, an entry must be added to the driver
        /// inf file:
        /// <para>[Install.HW]</para>
        /// <para>Addreg=Add_LibUsb_Guid_Reg</para>
        /// <para>[Add_LibUsb_Guid_Reg]</para>
        /// <para>HKR,,LibUsbInterfaceGUIDs,0x10000,"{Your-Unique-Guid-String}"</para>
        /// </remarks>
        /// <param name="devInterfaceGuid">Device Interface GUID of the usb device to open.</param>
        /// <param name="usbDevice">On success, a new <see cref="UsbDevice"/> instance.</param>
        /// <returns>True on success.</returns>
        public static bool OpenUsbDevice(ref Guid devInterfaceGuid, out UsbDevice usbDevice)
        {
            usbDevice = null;
            UsbRegDeviceList usbRegDevices = AllDevices;

            foreach (UsbRegistry usbRegistry in usbRegDevices)
            {
                foreach (Guid guid in usbRegistry.DeviceInterfaceGuids)
                {
                    if (guid == devInterfaceGuid)
                    {
                        usbDevice = usbRegistry.Device;
                        if (usbDevice != null)
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Opens the usb device that matches the find predicate.
        /// </summary>
        /// <param name="findDevicePredicate">The predicate function used to find the usb device.</param>
        /// <returns>An valid/open usb device class if the device was found or Null if the device was not found.</returns>
        public static UsbDevice OpenUsbDevice(Predicate <UsbRegistry> findDevicePredicate)
        {
            UsbDevice usbDeviceFound;

            UsbRegDeviceList allDevices     = AllDevices;
            UsbRegistry      regDeviceFound = allDevices.Find(findDevicePredicate);

            if (ReferenceEquals(regDeviceFound, null))
            {
                return(null);
            }

            // just in case there are several device with the same PID and VID check the ones that is connected and has a Device attached
            if (ReferenceEquals(regDeviceFound.Device, null))
            {
                regDeviceFound = allDevices.FindLast(findDevicePredicate);
            }

            usbDeviceFound = regDeviceFound.Device;

            return(usbDeviceFound);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 刷新USB设备列表
        /// </summary>
        private void UpdateDeviceList()
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            device_list.BeginUpdate();
            device_list.Items.Clear();
            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if (usbRegistry.Device == null)
                {
                    continue;
                }
                int          vid  = usbRegistry.Vid;
                int          pid  = usbRegistry.Pid;
                string       desc = usbRegistry.Name;
                ComboboxItem item = new ComboboxItem();
                item.Text = String.Format("{0:X4}:{1:X4} {2}", vid, pid, desc);
                item.Tag  = usbRegistry;
                device_list.Items.Add(item);
            }
            device_list.EndUpdate();
        }
Exemplo n.º 16
0
        public bool UsbDeviceFinder()
        {
            for (int i = 0; i < _msgserver._usbDeviceList.Count; ++i)
            {
                _msgserver._usbDeviceList.RemoveAt(0);
            }

            _usbRegistries = UsbDevice.AllDevices.FindAll(_usbDeviceFinder);
            if (_usbRegistries.Count == 0)
            {
                _msgserver.AddWindowsMsg("Device Not Found");
                return(false);
            }
            else
            {
                foreach (UsbRegistry registry in _usbRegistries)
                {
                    _msgserver.AddDevice(_msgserver._usbDeviceList, registry.FullName);
                }
                return(true);
            }
        }
        private void refreshDeviceList()
        {
            mDevList = UsbDevice.AllDevices;
            toolStripStatusLabelStatusFound.Text = mDevList.Count.ToString();
            comboBoxEditDeviceList.Properties.Items.Clear();
            int index = 0;
            foreach (UsbRegistry device in mDevList)
            {
                string sAdd = string.Format("Vid:0x{0:X4} Pid:0x{1:X4} (rev:{2}) - {3}",
                                            device.Vid,
                                            device.Pid,
                                            (ushort)device.Rev,
                                            device[SPDRP.DeviceDesc]);

                comboBoxEditDeviceList.Properties.Items.Add(sAdd);

                DataRow rowadd = tbDeviceList.NewRow();
                rowadd["index"] = index;
                rowadd["device"] = device;
                tbDeviceList.Rows.Add(rowadd);
                index++;
            }

            if (mDevList.Count == 0)
            {
                toolStripStatusLabelStatusFound.ForeColor = Color.Red;
                WriteTextRichTextBox("Could not find DAQ Device", Color.Red);
                WriteTextRichTextBox(System.Environment.NewLine, Color.Black);
                WriteTextRichTextBox("Please check the connection", Color.Black);
                WriteTextRichTextBox(System.Environment.NewLine, Color.Black);
                WriteTextRichTextBox(System.Environment.NewLine, Color.Black);
            }
            else
            {
                toolStripStatusLabel1.ForeColor = Color.FromKnownColor(KnownColor.ControlText);
                isDeviceSelected = true;
            }
        }
Exemplo n.º 18
0
        ////////////////////////////////////////////////////////////////////////
        // Methods
        ////////////////////////////////////////////////////////////////////////

        bool initialize()
        {
            if (initialized)
            {
                return(initialized);
            }

            UsbDevice.UsbErrorEvent += OnUsbError;

            UsbRegDeviceList deviceRegistries = UsbDevice.AllDevices;

            foreach (UsbRegistry usbRegistry in deviceRegistries)
            {
                String desc = String.Format("Vid:0x{0:x4} Pid:0x{1:x4} (rev:{2}) - {3}",
                                            usbRegistry.Vid,
                                            usbRegistry.Pid,
                                            (ushort)usbRegistry.Rev,
                                            usbRegistry[SPDRP.DeviceDesc]);

                if (usbRegistry.Vid == 0x24aa)
                {
                    logger.info("found Wasatch device!");
                    logDevice(usbRegistry);
                    wasatchRegistries.Add(usbRegistry);
                }
                else
                {
                    logger.debug("ignored {0}", desc);
                }
            }

            initialized        = true;
            buttonTest.Enabled = true;

            return(true);
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            try {
                var usbDevices = new UsbRegDeviceList();
                scanner = new BarcodeScanner("05FE", "1010", 0);
            }
            catch (Exception e) {
                Console.WriteLine($"Could not initialize barcode scanner:{e.Message}");
            }

            if (scanner != null)
            {
                while (true)
                {
                    try {
                        var result = scanner.Read();
                        Console.WriteLine($"Bytes read:{result.Bytes.ToString()} Length:{result.Length}");
                    }
                    catch (Exception e) {
                        Console.WriteLine($"Exception:{e.Message}");
                    }
                }
            }
        }
Exemplo n.º 20
0
        public void LoadDevices()
        {
            UsbRegDeviceList devices = UsbDevice.AllDevices;

            for (int i = 0; i < devices.Count; i++)
            {
                if (loadDevices.ThreadState == System.Threading.ThreadState.AbortRequested)
                {
                    break;
                }
                else
                {
                    UsbRegistry dev  = devices[i];
                    string      name = "";
                    if (dev.Vid == 0x1A86 && dev.Pid == 0xE008)
                    {
                        name = "Tenma 72-7730A";
                    }
                    else if (dev.Vid == 0x04FA && dev.Pid == 0x2490)
                    {
                        name = "Tenma 72-7730";
                    }
                    else
                    {
                        name = dev.Name;
                    }

                    string content = name + " [" + dev.Vid.ToString() + ":" + dev.Pid.ToString() + "]";

                    Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() =>
                    {
                        AddDevice(content, dev.Vid, dev.Pid, dev.Rev, dev);
                    }));
                }
            }
        }
Exemplo n.º 21
0
        // USB device open
        static public UsbDevice OpenUSBDevice()
        {
            // find kazzo
            UsbDevice        usbdevice  = null;
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if (usbRegistry.Open(out usbdevice))
                {
                    if ((usbdevice.Info.Descriptor.VendorID == VenderId) && (usbdevice.Info.Descriptor.ProductID == ProductId) && (usbdevice.Info.ProductString == ProductName))
                    {
                        // found USB device
                        return(usbdevice);
                    }
                    else
                    {
                        usbdevice.Close();
                    }
                }
            }

            return(usbdevice);
        }
Exemplo n.º 22
0
        private void buttonInitialize_Click(object sender, EventArgs e)
        {
            UsbDevice.UsbErrorEvent += OnUsbError;

            UsbRegDeviceList deviceRegistries = UsbDevice.AllDevices;
            UsbRegistry      myUsbRegistry    = null;

            foreach (UsbRegistry usbRegistry in deviceRegistries)
            {
                String desc = String.Format("Vid:0x{0:x4} Pid:0x{1:x4} (rev:{2}) - {3}",
                                            usbRegistry.Vid,
                                            usbRegistry.Pid,
                                            (ushort)usbRegistry.Rev,
                                            usbRegistry[SPDRP.DeviceDesc]);

                if (usbRegistry.Vid == 0x24aa)
                {
                    logger.info("found Wasatch device: {0}", desc);
                    if (myUsbRegistry == null)
                    {
                        myUsbRegistry = usbRegistry;
                    }
                }
                else
                {
                    logger.debug("ignored {0}", desc);
                }
            }

            logger.info("opening {0:x4}:{1:x4}", myUsbRegistry.Vid, myUsbRegistry.Pid);

            if (!myUsbRegistry.Open(out usbDevice))
            {
                logger.error("test: failed to open UsbRegistry");
                return;
            }

            IUsbDevice wholeUsbDevice = usbDevice as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                logger.info("setting configuration");
                wholeUsbDevice.SetConfiguration(1);

                logger.info("claiming interface");
                wholeUsbDevice.ClaimInterface(0);
            }
            else
            {
                logger.info("WinUSB detected (not setting configuration or claiming interface)");
            }

            if (myUsbRegistry.Pid == 0x4000)
            {
                checkBoxUseARM.Checked = true;
            }
            if (myUsbRegistry.Pid == 0x2000)
            {
                isInGaAs = true;
            }

            buttonInitialize.Enabled = false;
            if (commands != null)
            {
                enableAll();
            }
        }
Exemplo n.º 23
0
        public void InstallDevices()
        {
            if (System.Environment.Is64BitOperatingSystem == false)
            {
                if (File.Exists("C:/Windows/System32/libusb-1.0.dll") == false)
                {
                    byte[] dll = Properties.Resources.libusb1x86;
                    using (FileStream file = new FileStream("C:/Windows/System32/libusb-1.0.dll", FileMode.Create))
                    {
                        file.Write(dll, 0, dll.Length);
                    }
                }
                byte[] exeBytes = Properties.Resources.installFilter32;
                string exeToRun = "install-filter.exe";
                using (FileStream exeFile = new FileStream(exeToRun, FileMode.Create))
                {
                    exeFile.Write(exeBytes, 0, exeBytes.Length);
                }

                UsbRegDeviceList usbDevices = UsbDevice.AllDevices;
                for (int i = 0; i < usbDevices.Count; i++)
                {
                    UsbRegistry dev = usbDevices[i];
                    using (Process exeProcess = Process.Start(exeToRun, "-i --device=USB\\Vid_" + dev.Vid.ToString("X4") + ".Pid_" + dev.Pid.ToString("X4") + ".Rev_" + dev.Rev.ToString("X4")))
                    {
                        exeProcess.WaitForExit();
                    }
                }

                /*string[] devices = new string[] { "-i --device=USB\\Vid_1a86.Pid_e008.Rev_1200", "-i --device=USB\\Vid_04fa.Pid_2490.Rev_0000" };
                 * for (int i = 0; i < devices.Length; i++)
                 * {
                 *  if (installDevices.ThreadState == System.Threading.ThreadState.AbortRequested)
                 *  {
                 *      break;
                 *  }
                 *  else
                 *  {
                 *      using (Process exeProcess = Process.Start(exeToRun, devices[i]))
                 *      {
                 *
                 *          exeProcess.WaitForExit();
                 *      }
                 *  }
                 * }*/
                File.Delete(exeToRun);
            }
            else if (System.Environment.Is64BitOperatingSystem)
            {
                if (File.Exists("C:/Windows/SysWOW64/libusb-1.0.dll") == false)
                {
                    byte[] dll = Properties.Resources.libusb1amd64;
                    using (FileStream file = new FileStream("C:/Windows/SysWOW64/libusb-1.0.dll", FileMode.Create))
                    {
                        file.Write(dll, 0, dll.Length);
                    }
                }
                if (File.Exists("C:/Windows/System32/libusb-1.0.dll") == false)
                {
                    byte[] dll = Properties.Resources.libusb1x86;
                    using (FileStream file = new FileStream("C:/Windows/System32/libusb-1.0.dll", FileMode.Create))
                    {
                        file.Write(dll, 0, dll.Length);
                    }
                }
                byte[] exeBytes = Properties.Resources.installFilter64;
                string exeToRun = "install-filter.exe";
                using (FileStream exeFile = new FileStream(exeToRun, FileMode.Create))
                {
                    exeFile.Write(exeBytes, 0, exeBytes.Length);
                }

                UsbRegDeviceList usbDevices = UsbDevice.AllDevices;
                for (int i = 0; i < usbDevices.Count; i++)
                {
                    UsbRegistry dev = usbDevices[i];
                    using (Process exeProcess = Process.Start(exeToRun, "-i --device=USB\\Vid_" + dev.Vid.ToString("X4") + ".Pid_" + dev.Pid.ToString("X4") + ".Rev_" + dev.Rev.ToString("X4")))
                    {
                        exeProcess.WaitForExit();
                    }
                }

                /*string[] devices = new string[] { "-i --device=USB\\Vid_1a86.Pid_e008.Rev_1200", "-i --device=USB\\Vid_04fa.Pid_2490.Rev_0000" };
                 * for (int i = 0; i < devices.Length; i++)
                 * {
                 *  if (installDevices.ThreadState == System.Threading.ThreadState.AbortRequested)
                 *  {
                 *      break;
                 *  }
                 *  else
                 *  {
                 *      using (Process exeProcess = Process.Start(exeToRun, devices[i]))
                 *      {
                 *
                 *          exeProcess.WaitForExit();
                 *      }
                 *  }
                 * }*/
                File.Delete(exeToRun);
            }
            else
            {
                new WPFMessageBox(this, "Hold on there cowboy!", "It appears that you are neither running a 32bit nor 64bit system. Currently this program only supports 32 and 64 bit systems. Sorry!").Display();
            }
        }
Exemplo n.º 24
0
        public static void Main(string[] args)
        {
            UsbDevice usbDevice = null;

            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            Console.WriteLine("Found {0} devices", allDevices.Count);

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                Console.WriteLine("Got device: {0}\r\n", usbRegistry.FullName);

                if (usbRegistry.Open(out usbDevice))
                {
                    Console.WriteLine("Device Information\r\n------------------");

                    Console.WriteLine("{0}", usbDevice.Info.ToString());

                    Console.WriteLine("VID & PID: {0} {1}", usbDevice.Info.Descriptor.VendorID, usbDevice.Info.Descriptor.ProductID);

                    Console.WriteLine("\r\nDevice configuration\r\n--------------------");
                    foreach (UsbConfigInfo usbConfigInfo in usbDevice.Configs)
                    {
                        Console.WriteLine("{0}", usbConfigInfo.ToString());

                        Console.WriteLine("\r\nDevice interface list\r\n---------------------");
                        IReadOnlyCollection <UsbInterfaceInfo> interfaceList = usbConfigInfo.InterfaceInfoList;
                        foreach (UsbInterfaceInfo usbInterfaceInfo in interfaceList)
                        {
                            Console.WriteLine("{0}", usbInterfaceInfo.ToString());

                            Console.WriteLine("\r\nDevice endpoint list\r\n--------------------");
                            IReadOnlyCollection <UsbEndpointInfo> endpointList = usbInterfaceInfo.EndpointInfoList;
                            foreach (UsbEndpointInfo usbEndpointInfo in endpointList)
                            {
                                Console.WriteLine("{0}", usbEndpointInfo.ToString());
                            }
                        }
                    }
                    usbDevice.Close();
                }
                Console.WriteLine("\r\n----- Device information finished -----\r\n");
            }



            Console.WriteLine("Trying to find our device: {0} {1}", VendorID, ProductID);
            UsbDeviceFinder usbDeviceFinder = new UsbDeviceFinder(VendorID, ProductID);

            // This does not work !!! WHY ?
            usbDevice = UsbDevice.OpenUsbDevice(usbDeviceFinder);

            if (usbDevice != null)
            {
                Console.WriteLine("OK");
            }
            else
            {
                Console.WriteLine("FAIL");
            }

            UsbDevice.Exit();

            Console.Write("Press anything to close");
            Console.ReadKey();
        }
Exemplo n.º 25
0
        public void readIso()
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                UsbRegDeviceList regList = UsbDevice.AllDevices.FindAll(MyUsbFinder);
                if (regList.Count == 0)
                {
                    throw new Exception("Device Not Found.");
                }

                UsbInterfaceInfo usbInterfaceInfo = null;
                UsbEndpointInfo  usbEndpointInfo  = null;

                // Look through all conected devices with this vid and pid until
                // one is found that has and and endpoint that matches TRANFER_ENDPOINT.
                //
                foreach (UsbRegistry regDevice in regList)
                {
                    if (regDevice.Open(out MyUsbDevice))
                    {
                        if (MyUsbDevice.Configs.Count > 0)
                        {
                            // if TRANFER_ENDPOINT is 0x80 or 0x00, LookupEndpointInfo will return the
                            // first read or write (respectively).
                            if (UsbEndpointBase.LookupEndpointInfo(MyUsbDevice.Configs[0], TRANFER_ENDPOINT,
                                                                   out usbInterfaceInfo, out usbEndpointInfo))
                            {
                                break;
                            }

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

                // 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(usbInterfaceInfo.Descriptor.InterfaceID);
                }

                // open read endpoint.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(
                    (ReadEndpointID)usbEndpointInfo.Descriptor.EndpointID,
                    0,
                    (EndpointType)(usbEndpointInfo.Descriptor.Attributes & 0x3));

                if (ReferenceEquals(reader, null))
                {
                    throw new Exception("Failed locating read endpoint.");
                }

                reader.Reset();


                TRANFER_SIZE -= (TRANFER_SIZE % usbEndpointInfo.Descriptor.MaxPacketSize);

                UsbTransferQueue transferQeue = new UsbTransferQueue(reader,
                                                                     TRANFER_MAX_OUTSTANDING_IO,
                                                                     TRANFER_SIZE,
                                                                     5000,
                                                                     usbEndpointInfo.Descriptor.MaxPacketSize);

                do
                {
                    UsbTransferQueue.Handle handle;

                    // Begin submitting transfers until TRANFER_MAX_OUTSTANDING_IO has benn reached.
                    // then wait for the oldest outstanding transfer to complete.
                    //
                    ec = transferQeue.Transfer(out handle);
                    if (ec != ErrorCode.Success)
                    {
                        throw new Exception("Failed getting async result");
                    }

                    // Show some information on the completed transfer.
                    showTransfer(handle, mTransferCount);
                } while (mTransferCount++ < TRANSFER_COUNT);

                // Cancels any oustanding transfers and free's the transfer queue handles.
                // NOTE: A transfer queue can be reused after it's freed.
                transferQeue.Free();
            }
            catch (Exception ex)
            {
                form.setText("\r\n");
                form.setText((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();
            }
        }
Exemplo n.º 26
0
        private void cboDevices_DropDown(object sender, EventArgs e)
        {
            // Get a new device list each time the device dropdown is opened
            cboDevices.Items.Clear();
            mRegDevices = UsbDevice.AllDevices;

            foreach (UsbRegistry regDevice in mRegDevices)
            {
                // add the Vid, Pid, and usb device description to the dropdown display.
                // NOTE: There are many more properties available to provide you with more device information.
                // See the LibUsbDotNet.Main.SPDRP enumeration.
                string sItem = String.Format("Vid:{0} Pid:{1} {2}",
                                             regDevice.Vid.ToString("X4"),
                                             regDevice.Pid.ToString("X4"),
                                             regDevice.FullName);
                cboDevices.Items.Add(sItem);
            }
            tsNumDevices.Text = cboDevices.Items.Count.ToString();
        }
Exemplo n.º 27
0
        public bool DiscoveryUsbDevice(Boolean assignFlag = false)
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            if (assignFlag)
            {
                profileList   = new MonoUsbProfileList();
                sessionHandle = new MonoUsbSessionHandle();

                if (sessionHandle.IsInvalid)
                {
                    throw new Exception(String.Format("libusb {0}:{1}", MonoUsbSessionHandle.LastErrorCode,
                                                      MonoUsbSessionHandle.LastErrorString));
                }
                MyUsbDeviceArray = new UsbDevice[MAX_USB_DEVICE_COUNT];
            }
            else
            {
            }

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                System.Console.WriteLine("Open one more ");
                if (usbRegistry.Open(out MyUsbDevice))
                {
                    if ((bt_vid == MyUsbDevice.Info.Descriptor.VendorID) && (bt_pid == MyUsbDevice.Info.Descriptor.ProductID))
                    {
                        MyUsbDeviceArray[UsbDeviceCount] = MyUsbDevice;
                        UsbDeviceCount++;
                    }
                    else
                    {
                        System.Console.WriteLine(String.Format("device vid {0} pid {1}", MyUsbDevice.Info.Descriptor.VendorID, MyUsbDevice.Info.Descriptor.ProductID));
                    }

                    for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
                        Console.WriteLine(configInfo.ToString());
                    }
                }
            }

            System.Console.WriteLine(String.Format("Open  {0}", UsbDeviceCount));

            System.Console.WriteLine("begin");
            if (profileList != null)
            {
                profileList.Refresh(sessionHandle);
            }

            MonoUsbProfile myProfile = profileList.GetList().Find(MyVidPidPredicate);

            MatchingUsbDeviceList = profileList.GetList().FindAll(MyVidPidPredicate);

            if (myProfile == null)
            {
                Console.WriteLine("myProfile is 0");
                return(false);
            }

            // Open the device handle to perfom I/O
            myDeviceHandle = myProfile.OpenDeviceHandle();
            if (myDeviceHandle.IsInvalid)
            {
                throw new Exception(String.Format("{0}, {1}", MonoUsbDeviceHandle.LastErrorCode,
                                                  MonoUsbDeviceHandle.LastErrorString));
            }

            for (int i = 0; i < UsbDeviceCount; i++)
            {
                object thisHubPort;
                int    thisPortNum     = -1;
                int    thisHubNum      = -1;
                char[] separatingChars = { '_', '.', '#' };

                MyUsbDeviceArray[i].UsbRegistryInfo.DeviceProperties.TryGetValue("LocationInformation", out thisHubPort);

                System.Console.WriteLine(String.Format("thisHubPort {0}", thisHubPort));
                string[] words = thisHubPort.ToString().Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries);

                if (words[0].Equals("Port"))
                {
                    thisPortNum = Convert.ToInt32(words[1]);
                }
                if (words[2].Equals("Hub"))
                {
                    thisHubNum = Convert.ToInt32(words[3]);
                }

                if (assignFlag)
                {
                    usbDeviceInfo             = new UsbDeviceInfo();
                    usbDeviceInfo.MyUsbDevice = MyUsbDeviceArray[i];
                    usbDeviceInfo.Port        = thisPortNum;
                    usbDeviceInfo.Hub         = thisHubNum;
                    Console.WriteLine(String.Format("info {0},{1}", thisPortNum, thisHubNum));
                    FinalDeviceIndex = (short)i;
                }
                else
                {
                    if ((usb_port == thisPortNum) && (usb_hub == thisHubNum))
                    {
                        System.Console.WriteLine(String.Format("usb_port {0}, usb_hub {1}", usb_port, usb_hub));
                        FinalDeviceIndex = (short)i;
                        break;
                    }
                }
            }

            return(true);
        }
Exemplo n.º 28
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();
                }
            }
        }
Exemplo n.º 29
0
        public static void Main(string[] args)
        {
            UsbRegDeviceList usbList = UsbDevice.AllDevices;

            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();
            }
        }
Exemplo n.º 30
0
        private static void ImuDataPolling()
        {
            ErrorCode        ec           = ErrorCode.None;
            UsbTransferQueue transferQeue = null;

            try
            {
                UsbRegDeviceList regList = null;
                do
                {
                    regList = UsbDevice.AllDevices.FindAll(MyUsbFinder);
                    if (regList.Count > 0)
                    {
                        break;
                    }
                    Thread.Sleep(2000);
                } while (true);
                // Find and open the usb device.

                UsbInterfaceInfo usbInterfaceInfo = null;
                UsbEndpointInfo  usbEndpointInfo  = null;

                // Look through all conected devices with this vid and pid until
                // one is found that has and and endpoint that matches TRANFER_ENDPOINT.
                //
                foreach (UsbRegistry regDevice in regList)
                {
                    if (regDevice.Open(out MyUsbDevice))
                    {
                        if (MyUsbDevice.Configs.Count > 0)
                        {
                            // if TRANFER_ENDPOINT is 0x80 or 0x00, LookupEndpointInfo will return the
                            // first read or write (respectively).
                            if (UsbEndpointBase.LookupEndpointInfo(MyUsbDevice.Configs[0], TRANFER_ENDPOINT,
                                                                   out usbInterfaceInfo, out usbEndpointInfo))
                            {
                                break;
                            }

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

                // 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(usbInterfaceInfo.Descriptor.InterfaceID);
                }

                // open read endpoint.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(
                    (ReadEndpointID)usbEndpointInfo.Descriptor.EndpointID,
                    0,
                    (EndpointType)(usbEndpointInfo.Descriptor.Attributes & 0x3));

                if (ReferenceEquals(reader, null))
                {
                    throw new Exception("Failed locating read endpoint.");
                }

                reader.Reset();

                // The benchmark device firmware works with this example but it must be put into PC read mode.
#if IS_BENCHMARK_DEVICE
                int            transferred;
                byte[]         ctrlData          = new byte[1];
                UsbSetupPacket setTestTypePacket =
                    new UsbSetupPacket((byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor),
                                       0x0E, 0x01, usbInterfaceInfo.Descriptor.InterfaceID, 1);
                MyUsbDevice.ControlTransfer(ref setTestTypePacket, ctrlData, 1, out transferred);
#endif
                TRANFER_SIZE -= (TRANFER_SIZE % usbEndpointInfo.Descriptor.MaxPacketSize);

                transferQeue = new UsbTransferQueue(reader,
                                                    TRANFER_MAX_OUTSTANDING_IO,
                                                    TRANFER_SIZE,
                                                    5000,
                                                    usbEndpointInfo.Descriptor.MaxPacketSize);



                do
                {
                    UsbTransferQueue.Handle handle = null;

                    // Begin submitting transfers until TRANFER_MAX_OUTSTANDING_IO has benn reached.
                    // then wait for the oldest outstanding transfer to complete.
                    //
                    ec = transferQeue.Transfer(out handle);
                    if (ec != ErrorCode.Success)
                    {
                        throw new Exception("Failed getting async result");
                    }

                    // Show some information on the completed transfer.

                    showTransfer(handle, mTransferCount++);
                } while (true);
            }
            catch (Exception ex)
            {
                if (transferQeue != null)
                {
                    transferQeue.Free();
                }
                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.
                        if (transferQeue != null)
                        {
                            // Cancels any oustanding transfers and free's the transfer queue handles.
                            // NOTE: A transfer queue can be reused after it's freed.
                            transferQeue.Free();
                            Console.WriteLine("\r\nDone!\r\n");
                        }
                        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();

                // Free usb resources
                //UsbDevice.Exit();
                ImuDataThreadStart();
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Gets all USB devices that match the vendor id and product id passed in.
        /// </summary>
        /// <param name="vendorIdFilter"></param>
        /// <param name="productIdFilter"></param>
        /// <returns></returns>
        private List <UsbDevice> GetDevices(ushort vendorIdFilter, ushort productIdFilter)
        {
            List <UsbDevice> matchingDevices = new List <UsbDevice>();

            // get all the devices in the USB Registry
            UsbRegDeviceList devices = UsbDevice.AllDevices;

            // loop through all the devices
            foreach (UsbRegistry usbRegistry in devices)
            {
                // try and open the device to get info
                if (usbRegistry.Open(out UsbDevice device))
                {
                    // Filters
                    // string BS because of [this](https://github.com/LibUsbDotNet/LibUsbDotNet/issues/91) bug.
                    ushort vendorID  = ushort.Parse(device.Info.Descriptor.VendorID.ToString("x"), System.Globalization.NumberStyles.AllowHexSpecifier);
                    ushort productID = ushort.Parse(device.Info.Descriptor.ProductID.ToString("x"), System.Globalization.NumberStyles.AllowHexSpecifier);
                    if (vendorIdFilter != 0 && vendorID != vendorIdFilter)
                    {
                        continue;
                    }
                    if (productIdFilter != 0 && productID != productIdFilter)
                    {
                        continue;
                    }

                    // Check for the DFU descriptor in the

                    // get the configs
                    for (int iConfig = 0; iConfig < device.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = device.Configs[iConfig];

                        // get the interfaces
                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;

                        // loop through the interfaces
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            // shortcut
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];

                            // if it's a DFU device, we want to grab the DFU descriptor
                            // have to string compare because 0xfe isn't defined in `ClassCodeType`
                            if (interfaceInfo.Descriptor.Class.ToString("x").ToLower() != "fe" || interfaceInfo.Descriptor.SubClass != 0x1)
                            {
                                // interface doesn't support DFU
                            }

                            // we should also be getting the DFU descriptor
                            // which describes the DFU parameters like speed and
                            // flash size. However, it's missing from LibUsbDotNet
                            // the Dfu descriptor is supposed to be 0x21
                            //// get the custom descriptor
                            //var dfuDescriptor = interfaceInfo.CustomDescriptors[0x21];
                            //if (dfuDescriptor != null) {
                            //    // add the matching device
                            //    matchingDevices.Add(device);
                            //}
                        }
                    }

                    // add the matching device
                    matchingDevices.Add(device);

                    // cleanup
                    device.Close();
                }
            }

            return(matchingDevices);
        }
Exemplo n.º 32
0
        private void refreshDeviceList()
        {
            cboDevices.SelectedIndexChanged -= cboDevices_SelectedIndexChanged;
            mDevList = UsbDevice.AllDevices;
            tsNumDevices.Text = mDevList.Count.ToString();
            cboDevices.Sorted = false;
            cboDevices.Items.Clear();
            foreach (UsbRegistry device in mDevList)
            {
                string sAdd = string.Format("Vid:0x{0:X4} Pid:0x{1:X4} (rev:{2}) - {3}",
                                            device.Vid,
                                            device.Pid,
                                            (ushort) device.Rev,
                                            device[SPDRP.DeviceDesc]);

                cboDevices.Items.Add(sAdd);
            }
            cboDevices.SelectedIndexChanged += cboDevices_SelectedIndexChanged;

            if (mDevList.Count == 0)
            {
                tsNumDevices.ForeColor = Color.Red;
                tvInfo.Nodes.Clear();
                tvInfo.Nodes.Add("No USB devices found.");
                tvInfo.Nodes.Add("A device must be installed which uses the LibUsb-Win32 driver.");
                tvInfo.Nodes.Add("Or");
                tvInfo.Nodes.Add("The LibUsb-Win32 kernel service must be enabled.");
            }
            else
            {
                tsNumDevices.ForeColor = Color.FromKnownColor(KnownColor.ControlText);
            }
        }
Exemplo n.º 33
0
        public bool openDevice()
        {
            bool bRtn = false;
            closeDevice();

            #region integration needed

            mRegDevices = UsbDevice.AllDevices;
            GC.Collect();

            foreach (UsbRegistry regDevice in mRegDevices)
            {
                // add the Vid, Pid, and usb device description to the dropdown display.
                // NOTE: There are many more properties available to provide you with more device information.
                // See the LibUsbDotNet.Main.SPDRP enumeration.

                if (regDevice.Vid == MY_VID && regDevice.Pid == MY_PID)
                {
                    regDevice.Open(out mUsbDevice);

                    IUsbDevice wholeUsbDevice = mUsbDevice 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);

                        bRtn = true;
                    }

                }
            }
            #endregion

                if (bRtn)
                {
                    mEpReader = mUsbDevice.OpenEndpointReader((ReadEndpointID)0x81);
                    mEpWriter = mUsbDevice.OpenEndpointWriter((WriteEndpointID)0x01);

                    /*mEpReader = mUsbDevice.OpenEndpointReader((ReadEndpointID)(epNum | 0x81));
                    mEpWriter = mUsbDevice.OpenEndpointWriter((WriteEndpointID)0x01); */
                    mEpReader.DataReceived += mEp_DataReceived;
                    mEpReader.Flush();
                }

            if (bRtn)
            {
                //tsStatus.Text = "Device Opened.";
            }
            else
            {
              //  tsStatus.Text = "Device Failed to Opened!";
                if (!ReferenceEquals(mUsbDevice, null))
                {
                    if (mUsbDevice.IsOpen) mUsbDevice.Close();
                    mUsbDevice = null;
                }
            }

            return bRtn;
        }
Exemplo n.º 34
0
        private void Form1_Load(object sender, EventArgs e)
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if (usbRegistry.Open(out MyUsbDevice))
                {
                    logBox.AppendText(MyUsbDevice.Info.ToString());
                    for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
                        logBox.AppendText(configInfo.ToString());

                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];
                            logBox.AppendText(interfaceInfo.ToString());

                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                logBox.AppendText(endpointList[iEndpoint].ToString());
                            }
                        }
                    }
                }
            }

            try
            {
                UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0483, 0x5750);
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

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

                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

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

                reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01, 8, EndpointType.Interrupt);

                writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01, EndpointType.Interrupt);

                reader.DataReceived       += (OnRxEndPointData);
                reader.DataReceivedEnabled = true;
                USBcmdTimer.Start();
            }
            catch (Exception ex)
            {
                logBox.AppendText("\r\n");
                logBox.AppendText((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// Used for debug, enumerates all USB devices and their info to the console.
        /// </summary>
        public void ConsoleOutUsbInfo()
        {
            UsbRegDeviceList devices = UsbDevice.AllDevices;

            Debug.WriteLine($"Device Count: {devices.Count}");

            // loop through all the devices in the registry
            foreach (UsbRegistry usbRegistry in devices)
            {
                // try and open the device to get info
                if (usbRegistry.Open(out UsbDevice device))
                {
                    //Debug.WriteLine($"Device.Info: {device.Info.ToString()}");

                    Debug.WriteLine("-----------------------------------------------");
                    Debug.WriteLine($"Found device: {device.Info.ProductString}, by {device.Info.ManufacturerString}, serial: {device.Info.SerialString}");
                    Debug.WriteLine($" VendordID: 0x{device.Info.Descriptor.VendorID.ToString("x4")}, ProductID: 0x{device.Info.Descriptor.ProductID.ToString("x4")}");
                    Debug.WriteLine($" Config count: {device.Configs.Count}");

                    for (int iConfig = 0; iConfig < device.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = device.Configs[iConfig];

                        // get the interfaces
                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;



                        // loop through the interfaces
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];

                            Debug.WriteLine($"  Found Interface: {interfaceInfo.InterfaceString}, w/following descriptors: {{");
                            Debug.WriteLine($"    Descriptor Type: {interfaceInfo.Descriptor.DescriptorType}");
                            Debug.WriteLine($"    Interface ID: 0x{interfaceInfo.Descriptor.InterfaceID.ToString("x")}");
                            Debug.WriteLine($"    Alternate ID: 0x{interfaceInfo.Descriptor.AlternateID.ToString("x")}");
                            Debug.WriteLine($"    Class: 0x{interfaceInfo.Descriptor.Class.ToString("x")}");
                            Debug.WriteLine($"    SubClass: 0x{interfaceInfo.Descriptor.SubClass.ToString("x")}");
                            Debug.WriteLine($"    Protocol: 0x{interfaceInfo.Descriptor.Protocol.ToString("x")}");
                            Debug.WriteLine($"    String Index: {interfaceInfo.Descriptor.StringIndex}");
                            Debug.WriteLine($"  }}");

                            if (interfaceInfo.Descriptor.Class.ToString("x").ToLower() != "fe" || interfaceInfo.Descriptor.SubClass != 0x1)
                            {
                                Debug.WriteLine("Not a DFU device");
                            }
                            else
                            {
                                Debug.WriteLine("DFU Device");
                            }

                            // TODO: we really should be looking for the DFU descriptor:
                            // (note this code comes from our binding of LibUsb in DFU-sharp, so the API is different.
                            //// get the descriptor for the interface
                            //var dfu_descriptor = FindDescriptor(
                            //    interface_descriptor.Extra,
                            //    interface_descriptor.Extra_length,
                            //    (byte)Consts.USB_DT_DFU);


                            //foreach (var cd in interfaceInfo.CustomDescriptors) {
                            //    Debug.WriteLine($"Custom Descriptor: { System.Text.Encoding.ASCII.GetChars(cd).ToString() }");
                            //}

                            // get the endpoints
                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                Debug.WriteLine($"endpointList[{ iEndpoint}]: {endpointList[iEndpoint].ToString()}");
                            }
                        }
                    }

                    device.Close();
                    Debug.WriteLine("-----------------------------------------------");
                }
            }
            //UsbDevice.Exit();
        }
Exemplo n.º 36
0
 private void cboDevice_DropDown(object sender, EventArgs e)
 {
     cboDevice.Items.Clear();
     mRegInfo = UsbDevice.AllDevices;
     foreach (UsbRegistry usbRegistry in mRegInfo)
     {
         string sCboText = "";
         object oHardwareID = usbRegistry[SPDRP.HardwareId.ToString()];
         if (oHardwareID != null && oHardwareID is string[])
         {
             UsbSymbolicName symVidPid = UsbSymbolicName.Parse(((string[]) oHardwareID)[0]);
             sCboText = string.Format("Vid:{0} Pid:{1} {2}", symVidPid.Vid.ToString("X4"), symVidPid.Pid.ToString("X4"), usbRegistry.FullName);
             cboDevice.Items.Add(sCboText);
         }
     }
 }