예제 #1
0
        public void showInfo()
        {
            // Dump all devices and descriptor information to console output.
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

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

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

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

            // Free usb resources.
            // This is necessary for libusb-1.0 and Linux compatibility.
            UsbDevice.Exit();
        }
예제 #2
0
        private static void ConfigTest()
        {
            // Dump all devices and descriptor information to console output.
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

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

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

                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                Console.WriteLine(endpointList[iEndpoint].ToString());
                            }
                        }
                    }
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Attempts to get a USB configuration descriptor based on its index.
        /// </summary>
        /// <param name="configIndex">
        /// The index of the configuration you wish to retrieve
        /// </param>
        /// <param name="descriptor">
        /// The requested descriptor.
        /// </param>
        /// <returns>
        /// <see langword="true"/> if the descriptor could be loaded correctly; otherwise,
        /// <see langword="false" ">.
        /// </returns>
        public unsafe bool TryGetConfigDescriptor(byte configIndex, out UsbConfigInfo descriptor)
        {
            this.EnsureNotDisposed();

            ConfigDescriptor *list  = null;
            UsbConfigInfo     value = null;

            try
            {
                var ret = NativeMethods.GetConfigDescriptor(this.device, configIndex, &list);

                if (ret == Error.NotFound)
                {
                    descriptor = null;
                    return(false);
                }

                ret.ThrowOnError();

                value      = UsbConfigInfo.FromUsbConfigDescriptor(this, list[0]);
                descriptor = value;
                return(true);
            }
            finally
            {
                if (list != null)
                {
                    NativeMethods.FreeConfigDescriptor(list);
                }
            }
        }
        private void view_usb(object sender, RoutedEventArgs e)
        {
            // Dump all devices and descriptor information to console output.
            DebugInfo = "";
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

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

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

                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                DebugInfo += "endpointList iEndpoint[" + iEndpoint.ToString() + "]:\n";
                                DebugInfo += endpointList[iEndpoint].ToString();
                                DebugInfo += "\n\n\n";
                                //Console.WriteLine(endpointList[iEndpoint].ToString());
                            }
                        }
                    }
                }
            }
            // Free usb resources.
            // This is necessary for libusb-1.0 and Linux compatibility.
            UsbDevice.Exit();

            // Wait for user input..
            Console.Read();
        }
예제 #5
0
        /// <summary>
        /// Looks up endpoint/interface information in a configuration.
        /// </summary>
        /// <param name="currentConfigInfo">The config to seach.</param>
        /// <param name="altInterfaceID">Alternate interface id the endpoint exists in, or -1 for any alternate interface id.</param>
        /// <param name="endpointAddress">The endpoint address to look for.</param>
        /// <param name="usbInterfaceInfo">On success, the <see cref="UsbInterfaceInfo"/> class for this endpoint.</param>
        /// <param name="usbEndpointInfo">On success, the <see cref="UsbEndpointInfo"/> class for this endpoint.</param>
        /// <returns>True of the endpoint was found, otherwise false.</returns>
        public static bool LookupEndpointInfo(UsbConfigInfo currentConfigInfo, int altInterfaceID, byte endpointAddress, out UsbInterfaceInfo usbInterfaceInfo, out UsbEndpointInfo usbEndpointInfo)
        {
            bool found = false;

            usbInterfaceInfo = null;
            usbEndpointInfo  = null;
            foreach (UsbInterfaceInfo interfaceInfo in currentConfigInfo.Interfaces)
            {
                if (altInterfaceID == -1 || altInterfaceID == interfaceInfo.AlternateSetting)
                {
                    foreach (UsbEndpointInfo endpointInfo in interfaceInfo.Endpoints)
                    {
                        if ((endpointAddress & UsbConstants.EndpointNumberMask) == 0)
                        {
                            // find first read/write endpoint
                            if ((endpointAddress & UsbConstants.EndpointDirectionMask) == 0 &&
                                (endpointInfo.EndpointAddress & UsbConstants.EndpointDirectionMask) == 0)
                            {
                                // first write endpoint
                                found = true;
                            }

                            if ((endpointAddress & UsbConstants.EndpointDirectionMask) != 0 &&
                                (endpointInfo.EndpointAddress & UsbConstants.EndpointDirectionMask) != 0)
                            {
                                // first read endpoint
                                found = true;
                            }
                        }
                        else if (endpointInfo.EndpointAddress == endpointAddress)
                        {
                            found = true;
                        }

                        if (found)
                        {
                            usbInterfaceInfo = interfaceInfo;
                            usbEndpointInfo  = endpointInfo;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
예제 #6
0
        /// <summary>
        /// Looks up endpoint/interface information in a configuration.
        /// </summary>
        /// <param name="currentConfigInfo">The config to seach.</param>
        /// <param name="altInterfaceID">Alternate interface id the endpoint exists in, or -1 for any alternate interface id.</param>
        /// <param name="endpointAddress">The endpoint address to look for.</param>
        /// <param name="usbInterfaceInfo">On success, the <see cref="UsbInterfaceInfo"/> class for this endpoint.</param>
        /// <param name="usbEndpointInfo">On success, the <see cref="UsbEndpointInfo"/> class for this endpoint.</param>
        /// <returns>True of the endpoint was found, otherwise false.</returns>
        public static bool LookupEndpointInfo(UsbConfigInfo currentConfigInfo, int altInterfaceID, byte endpointAddress, out UsbInterfaceInfo usbInterfaceInfo, out UsbEndpointInfo usbEndpointInfo)
        {
            bool found = false;

            usbInterfaceInfo = null;
            usbEndpointInfo  = null;
            foreach (UsbInterfaceInfo interfaceInfo in currentConfigInfo.InterfaceInfoList)
            {
                if (altInterfaceID == -1 || altInterfaceID == interfaceInfo.Descriptor.AlternateID)
                {
                    foreach (UsbEndpointInfo endpointInfo in interfaceInfo.EndpointInfoList)
                    {
                        if ((endpointAddress & UsbConstants.ENDPOINT_NUMBER_MASK) == 0)
                        {
                            // find first read/write endpoint
                            if ((endpointAddress & UsbConstants.ENDPOINT_DIR_MASK) == 0 &&
                                (endpointInfo.Descriptor.EndpointID & UsbConstants.ENDPOINT_DIR_MASK) == 0)
                            {
                                // first write endpoint
                                found = true;
                            }
                            if ((endpointAddress & UsbConstants.ENDPOINT_DIR_MASK) != 0 &&
                                (endpointInfo.Descriptor.EndpointID & UsbConstants.ENDPOINT_DIR_MASK) != 0)
                            {
                                // first read endpoint
                                found = true;
                            }
                        }
                        else if (endpointInfo.Descriptor.EndpointID == endpointAddress)
                        {
                            found = true;
                        }

                        if (found)
                        {
                            usbInterfaceInfo = interfaceInfo;
                            usbEndpointInfo  = endpointInfo;
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
예제 #7
0
        private static ErrorCode GetConfigs(MonoUsbDevice usbDevice, out List <UsbConfigInfo> configInfoListRtn)
        {
            configInfoListRtn = new List <UsbConfigInfo>();
            UsbError usbError = null;
            List <MonoUsbConfigDescriptor> configList = new List <MonoUsbConfigDescriptor>();
            int iConfigs = usbDevice.Info.Descriptor.ConfigurationCount;

            for (int iConfig = 0; iConfig < iConfigs; iConfig++)
            {
                MonoUsbConfigHandle nextConfigHandle;
                int ret = MonoUsbApi.GetConfigDescriptor(usbDevice.mMonoUSBProfile.ProfileHandle, (byte)iConfig, out nextConfigHandle);
                Debug.Print("GetConfigDescriptor:{0}", ret);
                if (ret != 0 || nextConfigHandle.IsInvalid)
                {
                    usbError = UsbError.Error(ErrorCode.MonoApiError,
                                              ret,
                                              String.Format("GetConfigDescriptor Failed at index:{0}", iConfig),
                                              usbDevice);
                    return(usbError.ErrorCode);
                }
                try
                {
                    MonoUsbConfigDescriptor nextConfig = new MonoUsbConfigDescriptor();
                    Marshal.PtrToStructure(nextConfigHandle.DangerousGetHandle(), nextConfig);

                    UsbConfigInfo nextConfigInfo = new UsbConfigInfo(usbDevice, nextConfig);
                    configInfoListRtn.Add(nextConfigInfo);
                }
                catch (Exception ex)
                {
                    UsbError.Error(ErrorCode.InvalidConfig, Marshal.GetLastWin32Error(), ex.ToString(), usbDevice);
                }
                finally
                {
                    if (!nextConfigHandle.IsInvalid)
                    {
                        nextConfigHandle.Close();
                    }
                }
            }

            return(ErrorCode.Success);
        }
        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);//设置光标的位置到文本尾
        }
예제 #9
0
        public static void Main(string[] args)
        {
            // Dump all devices and descriptor information to console output.
            var allDevices = UsbDevice.AllDevices;

            foreach (var usbRegistry in allDevices)
            {
                Console.WriteLine(usbRegistry.Info.ToString());

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

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

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

                    usbRegistry.Close();
                }
            }


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

            // Wait for user input..
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
예제 #10
0
파일: dfu.cs 프로젝트: glocklueng/NXP_DFU
 /// <summary>
 ///   Find the interface that supports DFU. Return true if found.
 /// </summary>
 public bool findInterface()
 {
   byte currentConfig;
   
   foreach (UsbConfigInfo config in myUSBDevice.Configs)
     {
       currentConfig=config.Descriptor.ConfigID;
       foreach (UsbInterfaceInfo iface in config.InterfaceInfoList)
         {
           if (((byte)iface.Descriptor.Class == 0xFE /*Application Specific*/) &&
               ((byte)iface.Descriptor.SubClass == 0x01 /* DFU */) ) {
             DFUinterface=iface.Descriptor.InterfaceID;
             DFUconfig=currentConfig;
             myDFUconfig=config;
             myDFUiface=iface;
             return(true);
           }
         }
     }
   return(false);
 }
예제 #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();
        }
예제 #12
0
        public static void Main(string[] args)
        {
            // Dump all devices and descriptor information to console output.
            using (UsbContext context = new UsbContext())
            {
                var allDevices = context.List();
                foreach (var usbRegistry in allDevices)
                {
                    Console.WriteLine(usbRegistry.Info.ToString());

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

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

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

                        usbRegistry.Close();
                    }
                }
            }

            // Wait for user input..
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
예제 #13
0
        private void GetConfigValue_Click(object sender, EventArgs e)
        {
            byte bConfig;

            if (mUsbDevice.GetConfiguration(out bConfig))
            {
                ReadOnlyCollection <UsbConfigInfo> configProfiles = mUsbDevice.Configs;
                if (bConfig == 0 || bConfig > configProfiles.Count)
                {
                    tInfo.AppendText("[ERROR] Invalid configuration data received.");
                    return;
                }
                UsbConfigInfo currentConfig = configProfiles[bConfig - 1];
                SetStatus(string.Format("Config Value:{0} Size:{1}", bConfig, currentConfig.Descriptor.TotalLength), false);

                tInfo.AppendText(currentConfig.ToString());
            }
            else
            {
                SetStatus("GetConfiguration Failed.", true);
            }
        }
예제 #14
0
 private bool DeviceInit(int vendorID, int productID, bool deviceReset = true)
 {
     try {
         _vendorID  = vendorID;
         _productID = productID;
         Device     = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(vendorID, productID));
         if (Device == null)
         {
             Main.SendDebug(string.Format("No Device Found with VendorID: 0x{0:X04} and ProductID: 0x{1:X04}", vendorID, productID));
             Release();
             return(false);
         }
         if (deviceReset)
         {
             Release();
             Thread.Sleep(1000);
             return(DeviceInit(vendorID, productID, false));
         }
         DeviceConfigInfo = Device.Configs[0];
         var wholeUsbDevice = Device as IUsbDevice;
         if (!ReferenceEquals(wholeUsbDevice, null))
         {
             wholeUsbDevice.SetConfiguration(DeviceConfigInfo.Descriptor.ConfigID);
             wholeUsbDevice.ClaimInterface(0);
         }
         _reader = Device.OpenEndpointReader((ReadEndpointID)0x82);
         ClearReadBuffer();
         _writer = Device.OpenEndpointWriter((WriteEndpointID)0x05);
         UsbDevice.UsbErrorEvent += UsbDeviceOnUsbErrorEvent;
         return(true);
     }
     catch (Exception ex) {
         Main.SendDebug(String.Format("Device Init exception occured: {0}", ex.Message));
         throw;
     }
 }
예제 #15
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();
        }
예제 #16
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);
        }
예제 #17
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);
            }
        }
예제 #18
0
        public static UsbLibDotNetHIDDevice FindDevice(int vendorID, int productID, byte configID = 1, byte interfaceID = 0)
        {
            UsbLibDotNetHIDDevice newDev    = null;
            UsbDeviceFinder       usbFinder = new UsbDeviceFinder(vendorID, productID);
            UsbDevice             usbDev    = null;
            //Byte configID = 255;
            bool endpointsFound = false;

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

                // If the device is open and ready
                if (usbDev == null)
                {
                    Console.WriteLine("Device Not Found [0x" + vendorID.ToString("x4") + ":0x" + productID.ToString("x4") + "].");
                    return(null);
                }

                newDev = new UsbLibDotNetHIDDevice();

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

                    if (configID == configInfo.Descriptor.ConfigID)
                    {
                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;

                        //Console.WriteLine("Config Found: " + configInfo.Descriptor.ConfigID.ToString());
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];

                            if (interfaceID == interfaceInfo.Descriptor.InterfaceID)
                            {
                                //Console.WriteLine("Interface Found: " + interfaceInfo.Descriptor.EndpointCount.ToString());
                                // We need 2 Endpoints
                                if (interfaceInfo.Descriptor.EndpointCount == 2)
                                {
                                    ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;

                                    //Console.WriteLine("Two Endpoints Found");
                                    for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                                    {
                                        if (iEndpoint == 0)
                                        {
                                            newDev.m_readEndpoint = (ReadEndpointID)endpointList[iEndpoint].Descriptor.EndpointID;
                                        }
                                        else
                                        {
                                            newDev.m_writeEndpoint = (WriteEndpointID)endpointList[iEndpoint].Descriptor.EndpointID;
                                        }

                                        newDev.m_configID    = configInfo.Descriptor.ConfigID;
                                        newDev.m_interfaceID = interfaceInfo.Descriptor.InterfaceID;
                                    }

                                    endpointsFound = true;
                                }
                            }
                        }
                    }
                }

                if (String.Compare(System.Environment.GetEnvironmentVariable("USBLIBDOTNET_VERBOSE"), "yes", true) == 0)
                {
                    Console.WriteLine("*** GD77 USB Device Infos:\n  - " + usbDev.Info.ToString().Replace("\n", "\n  - "));
                    for (int iConfig = 0; iConfig < usbDev.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = usbDev.Configs[iConfig];

                        Console.WriteLine("   *** ConfigID: " + configInfo.Descriptor.ConfigID);
                        Console.WriteLine("   CONFIGURATION INFO: \n     - " + configInfo.ToString().Replace("\n", "\n        - "));

                        ReadOnlyCollection <UsbInterfaceInfo> interfaceList = configInfo.InterfaceInfoList;
                        for (int iInterface = 0; iInterface < interfaceList.Count; iInterface++)
                        {
                            UsbInterfaceInfo interfaceInfo = interfaceList[iInterface];
                            Console.WriteLine("         *** InterfaceID: " + interfaceInfo.Descriptor.InterfaceID);
                            Console.WriteLine("         INTERFACE INFO: \n        - " + interfaceInfo.ToString().Replace("\n", "\n        - "));

                            ReadOnlyCollection <UsbEndpointInfo> endpointList = interfaceInfo.EndpointInfoList;
                            for (int iEndpoint = 0; iEndpoint < endpointList.Count; iEndpoint++)
                            {
                                Console.WriteLine("            ENDPOINT LIST: \n           - " + endpointList[iEndpoint].ToString().Replace("\n", "\n           - "));
                            }
                        }
                    }
                    Console.WriteLine("***\n");
                }
                if (endpointsFound == false)
                {
                    Console.WriteLine("Couldn't find 2 endpoints for interface #" + interfaceID.ToString() + " of configuration #" + configID.ToString());
                    return(null);
                }
                // 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 = usbDev as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
#if DUMP_USB_INFOS
                    Console.WriteLine("*** ConfigID: " + newDev.m_configID);
                    Console.WriteLine("*** InterfaceID: " + newDev.m_interfaceID);
#endif
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

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

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

                // open read endpoint 1.
                newDev.m_usbReader = usbDev.OpenEndpointReader(newDev.m_readEndpoint);
                newDev.m_usbReader.ReadThreadPriority = ThreadPriority.AboveNormal;

                // open write endpoint 2
                newDev.m_usbWriter = usbDev.OpenEndpointWriter(newDev.m_writeEndpoint);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.Message);
                return(null);
            }

            newDev.m_usbDevice = usbDev;
            newDev.m_vendorID  = vendorID;
            newDev.m_productID = productID;

            return(newDev);
        }
예제 #19
0
 /// <summary>
 /// Looks up endpoint/interface information in a configuration.
 /// </summary>
 /// <param name="currentConfigInfo">The config to seach.</param>
 /// <param name="endpointAddress">The endpoint address to look for.</param>
 /// <param name="usbInterfaceInfo">On success, the <see cref="UsbInterfaceInfo"/> class for this endpoint.</param>
 /// <param name="usbEndpointInfo">On success, the <see cref="UsbEndpointInfo"/> class for this endpoint.</param>
 /// <returns>True of the endpoint was found, otherwise false.</returns>
 public static bool LookupEndpointInfo(UsbConfigInfo currentConfigInfo, byte endpointAddress, out UsbInterfaceInfo usbInterfaceInfo, out UsbEndpointInfo usbEndpointInfo)
 {
     return(LookupEndpointInfo(currentConfigInfo, -1, endpointAddress, out usbInterfaceInfo, out usbEndpointInfo));
 }
예제 #20
0
 public bool TryGetConfigDescriptor(byte configIndex, out UsbConfigInfo descriptor)
 {
     return(_device.TryGetConfigDescriptor(configIndex, out descriptor));
 }
예제 #21
0
        public static List <PTPDevice> FindDevices(bool only_supported = true, Func <UsbDevice, PTPDevice> constr = null)
        {
            List <PTPDevice> l = new List <PTPDevice>();

            if (constr == null)
            {
                constr = x => new PTPDevice(x);
            }

            foreach (UsbRegistry reg in UsbDevice.AllDevices)
            {
                UsbDevice dev;
                if (reg.Open(out dev))
                {
                    PTPDevice ptpdev = constr(dev);

                    for (int i = 0; i < dev.Configs.Count; i++)
                    {
                        UsbConfigInfo config_info = dev.Configs[i];

                        foreach (UsbInterfaceInfo interface_info in config_info.InterfaceInfoList)
                        {
                            if (interface_info.Descriptor.Class == ClassCodeType.Ptp)
                            {
                                bool rid_set = false;
                                bool wid_set = false;

                                foreach (UsbEndpointInfo endpoint_info in interface_info.EndpointInfoList)
                                {
                                    // BULK and assumed MaxPacketSize
                                    if ((endpoint_info.Descriptor.Attributes & 0x03) != 0x02 || endpoint_info.Descriptor.MaxPacketSize != 512)
                                    {
                                        continue;
                                    }

                                    if ((endpoint_info.Descriptor.EndpointID & 0x80) == 0)
                                    {
                                        ptpdev.WriterEndpointID = (WriteEndpointID)endpoint_info.Descriptor.EndpointID;
                                        wid_set = true;
                                    }
                                    else
                                    {
                                        ptpdev.ReaderEndpointID = (ReadEndpointID)endpoint_info.Descriptor.EndpointID;
                                        rid_set = true;
                                    }
                                }

                                if (rid_set && wid_set)
                                {
                                    ptpdev.ConfigurationID = config_info.Descriptor.ConfigID;
                                    ptpdev.InterfaceID     = interface_info.Descriptor.InterfaceID;
                                    ptpdev.PTPSupported    = true;
                                    break;
                                }
                            }
                            if (ptpdev.PTPSupported)
                            {
                                break;
                            }
                        }
                    }

                    if (!only_supported || ptpdev.PTPSupported)
                    {
                        l.Add(ptpdev);
                    }

                    dev.Close(); // always close so we don't have a list of open but unused devices
                }
            }

            return(l);
        }
예제 #22
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);
        }