public USB_DEVICE_DESCRIPTOR?ReadDeviceDescriptor() { try { //Check if device is initialized if (!Initialized) { Debug.WriteLine("Device needs to be initialized to read the descriptor."); return(null); } USB_DEVICE_DESCRIPTOR USB_DEVICE_DESCRIPTOR = new USB_DEVICE_DESCRIPTOR(); int descriptorSize = Marshal.SizeOf(USB_DEVICE_DESCRIPTOR); bool readed = WinUsb_GetDescriptor(WinUsbHandle, DESCRIPTOR_TYPE.USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, ref USB_DEVICE_DESCRIPTOR, descriptorSize, out int bytesRead) && bytesRead > 0; if (readed) { return(USB_DEVICE_DESCRIPTOR); } else { Debug.WriteLine("Failed to read device descriptor."); return(null); } } catch (Exception ex) { Debug.WriteLine("Failed to read device descriptor: " + ex.Message); return(null); } }
public static string GetManufact(IntPtr h, USB_DEVICE_DESCRIPTOR PortDeviceDescriptor, int PortPortNumber) { if (PortDeviceDescriptor.iManufacturer > 0) { int nBytesReturned; int nBytes = BUFFER_SIZE; // 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 string NullString = new string((char)0, nBytes / Marshal.SystemDefaultCharSize); 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)); return(StringDesc.bString); } Marshal.FreeHGlobal(ptrRequest); } return(""); }
USB_DEVICE_DESCRIPTOR ByteToDeviceDescriptor(byte[] packet) { GCHandle pinnedPacket = GCHandle.Alloc(packet, GCHandleType.Pinned); USB_DEVICE_DESCRIPTOR descriptor = (USB_DEVICE_DESCRIPTOR)Marshal.PtrToStructure( pinnedPacket.AddrOfPinnedObject(), typeof(USB_DEVICE_DESCRIPTOR)); pinnedPacket.Free(); return(descriptor); }
internal static extern Boolean WinUsb_GetDescriptor(IntPtr InterfaceHandle, Byte DescriptorType, Byte Index, UInt32 LanguageID, ref USB_DEVICE_DESCRIPTOR Buffer, UInt32 BufferLenght, ref UInt32 LengthTransferred);
private bool SelectConfiguration(EusbDeviceContext device, byte configIndex) { // 6. Sends TS_URB_CONTROL_DESCRIPTOR_REQUEST with the descriptor type of USB_DEVICE_DESCRIPTOR_TYPE. uint requestId = IdGenerator.NewId(); TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new UrbBuilder( URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE, requestId, 0).BuildDeviceDescriptorRequest(); rdpeusbAdapter.TransferInRequest(device, des, USB_DEVICE_DESCRIPTOR.DefaultSize); // 7. Receives a completion message with the result for USB_DEVICE_DESCRIPTOR."); EusbUrbCompletionPdu pdu = (EusbUrbCompletionPdu)rdpeusbAdapter.ExpectCompletion(device.VirtualChannel); if (null == pdu || pdu.HResult != (uint)HRESULT_FROM_WIN32.ERROR_SUCCESS) { return(false); } USB_DEVICE_DESCRIPTOR desDevice = UsbStructParser.Parse <USB_DEVICE_DESCRIPTOR>(pdu); // 8. Sends TS_URB_CONTROL_DESCRIPTOR_REQUEST to retrieve the total length of the configuration. requestId = IdGenerator.NewId(); des = new UrbBuilder( URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE, requestId, 0).BuildConfigurationDescriptorRequest(configIndex); rdpeusbAdapter.TransferInRequest(device, des, USB_CONFIGURATION_DESCRIPTOR.DefaultSize); // 9. Receives a completion message with the result for USB_CONFIGURATION_DESCRIPTOR."); pdu = (EusbUrbCompletionPdu)rdpeusbAdapter.ExpectCompletion(device.VirtualChannel); if (null == pdu || pdu.HResult != (uint)HRESULT_FROM_WIN32.ERROR_SUCCESS) { return(false); } USB_CONFIGURATION_DESCRIPTOR desConfig = UsbStructParser.Parse <USB_CONFIGURATION_DESCRIPTOR>(pdu); // 10. Sends TS_URB_CONTROL_DESCRIPTOR_REQUEST with the actual length of USB_CONFIGURATION_DESCRIPTOR result. requestId = IdGenerator.NewId(); des = new UrbBuilder( URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE, requestId, 0).BuildConfigurationDescriptorRequest(configIndex); rdpeusbAdapter.TransferInRequest(device, des, desConfig.wTotalLength); // 11. Receives a completion message with the complete result for USB_CONFIGURATION_DESCRIPTOR."); pdu = (EusbUrbCompletionPdu)rdpeusbAdapter.ExpectCompletion(device.VirtualChannel); // 12. Sends TS_URB_SELECT_CONFIGURATION URB request. UsbConfigurationParser configParser = new UsbConfigurationParser(); configParser.ParseAll(pdu); requestId = IdGenerator.NewId(); TS_URB_SELECT_CONFIGURATION sel = new UrbBuilder( URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE, requestId, 0).BuildSelectConfigRequest(configParser.Interfaces, configParser.configDescriptor); rdpeusbAdapter.TransferInRequest(device, sel, 0); // 13. Receives a completion message with the result for configuration selection."); EusbUrbCompletionNoDataPdu pduRes = (EusbUrbCompletionNoDataPdu)rdpeusbAdapter.ExpectCompletion(device.VirtualChannel); if (null == pduRes || pduRes.HResult != (uint)HRESULT_FROM_WIN32.ERROR_SUCCESS) { return(false); } TS_URB_SELECT_CONFIGURATION_RESULT urb = new TS_URB_SELECT_CONFIGURATION_RESULT(); if (!PduMarshaler.Unmarshal(pduRes.TsUrbResult, urb)) { return(false); } context.SelectedConfig = urb; return(true); }
public static extern bool WinUsb_GetDescriptor(IntPtr interfaceHandle, DESCRIPTOR_TYPE DescriptorType, byte Index, ushort LanguageID, ref USB_DEVICE_DESCRIPTOR deviceDesc, int BufferLength, out int LengthTransfered);
public bool InitializeDevice() { if (deviceList != null) { deviceList.Free(); } deviceList = null; if (usb != null) { usb.Free(); } usb = null; feature_value_dict.Clear(); feature_value_lookup_dict.Clear(); foreach (Control ctrl in this.Controls) { if (ctrl is ComboBox) { ComboBox box = (ComboBox)ctrl; box.Items.Clear(); } } deviceList = new LstK(KLST_FLAG.NONE); KLST_DEVINFO_HANDLE deviceInfo; DeviceInfo.Text = ""; bool success = false; deviceList.MoveReset(); while (deviceList.MoveNext(out deviceInfo)) { if ( // BSB 20120928 revised test // (deviceInfo.Common.Vid == vendorid1 || deviceInfo.Common.Vid == vendorid2) && // (deviceInfo.Common.Pid == productid1 || deviceInfo.Common.Pid == productid2 || deviceInfo.Common.Pid == productid3 || deviceInfo.Common.Pid == productid4) && // deviceInfo.DeviceInterfaceGUID.ToUpper() == "{D49AB938-53BA-498A-A848-8E2780A4A75F}" (deviceInfo.DeviceInterfaceGUID.ToUpper() == "{D49AB938-53BA-498A-A848-8E2780A4A75F}") && ( ( (deviceInfo.Common.Vid == vendorid1 || deviceInfo.Common.Vid == vendorid2) && (deviceInfo.Common.Pid == productid1 || deviceInfo.Common.Pid == productid2 || deviceInfo.Common.Pid == productid3 || deviceInfo.Common.Pid == productid4) ) || ( (deviceInfo.Common.Vid == audio_vendor_id) && ( (deviceInfo.Common.Pid == audio_product_id_1) || (deviceInfo.Common.Pid == audio_product_id_2) || (deviceInfo.Common.Pid == audio_product_id_3) || (deviceInfo.Common.Pid == audio_product_id_4) || (deviceInfo.Common.Pid == audio_product_id_5) || (deviceInfo.Common.Pid == audio_product_id_6) || (deviceInfo.Common.Pid == audio_product_id_7) || (deviceInfo.Common.Pid == audio_product_id_8) || (deviceInfo.Common.Pid == audio_product_id_9) || (deviceInfo.Common.Pid == audio_product_id_10) || (deviceInfo.Common.Pid == audio_product_id_11) || (deviceInfo.Common.Pid == audio_product_id_12) ) ) ) ) { if (deviceInfo.Connected) { success = true; break; } } } if (!success) { DeviceInfo.Text += String.Format("Audio-Widget device not found!\r\n"); if (deviceList != null) { deviceList.Free(); } deviceList = null; return(false); } usb = new UsbK(deviceInfo); DeviceInfo.Text += String.Format("Opening usb device OK\r\n"); usb.GetDescriptor((byte)USB_DESCRIPTOR_TYPE.DEVICE, 0, 0, globalBuffer, globalBufferLength, out LengthTransferred); USB_DEVICE_DESCRIPTOR deviceDescriptor = ByteToDeviceDescriptor(globalBuffer); usb.GetDescriptor((byte)USB_DESCRIPTOR_TYPE.CONFIGURATION, 0, 0, globalBuffer, globalBufferLength, out LengthTransferred); USB_CONFIGURATION_DESCRIPTOR configurationDescriptor = ByteToConfigDescriptor(globalBuffer); string product = GetStringDescriptor(deviceDescriptor.iProduct); string manufacturer = GetStringDescriptor(deviceDescriptor.iManufacturer); string serial = GetStringDescriptor(deviceDescriptor.iSerialNumber); DeviceInfo.Text += String.Format("Device: VID=0x{0:X04}/PID=0x{1:X04}\r\n", deviceDescriptor.idVendor, deviceDescriptor.idProduct); DeviceInfo.Text += String.Format("Product: {0}\r\n", product); DeviceInfo.Text += String.Format("Manufacturer: {0}\r\n", manufacturer); DeviceInfo.Text += String.Format("Serial number: {0}\r\n", serial); success = SendUsbControl(interfaceNumber, (byte)BMREQUEST_DIR.DEVICE_TO_HOST, (byte)BMREQUEST_TYPE.VENDOR, (byte)BMREQUEST_RECIPIENT.DEVICE, 0x71, 4, 1, globalBuffer, globalBufferLength, out LengthTransferred); ushort max_feature_value_index = globalBuffer[0]; ushort feature_index = 0; ComboBox control = null; for (ushort i = 0; i < max_feature_value_index; i++) { success = SendUsbControl(interfaceNumber, (byte)BMREQUEST_DIR.DEVICE_TO_HOST, (byte)BMREQUEST_TYPE.VENDOR, (byte)BMREQUEST_RECIPIENT.DEVICE, 0x71, 8, i, globalBuffer, globalBufferLength, out LengthTransferred); if (globalBuffer[0] == 63) { break; } string output_str = ""; for (int s = (int)LengthTransferred - 1; s >= 0; s--) { output_str += (char)globalBuffer[s]; } if (output_str == "end") { feature_index++; control = null; } else { if (control == null) { control = FindFeatureControl(feature_index); } if (control != null) { control.Items.Add(output_str); feature_value_dict[(int)i] = output_str; feature_value_lookup_dict[feature_index.ToString() + output_str] = (int)i; } } if (i > 100) { break; } } foreach (Control ctrl in this.Controls) { if (ctrl is ComboBox) { int index = Convert.ToInt32(ctrl.Tag); ComboBox box = (ComboBox)ctrl; success = SendUsbControl(interfaceNumber, (byte)BMREQUEST_DIR.DEVICE_TO_HOST, (byte)BMREQUEST_TYPE.VENDOR, (byte)BMREQUEST_RECIPIENT.DEVICE, 0x71, 4, (byte)(2 + index), globalBuffer, globalBufferLength, out LengthTransferred); int feature_value_index = (int)globalBuffer[0]; if (feature_value_dict.ContainsKey(feature_value_index)) { string text = feature_value_dict[feature_value_index].ToString(); box.SelectedIndex = box.Items.IndexOf(text); } } } return(true); }
public STDfuDevice(string devicePath) { if (STDFU_Open(devicePath, out _handle) != STDFU_NOERROR) { throw new Exception(); // exception: could not open connection to device } try { // retrieve our device descriptor (to retrieve STDFU version) USB_DEVICE_DESCRIPTOR usbDeviceDescriptor = new USB_DEVICE_DESCRIPTOR(); if (STDFU_GetDeviceDescriptor(ref _handle, ref usbDeviceDescriptor) != STDFU_NOERROR) { throw new Exception(); // exception: could not retrieve device descriptor } // retrieve our DFU functional desscriptor uint dfuInterfaceNum = 0; uint nbOfAlternates = 0; DFU_FUNCTIONAL_DESCRIPTOR dfuFunctionalDescriptor = new DFU_FUNCTIONAL_DESCRIPTOR(); if (STDFU_GetDFUDescriptor_Proxy(ref _handle, ref dfuInterfaceNum, ref nbOfAlternates, ref dfuFunctionalDescriptor) != STDFU_NOERROR) { //if (STDFU_GetDFUDescriptor(ref _handle, ref dfuInterfaceNum, ref nbOfAlternates, ref dfuFunctionalDescriptor) != STDFU_NOERROR) throw new Exception(); // exception: could not retrieve DFU descriptor } // retrieve our block transfer size (# of bytes per block in upload/download requests) _blockTransferSize = dfuFunctionalDescriptor.wTransferSize; // verify that our DFU protocol version is valid. if (dfuFunctionalDescriptor.bcdDFUVersion < 0x011A || dfuFunctionalDescriptor.bcdDFUVersion > 0x0120) { throw new Exception(); // unknown DFU protocol version } // retrieve our attributes (supported operations, etc.) if ((dfuFunctionalDescriptor.bmAttributes & ATTR_DNLOAD_CAPABLE) > 0) { _isDownloadCapable = true; } if ((dfuFunctionalDescriptor.bmAttributes & ATTR_UPLOAD_CAPABLE) > 0) { _isUploadCapable = true; } if ((dfuFunctionalDescriptor.bmAttributes & ATTR_WILL_DETACH) > 0) { _isWillDetach = true; } if ((dfuFunctionalDescriptor.bmAttributes & ATTR_MANIFESTATION_TOLERANT) > 0) { _isManifestationTolerant = true; } if ((dfuFunctionalDescriptor.bmAttributes & ATTR_ST_CAN_ACCELERATE) > 0) { _isStCanAccelerate = true; } byte[] commands = new byte[4]; if (GetDownloadCommands(out commands) == true && commands.Length >= 4) { // we were able to load the command bytes for DOWNLOAD functions; set them now. _downloadCommandSetAddressPointer = commands[1]; _downloadCommandErase = commands[2]; _downloadCommandReadUnprotect = commands[3]; } else { // use defaults } } catch { STDFU_Close(ref _handle); } }
public static extern bool WinUsb_GetDescriptor(IntPtr InterfaceHandle, byte DescriptorType, byte Index, UInt16 LanguageID, out USB_DEVICE_DESCRIPTOR deviceDesc, UInt32 BufferLength, out UInt32 LengthTransfered);
public static extern bool WinUsb_GetDescriptor( IntPtr InterfaceHandle, byte DescriptorType, byte Index, short LanguageID, ref USB_DEVICE_DESCRIPTOR Buffer, int BufferLength, out int LengthTransferred );
static extern uint STDFU_GetDeviceDescriptor( ref IntPtr phDevice, ref USB_DEVICE_DESCRIPTOR pDesc );
public static extern Boolean Uusbd_GetDeviceDescriptor(Int16 husb, USB_DEVICE_DESCRIPTOR descriptor);
private qusbListInfo CreateQLVI(QuickUsb qusb, string devName, out bool alreadyAdded) { // The name is only passed in when it can't be extract from the info parameter (probably bc the module is not connected) if (qusb == null) { alreadyAdded = false; return(null); } if (qusb.Name == null) { if (devName == null) { throw new Exception("Unable to create item from QuickUSB - Too little information"); } } else { if (devName != null && devName != qusb.Name) { throw new Exception("Unable to create item from QuickUSB - Conflicting module information"); } devName = qusb.Name; } // First, see if this module has already been added string[] arr; arr = new string[QuickUsbDict.Count]; QuickUsbDict.Keys.CopyTo(arr, 0); for (int k = 0; k < arr.Length; ++k) { if (QuickUsbDict[arr[k]].qusb.Name == devName) { alreadyAdded = true; return(QuickUsbDict[arr[k]]); } } // Create a new qusbListInfo item var listInfo = new qusbListInfo(); listInfo.qusb = qusb; listInfo.attached = false; // Variables string newSerial; newSerial = listInfo.qusb.Serial; Version v; listInfo.lvi = new ListViewItem(new string[columnData.Count], 0, ModuleGroup); // Read device descriptor USB_DEVICE_DESCRIPTOR desc = new USB_DEVICE_DESCRIPTOR(); IntPtr hDevice; int result; result = QuickUsbOpenUtil(out hDevice, listInfo.qusb.Name); if (result != 0) { try { result = QuickUsbGetDeviceDesc(listInfo.qusb.Handle, ref desc, 18); } catch { // User is using an older DLL, so we won't be able to read descriptor information } result = QuickUsbCloseUtil(hDevice); } // Add data to columns for (int k = 0; k < columnData.Count; ++k) { switch (columnData[k].type) { case ColumnDataType.Name: listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, listInfo.qusb.Name); break; case ColumnDataType.Make: if (showUnprogrammedDevices && listInfo.qusb.Make == null && desc.idVendor == 0x04b4 && desc.idProduct == 0x8613) { listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, "Bitwise Systems"); } else { listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, listInfo.qusb.Make); } break; case ColumnDataType.Model: if (showUnprogrammedDevices && listInfo.qusb.Make == null) { listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, "Unprogrammed"); } else { listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, listInfo.qusb.Model); } break; case ColumnDataType.Serial: listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, listInfo.qusb.Serial); break; case ColumnDataType.PrivateModel: listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, qusb.GetStringDescriptor((QuickUsb.StringDescriptor) 4)); break; case ColumnDataType.IOModel: string ioModel = qusb.GetStringDescriptor((QuickUsb.StringDescriptor) 4); // The IO Model is in parenthesis in the private model string. If there are no parentheses, then it's the simple IO model if (ioModel != null) { int start = ioModel.IndexOf('('); int end = ioModel.IndexOf(')'); if (start == -1 || end == -1) { ioModel = "Simple I/O"; } else { ioModel = ioModel.Substring(start + 1, (end - start - 1)); } listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, ioModel); } break; case ColumnDataType.PrivateSerial: listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, qusb.GetStringDescriptor((QuickUsb.StringDescriptor) 5)); break; case ColumnDataType.PrivateMake: listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, qusb.GetStringDescriptor((QuickUsb.StringDescriptor) 6)); break; case ColumnDataType.FirmwareVersion: // Make sure that device contains firmware before trying to communicate with it if (listInfo.qusb.Make != null) { listInfo.qusb.GetFirmwareVersion(out v); if (v != null) { listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, String.Format("{0}.{1}.{2}", v.Major, v.Minor, v.Build)); } } break; case ColumnDataType.DriverVersion: QuickUsb.GetDriverVersion(out v); if (v != null) { listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, String.Format("{0}.{1}.{2}", v.Major, v.Minor, v.Build)); } break; case ColumnDataType.LibraryVersion: QuickUsb.GetDllVersion(out v); if (v != null) { listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, String.Format("{0}.{1}.{2}", v.Major, v.Minor, v.Build)); } break; case ColumnDataType.VID: listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, "0x" + desc.idVendor.ToString("X4")); break; case ColumnDataType.PID: listInfo.lvi.SubItems[k] = new ListViewItem.ListViewSubItem(listInfo.lvi, "0x" + desc.idProduct.ToString("X4")); break; } } listInfo.visible = true; listInfo.lvi.Name = listInfo.qusb.Make; listInfo.lvi.ToolTipText = "Name: " + devName + Environment.NewLine + "Serial: " + newSerial + Environment.NewLine; listInfo.lvi.Tag = listInfo.qusb; // NOTE: Tag of LVI contains QuickUSB object (Very convenient) listInfo.lvi.ImageIndex = 1; // Default to unattached icon alreadyAdded = false; return(listInfo); }
internal static extern int QuickUsbGetDeviceDesc(IntPtr hDevice, ref USB_DEVICE_DESCRIPTOR data, uint length);
/// <summary> /// Returns the vendor and product id of the device. /// </summary> /// /// <returns> /// True if device descriptor was returned. /// </returns> internal Boolean GetUsbDeviceDescriptor() { UInt32 transfered = 0, size; Boolean success; usbDevDescriptor = default(USB_DEVICE_DESCRIPTOR); size = Convert.ToUInt32(Marshal.SizeOf(usbDevDescriptor)); success = WinUsb_GetDescriptor(devInfo.winUsbHandle, USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, ref usbDevDescriptor, size, ref transfered); return ((transfered == size) && (success)); }