protected override void Initialize()
        {
            winUsbForm               = new Form();
            notifier                 = new USBNotifier(winUsbForm, guid);
            winUsbForm.Name          = "WinUSB form";
            notifier.Arrival        += OnDeviceArrival;
            notifier.Removal        += OnDeviceRemoval;
            winUsbForm.Size          = new System.Drawing.Size(0, 0);
            winUsbForm.WindowState   = FormWindowState.Minimized;
            winUsbForm.ShowInTaskbar = false;
            winUsbForm.Enabled       = false;
            winUsbForm.Show();
            winUsbForm.Visible = false;
            USBDeviceInfo[] usbDeviceList = USBDevice.GetDevices(guid);
            C.Logger.Debug("Total number of Win USB devices attached: " + usbDeviceList.Length.ToString());
            foreach (USBDeviceInfo device in usbDeviceList)
            {
                string sAdd = string.Format("Vid:0x{0:X4} Pid:0x{1:X4} (dsc:{2}) - path:{3}",
                                            device.VID,
                                            device.PID,
                                            device.DeviceDescription, device.DevicePath);

                C.Logger.Debug(sAdd);
            }
        }
示例#2
0
        /// <summary>
        /// Initialize resources, open usb driver, register for
        /// USB events
        /// </summary>
        /// <returns>true on success, false otherwise</returns>
        public override bool Init()
        {
            Settings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName);
            WordsPlusActuatorSettings    = Settings.Load();

            // register for USB events "PID_0303";
            _usbDevice = new USBDevice(WordsPlusVid, _wordsPlusPID);
            _usbDevice.EvtReadDataNotify     += _usbDevice_EvtReadDataNotify;
            _usbDevice.EvtDeviceDisconnected += _usbDevice_EvtDeviceDisconnected;

            // timer is used, in case the USB device is
            // not connected.  Let's poll periodically to
            // see if it is plugged in
            _timer = new Timer {
                Interval = WordsPlusActuatorSettings.WordsPlusKeyCheckInterval
            };
            _timer.Elapsed += _timer_Elapsed;

            // open usb device and begin reading data
            if (!openAndBeginRead())
            {
                _timer.Start();
            }

            return(true);
        }
示例#3
0
        public void enter(object s, EventArgs a)
        {
            device = new USBDevice(0xffff, 0x1f40, null, false, 31);

            if (device == null)
            {
                return;
            }

            mainWindow?.Dispatcher.Invoke(() => { mainWindow.Title = "Infinitton WPF - Device Connected"; });

            Console.WriteLine(device.GetProductString());

            // add handle for data read
            device.InputReportArrivedEvent += handle;
            // after adding the handle start reading
            device.StartAsyncRead();
            // can add more handles at any time
            device.InputReportArrivedEvent += handle;

            SetDeviceBrightness(Properties.Settings.Default.Brightness);


            LoadIcons();
        }
示例#4
0
        /// <summary>
        /// Initializes the device via LibUSB, and sets the refresh interval of the controller data
        /// </summary>
        /// <param name="Interval">The interval that the device is polled for information.</param>
        public void Init(int Interval)
        {
            //ErrorCode ec = ErrorCode.None;


            //HKEY_LOCAL_MACHINE\System\CurrentControlSet\Enum\USB\VID_0A7B&PID_D000\6&688a3b8&0&1\Device Parameters\DeviceInterfaceGUIDs
            USBDeviceInfo[] details = USBDevice.GetDevices("{5C2B3F1A-E9B8-4BD6-9D19-8A283B85726E}");
            USBDeviceInfo   match   = details.First(info => info.VID == 0x0A7B && info.PID == 0xD000);

            MyUsbDevice = new USBDevice(match);
            reader      = MyUsbDevice.Interfaces.First().InPipe;
            writer      = MyUsbDevice.Interfaces.First().OutPipe;

            byte[] buf = new byte[64];

            reader.Read(buf);//can't remember why I do this.

            ButtonMasks.InitializeMasks();

            SetPollingInterval(Interval);
            pollTimer.Elapsed += new ElapsedEventHandler(pollTimer_Elapsed);
            pollTimer.Start();

            TestLEDs();
            if (updateGearLights)
            {
                GearLightsRefresh((int)unchecked ((sbyte)buf[25]));
            }
            RefreshLEDState();
        }
示例#5
0
        /// <summary>
        /// Prepare interrupt
        /// </summary>
        /// <param name="dev"></param>
        /// <param name="transfer"></param>
        private static void PrepareInterrupt(USBDevice dev, USBTransfer *transfer)
        {
            UHCIController controller = (UHCIController)dev.Controller;

            uint endp = (uint)(dev.EndPointDesc->Address & 0xF);

            UHCITransmitDescriptor *td = GetTransmit(controller);

            if (td == null)
            {
                transfer->Success  = false;
                transfer->Executed = true;
            }

            UHCITransmitDescriptor *head = td;

            /**
             * Initalize read
             */
            InitTransmit(td, null, dev.Speed, dev.Address, endp, dev.Toggle, TRANS_PACKET_IN, transfer->Length, transfer->Data);

            UHCIQueueHead *qh = GetQueueHead(controller);

            qh->Element  = (int)Paging.GetPhysicalFromVirtual(head);
            qh->Head     = 0;
            qh->Transfer = transfer;
            qh->Transmit = head;

            InsertHead(controller, qh);
        }
        /// <summary>
        /// Initializes the device via LibUSB, and sets the refresh interval of the controller data
        /// </summary>
        /// <param name="Interval">The interval that the device is polled for information.</param>
        public void Init(int Interval)
        {
            //ErrorCode ec = ErrorCode.None;

            //zadig creates a new device GUID everytime you install, so I placed file in
            //C:\Users\salds_000\Documents\Visual Studio 2013\Projects\steel_batallion-64\steelbattalionnet\winusb\usb_driver
            //check inf file for guid. Right clicking the inf file installs it.

            //after installation you can find this in regedit
            //HKEY_LOCAL_MACHINE\System\CurrentControlSet\Enum\USB\VID_0A7B&PID_D000\6&688a3b8&0&1\Device Parameters\DeviceInterfaceGUIDs
            USBDeviceInfo[] details = USBDevice.GetDevices("{5C2B3F1A-E9B8-4BD6-9D19-8A283B85726E}");
            USBDeviceInfo   match   = details.First(info => info.VID == 0x0A7B && info.PID == 0xD000);

            MyUsbDevice = new USBDevice(match);
            reader      = MyUsbDevice.Interfaces.First().InPipe;
            writer      = MyUsbDevice.Interfaces.First().OutPipe;

            byte[] buf = new byte[64];

            reader.Read(buf);//can't remember why I do this.

            ButtonMasks.InitializeMasks();

            SetPollingInterval(Interval);
            pollTimer.Elapsed += new ElapsedEventHandler(pollTimer_Elapsed);
            pollTimer.Start();

            TestLEDs();
            if (updateGearLights)
            {
                GearLightsRefresh((int)unchecked ((sbyte)buf[25]));
            }
            RefreshLEDState();
        }
示例#7
0
        public unsafe IUSBDriver Load(USBDevice device)
        {
            USBInterfaceDescriptor *desc = device.InterfaceDesc;

            if (!(desc->Class == (byte)USBClassCodes.HID &&
                  desc->SubClass == 0x01 &&
                  desc->Protocol == 0x02))
            {
                return(null);
            }

            device.Classifier = USBDeviceClassifier.FUNCTION;

            mTransfer = (USBTransfer *)Heap.Alloc(sizeof(USBTransfer));
            mLocation = (MouseLocation *)Heap.Alloc(sizeof(MouseLocation));

            /**
             * Prepare poll transfer
             */
            mTransfer->Data     = (byte *)mLocation;
            mTransfer->Length   = 3;
            mTransfer->Executed = false;
            mTransfer->Success  = false;
            mTransfer->ID       = 2;



            //device.PrepareInterrupt(device, mTransfer);


            return(this);
        }
示例#8
0
        private void send_button_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                return;
            }

            USBDevice USB = new USBDevice(0x1234, 0x5678);

            if (!USB.Connect())
            {
                MessageBox.Show("Unable to connect to the USB device!");
                return;
            }

            byte[] buffer = Encoding.ASCII.GetBytes(textBox1.Text);

            if (USB.Write(buffer))
            {
                richTextBox1.Text += Encoding.ASCII.GetString(buffer) + "\r\n";
            }
            else
            {
                MessageBox.Show("Send error data!");
            }
        }
示例#9
0
文件: Fel.cs 项目: jpcoop/hakchi2
 public void Open(UInt16 vid, UInt16 pid)
 {
     this.vid = vid;
     this.pid = pid;
     Close();
     device = USBDevice.GetSingleDevice(vid, pid);
     if (device == null)
     {
         throw new FelException("Device not found");
     }
     foreach (var pipe in device.Pipes)
     {
         if (pipe.IsIn)
         {
             inEndp = pipe.Address;
         }
         else
         {
             outEndp = pipe.Address;
         }
     }
     device.Pipes[outEndp].Policy.PipeTransferTimeout = ReadTimeout;
     ClearInputBuffer();
     if (VerifyDevice().Board != 0x00166700)
     {
         throw new FelException("Invalid board ID");
     }
 }
示例#10
0
        public Form1()
        {
            InitializeComponent();
            logger.Info("Trying to connect to device with GUID: {0}", deviceGUID.ToString());
            if (USBDevice.GetDevices(deviceGUID).Count() > 0)
            {
                try
                {
                    device = USBDevice.GetSingleDevice(deviceGUID);
                }catch (USBException ex)
                {
                    logger.Warn("Something went wrong connecting to device", ex);
                }
            }

            connectionNotifier = new USBNotifier(this, deviceGUID); //setup connection and disconnection Notifier
            if (device == null)
            {
                logger.Warn("No Device found");
            }
            else
            {
                logger.Info("Connected to device");
                logDeviceiFaceProperties(device);
            }
            connectionNotifier.Arrival += ConnectionNotifier_Arrival;
            connectionNotifier.Removal += ConnectionNotifier_Removal;
        }
示例#11
0
        private void SetDevice()
        {
            USBDevice dev = usbDevices[46084, 4099];

            if (dev != null)
            {
                cyDevice        = (CyUSBDevice)dev;
                controlEndPoint = null;
                bulkInEndPoint  = null;

                GetEndpointsOfNode(cyDevice.Tree);
                if (controlEndPoint != null)
                {
                    isReady = true;

                    name     = dev.FriendlyName;
                    version  = GetFirmwareVer();
                    revision = GetRevision();

                    DeviceReadyEventArgs args = new DeviceReadyEventArgs();
                    args.DeviceName = name;
                    args.VidPid     = new[] { dev.VendorID, dev.ProductID };
                    args.Version    = version;
                    args.Revision   = revision;

                    DeviceReady?.Invoke(this, args);
                }
            }
            else
            {
                isReady = false;
                DeviceNotReady?.Invoke(this, null);
            }
        }
示例#12
0
 public void Open(UInt16 vid, UInt16 pid)
 {
     this.vid = vid;
     this.pid = pid;
     Close();
     Debug.WriteLine("Trying to open device...");
     device = USBDevice.GetSingleDevice(vid, pid);
     if (device == null)
     {
         throw new FelException("Device with such VID and PID not found");
     }
     Debug.WriteLine("Checking USB endpoints...");
     foreach (var pipe in device.Pipes)
     {
         if (pipe.IsIn)
         {
             inEndp = pipe.Address;
             Debug.WriteLine("IN endpoint found: " + inEndp);
         }
         else
         {
             outEndp = pipe.Address;
             Debug.WriteLine("Out endpoint found: " + outEndp);
         }
     }
     device.Pipes[inEndp].Policy.PipeTransferTimeout  = ReadTimeout;
     device.Pipes[outEndp].Policy.PipeTransferTimeout = WriteTimeout;
     Debug.WriteLine("Trying to verify device");
     if (VerifyDevice().Board != 0x00166700)
     {
         throw new FelException("Invalid board ID: " + VerifyDevice().Board);
     }
 }
        /// <summary>
        /// Specifies the list of adapters connected to a Host.
        /// </summary>
        /// <returns>Adapaters list.</returns>
        public static List <CanAdapterItem> GetAdapters()
        {
            USBDeviceInfo[]       dies     = USBDevice.GetDevices("{AA40624D-0F4B-4F4F-8E23-BA4209EE3AF2}");
            List <CanAdapterItem> adapters = new List <CanAdapterItem>();

            foreach (USBDeviceInfo info in dies)
            {
                var adapter = new CanAdapterItem();
                adapter.DevicePath = info.DevicePath;

                adapter.SerialNumber      = info.DevicePath.ToUpper().Split('#')[2];
                adapter.DeviceDescription = info.DeviceDescription;
                try
                {
                    Mutex mut = Mutex.OpenExisting(adapter.DeviceDescription + " " + adapter.SerialNumber);
                    adapter.InUse = true;
                    mut.Close();
                    mut = null;
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    adapter.InUse = false;
                }
                adapters.Add(adapter);
            }

            return(adapters);
        }
示例#14
0
文件: Reader.cs 项目: tate98/USB
 public void StartListening()
 {
     USBDevice?.Close();
     DeviceListener.DeviceDisconnected += DevicePoller_DeviceDisconnected;
     DeviceListener.DeviceInitialized  += DevicePoller_DeviceInitialized;
     DeviceListener.Start();
 }
示例#15
0
        public QualcommSerial(string DevicePath)
        {
            CRC16 = new CRC16(0x1189, 0xFFFF, 0xFFFF);

            string[] DevicePathElements = DevicePath.Split(new char[] { '#' });
            if (string.Equals(DevicePathElements[3], "{86E0D1E0-8089-11D0-9CE4-08003E301F73}", StringComparison.CurrentCultureIgnoreCase))
            {
                string PortName = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\" + DevicePathElements[1] + @"\" + DevicePathElements[2] + @"\Device Parameters", "PortName", null);
                if (PortName != null)
                {
                    Port = new SerialPort(PortName, 115200)
                    {
                        ReadTimeout  = 1000,
                        WriteTimeout = 1000
                    };
                    Port.Open();
                }
            }
            else
            {
                try
                {
                    this.USBDevice = new USBDevice(DevicePath);
                }
                catch { }
            }
        }
示例#16
0
        internal async Task <byte[]> ReadPacket(USBDevice device, byte[] packet)
        {
            var input = new MemoryStream();

            for (int i = 0; i < packet.Length; i++)
            {
                var readedByte = packet[i];
                if (readedByte == PinPadConstants.ACK || readedByte == PinPadConstants.NAK)
                {
                    continue;
                }
                input.WriteByte(readedByte);

                if (readedByte == PinPadConstants.SYN)
                {
                    continue;
                }

                if (readedByte == PinPadConstants.ETB)
                {
                    var data = input.ToArray().Skip(1).ToArray();
                    await device.TransferOut(2, new byte[] { PinPadConstants.ACK });

                    return(data.Take(data.Length - 1).ToArray());
                }
            }
            return(null);
        }
示例#17
0
文件: Reader.cs 项目: tate98/USB
 public void Dispose()
 {
     DeviceListener.DeviceDisconnected -= DevicePoller_DeviceDisconnected;
     DeviceListener.DeviceInitialized  -= DevicePoller_DeviceInitialized;
     DeviceListener.Dispose();
     USBDevice?.Dispose();
 }
示例#18
0
        internal WinusbAppiDev(USBDeviceInfo di)
        {
            // TODO: Отлавливать исключения WinUsbNet
            try
            {
                Device     = new USBDevice(di);
                DevicePath = di.DevicePath;

                ReadPipe = Device.Pipes.First(p => p.IsIn);
                ReadPipe.Policy.PipeTransferTimeout = 100;
                ReadPipe.Policy.AutoClearStall      = true;
                ReadPipe.Flush();

                WritePipe = Device.Pipes.First(p => p.IsOut);
                WritePipe.Policy.PipeTransferTimeout = 100;

                lock (OpenedDevicesLocker)
                {
                    OpenedDevices.Add(this);
                }
            }
            catch (USBException e)
            {
                throw new AppiConnectoinException(e);
            }
        }
示例#19
0
        internal async Task <DeviceInfo> Open(USBDevice device)
        {
            var readed = await WritePacket(device, GetCommandData(CommandTypes.Open));

            var ret = GetReturnCode(Encoding.ASCII.GetString(readed));

            if (ret != ReturnCodes.Ok && ret != ReturnCodes.AlreadyOpen)
            {
                this._logger.LogError("Unable to open PinPad.");
                return(null);
            }
            await Cancel(device);

            readed = await WritePacket(device, GetCommandData(CommandTypes.Open));

            ret = GetReturnCode(Encoding.ASCII.GetString(readed));
            if (ret != ReturnCodes.Ok && ret != ReturnCodes.AlreadyOpen)
            {
                this._logger.LogError("Unable to open PinPad.");
                return(null);
            }

            await DisplayMessage(device, "Getting device info...");

            readed = await WritePacket(device, GetCommandData(CommandTypes.GetInfo, ((short)0).ToString().PadLeft(2, '0')));

            ret = GetReturnCode(Encoding.ASCII.GetString(readed));
            if (ret != ReturnCodes.Ok)
            {
                this._logger.LogError("Unable to read device info.");
                return(null);
            }
            return(new DeviceInfo(readed));
        }
示例#20
0
        /*Summary
         * Search the device with VID-PID 04b4-00F1 and if found, select the end point
         */
        private void SetDevice()
        {
            USBDevice dev = usbDevices[0x04B4, 0x00F1];

            if (dev != null)
            {
                MyDevice = (CyUSBDevice)dev;

                GetEndpointsOfNode(MyDevice.Tree);
                PpxBox.Text = "8"; //Set default value to 8 Packets
                if (EndPointsComboBox.Items.Count > 0)
                {
                    EndPointsComboBox.SelectedIndex = 0;
                    StartBtn.Enabled = true;
                }
                Text = MyDevice.FriendlyName;
            }
            else
            {
                StartBtn.Enabled = false;
                EndPointsComboBox.Items.Clear();
                EndPointsComboBox.Text = "";
                Text = "C# Streamer - no device";
            }
        }
示例#21
0
        private void logDeviceiFaceProperties(USBDevice device)
        {
            logger.Trace("Device Properties:");
            logger.Trace(device.Descriptor.FullName);
            logger.Trace("VID: {0:X4} - PID: {1:X4} ", device.Descriptor.VID, device.Descriptor.PID);
            logger.Trace("MFG {0} ", device.Descriptor.Manufacturer);
            logger.Trace("SerialNo {0} ", device.Descriptor.SerialNumber);
            logger.Trace("Product {0} ", device.Descriptor.Product);
            logger.Trace("Number of interfaces: {0}", device.Interfaces.Count());
            int count = 0;

            foreach (USBInterface iface in device.Interfaces)
            {
                logger.Trace("Interface {0}", count);

                logger.Trace("Number of Pipes in current interface: {0} ", iface.Pipes.Count());
                count++;
                int pipecount = 0;
                foreach (USBPipe pipe in iface.Pipes)
                {
                    logger.Trace("Pipe {0} with direction {1}", pipecount, pipe.IsIn ? "IN" : "OUT");
                    pipecount++;
                }
            }
        }
示例#22
0
 public USBMissileLauncher()
 {
     commandQueue = new ConcurrentQueue <TimedCommand>();
     device       = new USBDevice();
     device.turnLedOn();
     InitTimer();
 }
 public RezTranceVibratorDevice(IButtplugLogManager aLogManager, USBDevice aDevice, uint aIndex)
     : base(aLogManager, "Trancevibrator " + aIndex, "Trancevibrator " + aIndex)
 {
     _device = aDevice;
     MsgFuncs.Add(typeof(SingleMotorVibrateCmd), new ButtplugDeviceWrapper(HandleSingleMotorVibrateCmd));
     MsgFuncs.Add(typeof(StopDeviceCmd), new ButtplugDeviceWrapper(HandleStopDeviceCmd));
     MsgFuncs.Add(typeof(VibrateCmd), new ButtplugDeviceWrapper(HandleVibrateCmd));
 }
示例#24
0
 public int DevicesConnected()
 {
     if (NumDevices == 1)
     {
         SelectedDevice = (USBDevice)Webcams[0];
     }
     return(NumDevices);
 }
示例#25
0
文件: Fel.cs 项目: jpcoop/hakchi2
 public void Close()
 {
     if (device != null)
     {
         device.Dispose();
         device = null;
     }
 }
示例#26
0
        internal USBPipe(USBDevice device, API.WINUSB_PIPE_INFORMATION pipeInfo)
        {
            _pipeInfo = pipeInfo;
            _device   = device;

            // Policy is not set until interface is attached
            _policy = null;
        }
示例#27
0
 private void OnDisconnect(USBDevice device)
 {
     if (_filters.Any(f => f.ProductId == device.ProductId && f.VendorId == device.VendorId))
     {
         this._logger.LogInformation("PinPad disconnected:");
         this._logger.LogInformation(device);
     }
 }
示例#28
0
 public void ReadSomeData()
 {
     //int num = USBDevice.GetNumberOfDevices() - 1;
     USBDevice device = new USBDevice(0);
     device.Open();
     Thread.Sleep(500);
     var data = device.Read();
     Debug.WriteLine(data);
 }
示例#29
0
 /// <summary>
 /// 设备已断开事件
 /// </summary>
 private void OnDeviceRemoved(USBDevice dev)
 {
     this.Dispatcher.Invoke((Action) delegate
     {
         DebugPrint($"连接已断开-> {dev.Path}");
         Refresh.IsEnabled = false;
         LoadHex.IsEnabled = false;
     });
 }
示例#30
0
文件: Form1.cs 项目: longzai2651/USB
 private void CloseUSB()
 {
     if (_usbDevice != null && !_usbDevice.IsOpen)
     {
         _usbDevice.OnUsbDataReceived -= _usbDevice_OnUsbDataReceived;
         _usbDevice.Close();
     }
     _usbDevice = null;
 }
示例#31
0
        public void FindDeviceByDeviceInterfaceGuid()
        {
            USBDeviceInfo[] dies = USBDevice.GetDevices("{AA40624D-0F4B-4F4F-8E23-BA4209EE3AF2}");
            USBDeviceInfo   di   = dies[0];
            USBDevice       dev  = new USBDevice(di.DevicePath);

            Assert.AreEqual("Konvolucio Bt", dev.Descriptor.Manufacturer);
            dev.Dispose();
        }
示例#32
0
            /*
            public static Device[] Enumerate()
            {
                List<Device> devices;
                devices = new List<Device>();
                USBDevice device;

                skyetek_hid h = new skyetek_hid();
                //string[] d = new string[];
                string[] d = h.FindTheHid();
                Console.Out.WriteLine("Device Count" + devices.Count);
                for (int i = 0; i < d.Length; i++)
                {
                    device = new USBDevice(d[i]);
                    devices.Add(device);
                }

                //Console.Out.WriteLine("Device Count" + devices.Count);
                return devices.ToArray();
            }
             */
            public static Device[] Enumerate()
            {
                List<Device> devices;
                devices = new List<Device>();
                USBDevice device;
                String emptyPath = "";

                skyetek_hid h = new skyetek_hid(emptyPath);
                //string[] d = new string[];
                //string[] d = h.FindTheHids();
                string[] d = h.GetGuids();
                //Console.Out.WriteLine("Device Count" + devices.Count);
                for (int i = 0; i < d.Length; i++)
                {
                    device = new USBDevice(d[i]);
                    devices.Add(device);
                }

                //Console.Out.WriteLine("Device Count" + devices.Count);
                return devices.ToArray();
            }
示例#33
0
            // return a down stream external hub
            public USBDevice GetDevice()
            {
                if (!PortIsDeviceConnected)
                {
                    return null;
                }
                USBDevice Device = new USBDevice();

                // Copy over some values from the Port class
                // Ya know, I've given some thought about making Device a derived class...
                Device.DevicePortNumber = PortPortNumber;
                Device.DeviceHubDevicePath = PortHubDevicePath;
                Device.DeviceDescriptor = PortDeviceDescriptor;

                // Open a handle to the Hub device
                IntPtr h = CreateFile(PortHubDevicePath, GENERIC_WRITE, FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                if (h.ToInt32() != INVALID_HANDLE_VALUE)
                {
                    int nBytesReturned;
                    int nBytes = BUFFER_SIZE;
                    // We use this to zero fill a buffer
                    string NullString = new string((char)0, BUFFER_SIZE / Marshal.SystemDefaultCharSize);

                    // The iManufacturer, iProduct and iSerialNumber entries in the
                    // Device Descriptor are really just indexes.  So, we have to
                    // request a String Descriptor to get the values for those strings.

                    if (PortDeviceDescriptor.iManufacturer > 0)
                    {
                        // build a request for string descriptor
                        USB_DESCRIPTOR_REQUEST Request = new USB_DESCRIPTOR_REQUEST();
                        Request.ConnectionIndex = PortPortNumber;
                        Request.SetupPacket.wValue = (short)((USB_STRING_DESCRIPTOR_TYPE << 8) + PortDeviceDescriptor.iManufacturer);
                        Request.SetupPacket.wLength = (short)(nBytes - Marshal.SizeOf(Request));
                        Request.SetupPacket.wIndex = 0x409; // Language Code
                        // Geez, I wish C# had a Marshal.MemSet() method
                        IntPtr ptrRequest = Marshal.StringToHGlobalAuto(NullString);
                        Marshal.StructureToPtr(Request, ptrRequest, true);

                        // Use an IOCTL call to request the String Descriptor
                        if (DeviceIoControl(h, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, ptrRequest, nBytes, ptrRequest, nBytes, out nBytesReturned, IntPtr.Zero))
                        {
                            // The location of the string descriptor is immediately after
                            // the Request structure.  Because this location is not "covered"
                            // by the structure allocation, we're forced to zero out this
                            // chunk of memory by using the StringToHGlobalAuto() hack above
                            IntPtr ptrStringDesc = new IntPtr(ptrRequest.ToInt32() + Marshal.SizeOf(Request));
                            USB_STRING_DESCRIPTOR StringDesc = (USB_STRING_DESCRIPTOR)Marshal.PtrToStructure(ptrStringDesc, typeof(USB_STRING_DESCRIPTOR));
                            Device.DeviceManufacturer = StringDesc.bString;
                        }
                        Marshal.FreeHGlobal(ptrRequest);
                    }
                    if (PortDeviceDescriptor.iProduct > 0)
                    {
                        // build a request for string descriptor
                        USB_DESCRIPTOR_REQUEST Request = new USB_DESCRIPTOR_REQUEST();
                        Request.ConnectionIndex = PortPortNumber;
                        Request.SetupPacket.wValue = (short)((USB_STRING_DESCRIPTOR_TYPE << 8) + PortDeviceDescriptor.iProduct);
                        Request.SetupPacket.wLength = (short)(nBytes - Marshal.SizeOf(Request));
                        Request.SetupPacket.wIndex = 0x409; // Language Code
                        // Geez, I wish C# had a Marshal.MemSet() method
                        IntPtr ptrRequest = Marshal.StringToHGlobalAuto(NullString);
                        Marshal.StructureToPtr(Request, ptrRequest, true);

                        // Use an IOCTL call to request the String Descriptor
                        if (DeviceIoControl(h, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, ptrRequest, nBytes, ptrRequest, nBytes, out nBytesReturned, IntPtr.Zero))
                        {
                            // the location of the string descriptor is immediately after the Request structure
                            IntPtr ptrStringDesc = new IntPtr(ptrRequest.ToInt32() + Marshal.SizeOf(Request));
                            USB_STRING_DESCRIPTOR StringDesc = (USB_STRING_DESCRIPTOR)Marshal.PtrToStructure(ptrStringDesc, typeof(USB_STRING_DESCRIPTOR));
                            Device.DeviceProduct = StringDesc.bString;
                        }
                        Marshal.FreeHGlobal(ptrRequest);
                    }
                    if (PortDeviceDescriptor.iSerialNumber > 0)
                    {
                        // build a request for string descriptor
                        USB_DESCRIPTOR_REQUEST Request = new USB_DESCRIPTOR_REQUEST();
                        Request.ConnectionIndex = PortPortNumber;
                        Request.SetupPacket.wValue = (short)((USB_STRING_DESCRIPTOR_TYPE << 8) + PortDeviceDescriptor.iSerialNumber);
                        Request.SetupPacket.wLength = (short)(nBytes - Marshal.SizeOf(Request));
                        Request.SetupPacket.wIndex = 0x409; // Language Code
                        // Geez, I wish C# had a Marshal.MemSet() method
                        IntPtr ptrRequest = Marshal.StringToHGlobalAuto(NullString);
                        Marshal.StructureToPtr(Request, ptrRequest, true);

                        // Use an IOCTL call to request the String Descriptor
                        if (DeviceIoControl(h, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, ptrRequest, nBytes, ptrRequest, nBytes, out nBytesReturned, IntPtr.Zero))
                        {
                            // the location of the string descriptor is immediately after the Request structure
                            IntPtr ptrStringDesc = new IntPtr(ptrRequest.ToInt32() + Marshal.SizeOf(Request));
                            USB_STRING_DESCRIPTOR StringDesc = (USB_STRING_DESCRIPTOR)Marshal.PtrToStructure(ptrStringDesc, typeof(USB_STRING_DESCRIPTOR));
                            Device.DeviceSerialNumber = StringDesc.bString;
                        }
                        Marshal.FreeHGlobal(ptrRequest);
                    }

                    // Get the Driver Key Name (usefull in locating a device)
                    USB_NODE_CONNECTION_DRIVERKEY_NAME DriverKey = new USB_NODE_CONNECTION_DRIVERKEY_NAME();
                    DriverKey.ConnectionIndex = PortPortNumber;
                    nBytes = Marshal.SizeOf(DriverKey);
                    IntPtr ptrDriverKey = Marshal.AllocHGlobal(nBytes);
                    Marshal.StructureToPtr(DriverKey, ptrDriverKey, true);

                    // Use an IOCTL call to request the Driver Key Name
                    if (DeviceIoControl(h, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, ptrDriverKey, nBytes, ptrDriverKey, nBytes, out nBytesReturned, IntPtr.Zero))
                    {
                        DriverKey = (USB_NODE_CONNECTION_DRIVERKEY_NAME)Marshal.PtrToStructure(ptrDriverKey, typeof(USB_NODE_CONNECTION_DRIVERKEY_NAME));
                        Device.DeviceDriverKey = DriverKey.DriverKeyName;

                        // use the DriverKeyName to get the Device Description and Instance ID
                        Device.DeviceName = GetDescriptionByKeyName(Device.DeviceDriverKey);
                        Device.DeviceInstanceID = GetInstanceIDByKeyName(Device.DeviceDriverKey);
                    }
                    Marshal.FreeHGlobal(ptrDriverKey);
                    CloseHandle(h);
                }
                return Device;
            }