private static void FindMyDevice() { var devicePathName = ""; if (!(DeviceDetected)) { // This GUID must match the GUID in the device's INF file. // Convert the device interface GUID String to a GUID object: if (_deviceManager.FindDeviceFromGuid(WinUsbDemoGuid, ref devicePathName)) { var success = _usbDevice.GetDeviceHandle(devicePathName); if (success) { DeviceDetected = true; // Save DevicePathName so OnDeviceChange() knows which name is my device. _devicePathName = devicePathName; } else { // There was a problem in retrieving the information. DeviceDetected = false; _usbDevice.CloseDeviceHandle(); } } if (DeviceDetected) { _usbDevice.InitializeDevice(); } } }
/// <summary> /// Taken from Jan Axelson's USB Bulk Transfer implementation. /// Finds the device if it exists, retrieves the handle to it. Subscribes the main /// form to receive notifications from /// the device. This function should only be called from the main code until the deivice is initially /// </summary> /// <returns></returns> public bool FindMyDevice() { Boolean deviceFound = false; String devPathName = ""; Boolean success = false; isDeviceDetected = false; try { if (!(isDeviceDetected)) { // Convert the device interface GUID String to a GUID object: System.Guid winusb_device_guid = new System.Guid(deviceGUID); // Fill an array with the device path names of all attached devices with matching GUIDs. deviceFound = deviceManager.FindDeviceFromGuid (winusb_device_guid, ref devPathName); if (deviceFound == true) { success = device.GetDeviceHandle(devPathName); if (success) { isDeviceDetected = true; // Save DevicePathName so OnDeviceChange() knows which name is my device. devicePathName = devPathName; } else { // There was a problem in retrieving the information. isDeviceDetected = false; device.CloseDeviceHandle(); } } if (isDeviceDetected) { // The device was detected. // Register to receive notifications if the device is removed or attached. if (deviceNotificationHandle == IntPtr.Zero) { success = deviceManager.RegisterForDeviceNotifications (devicePathName, formReference.Handle, winusb_device_guid, ref deviceNotificationHandle); } if (success) { device.InitializeDevice(); } } } return(isDeviceDetected); } catch (Exception ex) { throw ex; } }
/// <summary> /// Uses a series of API calls to locate a HID-class device /// by its Vendor ID and Product ID. /// </summary> /// <returns>True if the device is detected, False if not detected.</returns> private bool FindTheHid() { string[] DevicePathName = new string[128]; FileIOApiDeclarations.SECURITY_ATTRIBUTES Security = new FileIOApiDeclarations.SECURITY_ATTRIBUTES(); try { if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: Searching for display with VendorID:{0:X} & ProductID:{1:X}", _VendorID, _ProductID); } Guid HidGuid = Guid.Empty; _MyDeviceDetected = false; // Values for the SECURITY_ATTRIBUTES structure: Security.lpSecurityDescriptor = 0; Security.bInheritHandle = Convert.ToInt32(true); Security.nLength = Marshal.SizeOf(Security); /* * API function: 'HidD_GetHidGuid * Purpose: Retrieves the interface class GUID for the HID class. * Accepts: 'A System.Guid object for storing the GUID. */ HidApiDeclarations.HidD_GetHidGuid(ref HidGuid); if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("GetHidGuid")); } // Display the GUID. string GUIDString = HidGuid.ToString(); if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: GUID for system HIDs: " + GUIDString); } // Fill an array with the device path names of all attached HIDs. bool DeviceFound = DeviceManagement.FindDeviceFromGuid(HidGuid, ref DevicePathName); // If there is at least one HID, attempt to read the Vendor ID and Product ID // of each device until there is a match or all devices have been examined. if (DeviceFound) { int MemberIndex = 0; do { // *** // API function: // CreateFile // Purpose: // Retrieves a handle to a device. // Accepts: // A device path name returned by SetupDiGetDeviceInterfaceDetail // The type of access requested (read/write). // FILE_SHARE attributes to allow other processes to access the device while this handle is open. // A Security structure. Using Null for this may cause problems under Windows XP. // A creation disposition value. Use OPEN_EXISTING for devices. // Flags and attributes for files. Not used for devices. // Handle to a template file. Not used. // Returns: a handle that enables reading and writing to the device. // *** _HIDHandle = FileIOApiDeclarations.CreateFile (DevicePathName[MemberIndex], FileIOApiDeclarations.GENERIC_READ | FileIOApiDeclarations.GENERIC_WRITE, FileIOApiDeclarations.FILE_SHARE_READ | FileIOApiDeclarations.FILE_SHARE_WRITE, ref Security, FileIOApiDeclarations.OPEN_EXISTING, 0, 0); if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("CreateFile")); } if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: Returned handle: " + _HIDHandle.ToString("x") + "h"); } if (_HIDHandle != FileIOApiDeclarations.INVALID_HANDLE_VALUE) { // The returned handle is valid, // so find out if this is the device we're looking for. // Set the Size property of DeviceAttributes to the number of bytes in the structure. _MyHID.DeviceAttributes.Size = Marshal.SizeOf(_MyHID.DeviceAttributes); // *** // API function: // HidD_GetAttributes // Purpose: // Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, // Product ID, and Product Version Number for a device. // Accepts: // A handle returned by CreateFile. // A pointer to receive a HIDD_ATTRIBUTES structure. // Returns: // True on success, False on failure. // *** int Result = HidApiDeclarations.HidD_GetAttributes(_HIDHandle, ref _MyHID.DeviceAttributes); if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("HidD_GetAttributes")); } if (Result != 0) { if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: HIDD_ATTRIBUTES structure filled without error."); } if (Settings.Instance.ExtensiveLogging) { Log.Debug( "MiniDisplay.VFD_Control: Vendor ID: {0:X}, Product ID: {1:X}, Version {2:X}" + _MyHID.DeviceAttributes.VendorID, _MyHID.DeviceAttributes.ProductID, _MyHID.DeviceAttributes.VersionNumber); } // Find out if the device matches the one we're looking for. if ((_MyHID.DeviceAttributes.VendorID == _VendorID) & (_MyHID.DeviceAttributes.ProductID == _ProductID)) { // It's the desired device. if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: My device detected"); } _MyDeviceDetected = true; // Save the DevicePathName so OnDeviceChange() knows which name is my device. } else { // It's not a match, so close the handle. _MyDeviceDetected = false; FileIOApiDeclarations.CloseHandle(_HIDHandle); if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("CloseHandle")); } } } else { // There was a problem in retrieving the information. if (Settings.Instance.ExtensiveLogging) { Log.Debug("MiniDisplay.VFD_Control: Error in filling HIDD_ATTRIBUTES structure."); } _MyDeviceDetected = false; FileIOApiDeclarations.CloseHandle(_HIDHandle); } } // Keep looking until we find the device or there are no more left to examine. MemberIndex = MemberIndex + 1; } while (!(_MyDeviceDetected || (MemberIndex == DevicePathName.Length) || DevicePathName[MemberIndex] == null)); } if (_MyDeviceDetected) { // The device was detected. // Learn the capabilities of the device. _MyHID.Capabilities = _MyHID.GetDeviceCapabilities(_HIDHandle); } } catch (Exception ex) { Log.Error(ex); //HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex); } return(_MyDeviceDetected); }
/// <summary> /// Find the Nintendo USB controller. Also save HID capabilities for device for later. /// </summary> /// <returns></returns> public bool FindController() { bool deviceFound = false; Guid hidGuid = Guid.Empty; String[] devicePathName = new String[255]; Int32 memberIndex = 0; bool success = false; try { myDeviceDetected = false; CloseCommunications(); // Get the Guid associated with USB HID class. Hid.HidD_GetHidGuid(ref hidGuid); Debug.WriteLineIf(WRITE_DEBUG_INFO, MyDebugging.ResultOfAPICall("Hid.HidD_GetHidGuid")); // Get all attached HIDs. I am assuming there are a maximum of 128. deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName); if (deviceFound) { memberIndex = 0; // Loop through all USB HIDs found and look for my VID/PID. do { // Open HID handle without read nor write access to get info. hidHandle = FileIO.CreateFile( devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); Debug.WriteLineIf(WRITE_DEBUG_INFO, MyDebugging.ResultOfAPICall("FileIO.CreateFile")); if (!hidHandle.IsInvalid) { // Get DeviceAttribute size in bytes. MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes); // Get HID attributes. success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes); if (success) { if (MyHid.DeviceAttributes.VendorID == USB_NINTENDO_VID && MyHid.DeviceAttributes.ProductID == USB_NINTENDO_PID) { myDeviceDetected = true; myDevicePathName = devicePathName[memberIndex]; } else { // Not a match - close handle. hidHandle.Close(); } } else { // There was a problem trying to retrieve the HID info. Debug.WriteLineIf(WRITE_DEBUG_INFO, "Error trying to get HID attributes in " + "UsbSingleNintendoController.FindController() when calling " + "Hid.HidD_GetAttributes(...)"); hidHandle.Close(); } } // Prepare to go to next index. memberIndex++; }while (!((myDeviceDetected || (memberIndex == devicePathName.Length)))); } // If device found, wire it up to this class. if (myDeviceDetected) { // Only allow a very few number of input reports to be queued. MyHid.SetNumberOfInputBuffers(hidHandle, USB_NUMBER_INPUT_REPORT_BUFFERS); Debug.WriteLineIf(WRITE_DEBUG_INFO, MyDebugging.ResultOfAPICall("MyHid.SetNumberOfInputBuffers")); // Register for notification if HID removed or attached. success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, this.Handle, hidGuid, ref deviceNotificationHandle); Debug.WriteLineIf(WRITE_DEBUG_INFO && !success, "Failed at: MyDeviceManagement.RegisterForDeviceNotifications"); // Get capabilities report for report sizes. MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle); Debug.WriteLineIf(WRITE_DEBUG_INFO, MyDebugging.ResultOfAPICall("MyHid.GetDeviceCapabilities")); if (success) { // Close handle then reopen in RW mode. hidHandle.Close(); hidHandle = FileIO.CreateFile( myDevicePathName, FileIO.GENERIC_READ | FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); #pragma warning disable Debug.WriteLineIf(WRITE_DEBUG_INFO && hidHandle.IsInvalid, "File handle invalid at: FileIO.CreateFile(read/write)"); #pragma warning restore Debug.WriteLineIf(WRITE_DEBUG_INFO, MyDebugging.ResultOfAPICall("FileIO.CreateFile(read/write)")); if (MyHid.Capabilities.InputReportByteLength > 0) { fileStreamDeviceData = new FileStream( hidHandle, FileAccess.ReadWrite, MyHid.Capabilities.InputReportByteLength, false); } MyHid.FlushQueue(hidHandle); } } } catch (Exception ex) { Debug.WriteLineIf(WRITE_DEBUG_INFO, ex.Message); deviceFound = false; } return(deviceFound); }
private static Boolean FindBootloader_WIN() { Boolean deviceFound; String devicePathName = ""; Boolean success; try { if (!(HID.BootloaderDetected)) { // Convert the device interface GUID String to a GUID object: System.Guid winUsbDemoGuid = new System.Guid(variables.BOOTLOADER_GUID_STRING); // Fill an array with the device path names of all attached devices with matching GUIDs. deviceFound = BootloaderManagement.FindDeviceFromGuid (winUsbDemoGuid, ref devicePathName); if (variables.debugme) { Console.WriteLine("DemoN - {0}", devicePathName); } if (deviceFound == true) { success = Bootloader.GetDeviceHandle(devicePathName); if (success) { if (variables.debugme) { Console.WriteLine("Bootloader attached -85"); } HID.BootloaderDetected = true; // Save DevicePathName so OnDeviceChange() knows which name is my device. BootloaderPathName = devicePathName; } else { // There was a problem in retrieving the information. HID.BootloaderDetected = false; Bootloader.CloseDeviceHandle(); } } if (HID.BootloaderDetected) { // The device was detected. // Register to receive notifications if the device is removed or attached. if (variables.debugme) { Console.WriteLine("Bootloader attached.-106"); } success = BootloaderManagement.RegisterForDeviceNotifications (BootloaderPathName, MainForm.frmMy.Handle, winUsbDemoGuid, ref BootloaderNotificationHandle); if (success) { if (Bootloader.InitializeDevice()) { if (variables.debugme) { Console.WriteLine("Bootloader attached.-117"); } } else { if (variables.debugme) { Console.WriteLine("failed 121"); } } } else { if (variables.debugme) { Console.WriteLine("failed 126"); } } } else { if (variables.debugme) { Console.WriteLine("Bootloader not found."); } } } else { if (variables.debugme) { Console.WriteLine("Bootloader attached.-128"); } } return(HID.BootloaderDetected); } catch (Exception ex) { if (variables.debugme) { Console.WriteLine(ex.ToString()); } return(false); } }
/// <summary> /// Uses a series of API calls to locate a HID-class device /// by its Vendor ID and Product ID. /// Fills myDevicePathName with a path to device found, readHandle and writeHandle. Registers for Device Notifications (attached / detached type of events). /// </summary> /// /// <returns> /// True if the device is detected, False if not detected. /// </returns> private Boolean FindTheHid(Int32 myVendorID, Int32 myProductID) { Boolean someHidDevicesFound = false; String[] devicePathName = new String[128]; String functionName = ""; Guid hidGuid = Guid.Empty; Int32 memberIndex = 0; Boolean success = false; try { myDeviceDetected = false; Tracer.Trace(string.Format("FindTheHid(0x{0:X04}, 0x{1:X04})", myVendorID, myProductID)); // *** // API function: 'HidD_GetHidGuid // Purpose: Retrieves the interface class GUID for the HID class. // Accepts: 'A System.Guid object for storing the GUID. // *** Hid.HidD_GetHidGuid(ref hidGuid); functionName = "GetHidGuid"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" GUID for system HIDs: " + hidGuid.ToString()); // Fill an array with the device path names of all attached HIDs. someHidDevicesFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName); // If there is at least one HID, attempt to read the Vendor ID and Product ID // of each device until there is a match or all devices have been examined. // // Fill myDevicePathName with a path to device found. if (someHidDevicesFound) { memberIndex = 0; // Tracer.Trace(" total number of HID devices: " + devicePathName.Length); // will be something like 128, a lot of empty paths there. do { // *** // API function: // CreateFile // Purpose: // Retrieves a handle to a device. // Accepts: // A device path name returned by SetupDiGetDeviceInterfaceDetail // The type of access requested (read/write). // FILE_SHARE attributes to allow other processes to access the device while this handle is open. // A Security structure or IntPtr.Zero. // A creation disposition value. Use OPEN_EXISTING for devices. // Flags and attributes for files. Not used for devices. // Handle to a template file. Not used. // Returns: a handle without read or write access. // This enables obtaining information about all HIDs, even system // keyboards and mice. // Separate handles are used for reading and writing. // *** if (!string.IsNullOrEmpty(devicePathName[memberIndex])) { Tracer.Trace(" trying HID device path '" + devicePathName[memberIndex] + "'"); hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); functionName = "CreateFile"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" FindTheHid(): some HID device found, returned handle: " + hidHandle.ToString()); if (!hidHandle.IsInvalid) { // The returned handle is valid, // so find out if this is the device we're looking for. // Set the Size property of DeviceAttributes to the number of bytes in the structure. MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes); // *** // API function: // HidD_GetAttributes // Purpose: // Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, // Product ID, and Product Version Number for a device. // Accepts: // A handle returned by CreateFile. // A pointer to receive a HIDD_ATTRIBUTES structure. // Returns: // True on success, False on failure. // *** success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes); if (success) { Tracer.Trace(" HIDD_ATTRIBUTES structure filled without error."); Tracer.Trace(" Structure size: " + MyHid.DeviceAttributes.Size); Tracer.Trace(string.Format(" Vendor ID: 0x{0:X04}", MyHid.DeviceAttributes.VendorID)); Tracer.Trace(string.Format(" Product ID: 0x{0:X04}", MyHid.DeviceAttributes.ProductID)); Tracer.Trace(string.Format(" Version Number: 0x{0:X04}", MyHid.DeviceAttributes.VersionNumber)); // Find out if the device matches the one we're looking for. if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID)) { Tracer.Trace(" My device detected"); myDeviceDetected = true; // Save the DevicePathName for OnDeviceChange(). myDevicePathName = devicePathName[memberIndex]; } else { // It's not a match, so close the handle. Tracer.Trace(" (This is not My Device)"); myDeviceDetected = false; hidHandle.Close(); } } else { // There was a problem in retrieving the information. Tracer.Trace(" Error in filling HIDD_ATTRIBUTES structure."); myDeviceDetected = false; hidHandle.Close(); } } } // Keep looking until we find the device or there are no devices left to examine. memberIndex = memberIndex + 1; }while (!((myDeviceDetected || (memberIndex == devicePathName.Length)))); } if (myDeviceDetected) { // The device was detected. // Register to receive notifications if the device is removed or attached. success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, WindowHandle, hidGuid, ref deviceNotificationHandle); Tracer.Trace("RegisterForDeviceNotifications = " + success); // Learn the capabilities of the device. MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle); if (success) { // Find out if the device is a system mouse or keyboard. hidUsage = MyHid.GetHidUsage(MyHid.Capabilities); // Get the Input report buffer size. GetInputReportBufferSize(); // Get handles to use in requesting Input and Output reports. readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0); functionName = "CreateFile, ReadHandle"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" FindTheHid(): success, returned handle: " + readHandle.ToString()); if (readHandle.IsInvalid) { exclusiveAccess = true; Tracer.Error("The device is a system " + hidUsage + ". Applications can access Feature reports only."); } else { writeHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); functionName = "CreateFile, WriteHandle"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" FindTheHid(): handle valid, returned handle: " + writeHandle.ToString()); // Flush any waiting reports in the input buffer. (optional) MyHid.FlushQueue(readHandle); } } } else { // The device wasn't detected. Tracer.Error(string.Format("My Device not found - need a HID with vendorId={0}, productId={1}.", vendorId, productId)); } return(myDeviceDetected); } catch (Exception ex) { Tracer.Error(ex); throw; } }
/// <summary> /// Call HID functions that use Win32 API functions to locate a HID-class device /// by its Vendor ID and Product ID. Open a handle to the device. /// </summary> /// /// <returns> /// True if the device is detected, False if not detected. /// </returns> private Boolean FindTheHid() { var devicePathName = new String[128]; String myDevicePathName = ""; try { _deviceHandleObtained = false; CloseCommunications(); _myVendorId = 0x16c0; _myProductId = 0x05df; // Get the HID-class GUID. Guid hidGuid = _myHid.GetHidGuid(); // Fill an array with the device path names of all attached HIDs. Boolean availableHids = _myDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName); // If there is at least one HID, attempt to read the Vendor ID and Product ID // of each device until there is a match or all devices have been examined. if (availableHids) { Int32 memberIndex = 0; do { // Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice. _hidHandle = _myHid.OpenHandle(devicePathName[memberIndex], false); if (!_hidHandle.IsInvalid) { // The returned handle is valid, // so find out if this is the device we're looking for. //_myHid.DeviceAttributes.Size = Marshal.SizeOf(_myHid.DeviceAttributes); Boolean success = _myHid.GetAttributes(_hidHandle, ref _myHid.DeviceAttributes); if (success) { //Debug.WriteLine(" HIDD_ATTRIBUTES structure filled without error."); //Debug.WriteLine(" Structure size: " + _myHid.DeviceAttributes.Size); //Debug.WriteLine(" Vendor ID: " + Convert.ToString(_myHid.DeviceAttributes.VendorID, 16)); //Debug.WriteLine(" Product ID: " + Convert.ToString(_myHid.DeviceAttributes.ProductID, 16)); //Debug.WriteLine(" Version Number: " + Convert.ToString(_myHid.DeviceAttributes.VersionNumber, 16)); if ((_myHid.DeviceAttributes.VendorID == _myVendorId) && (_myHid.DeviceAttributes.ProductID == _myProductId)) { //Debug.WriteLine(" Handle obtained to my device"); // Display the information in form's list box. //InfoBox.Text += "\nHandle obtained to my device:"; InfoBox.Text = " VID=" + Convert.ToString(_myHid.DeviceAttributes.VendorID, 16); InfoBox.Text += " PID=" + Convert.ToString(_myHid.DeviceAttributes.ProductID, 16); _deviceHandleObtained = true; myDevicePathName = devicePathName[memberIndex]; } else { // It's not a match, so close the handle. _deviceHandleObtained = false; _hidHandle.Close(); } } else { // There was a problem retrieving the information. //Debug.WriteLine(" Error in filling HIDD_ATTRIBUTES structure."); _deviceHandleObtained = false; _hidHandle.Close(); } } // Keep looking until we find the device or there are no devices left to examine. memberIndex = memberIndex + 1; }while (!((_deviceHandleObtained || (memberIndex == devicePathName.Length)))); } if (_deviceHandleObtained) { // The device was detected. // Learn the capabilities of the device. _myHid.Capabilities = _myHid.GetDeviceCapabilities(_hidHandle); // Find out if the device is a system mouse or keyboard. _hidUsage = _myHid.GetHidUsage(_myHid.Capabilities); //Close the handle and reopen it with read/write access. _hidHandle.Close(); _hidHandle = _myHid.OpenHandle(myDevicePathName, true); if (_hidHandle.IsInvalid) { InfoBox.Text += "The device is a system " + _hidUsage + "."; } else { if (_myHid.Capabilities.InputReportByteLength > 0) { // Set the size of the Input report buffer. var inputReportBuffer = new Byte[_myHid.Capabilities.InputReportByteLength]; _deviceData = new FileStream(_hidHandle, FileAccess.Read | FileAccess.Write, inputReportBuffer.Length, false); inputReportBuf = new Byte[_myHid.Capabilities.InputReportByteLength]; } if (_myHid.Capabilities.OutputReportByteLength > 0) { Byte[] outputReportBuffer = null; } // Flush any waiting reports in the input buffer. (optional) _myHid.FlushQueue(_hidHandle); } ErrorBox.Text = ""; } else { ErrorBox.Text = "Device not found."; } return(_deviceHandleObtained); } catch (Exception ex) { DisplayException(Name, ex); throw; } }
public void connect(UInt16 vid, UInt16 pid, bool skip) { if (connected) { Log.Write(String.Format("USBInterface.connect() for already connected interface - vid{0}, pid={1}, skip={2}) begins\n", vid, pid, skip)); } else { System.Guid Guid = new System.Guid(GUID_STRING); Int32 index = 0; Log.Write(String.Format("USBInterface.connect() begins vid{0}, pid={1}, skip={2}) begins\n", vid, pid, skip)); while (true) { bool bUseThisDevice = true; if (!myDeviceManagement.FindDeviceFromGuid(Guid, out devicePathName, ref index)) { throw new System.IO.IOException(String.Format("Unable to locate a USB device with GUID {0}, vid={1}, pid={2}, skip={3}", Guid, vid, pid, skip)); } Log.Write(String.Format("USBInterface.connect(): Considering USB Device {0}\n", devicePathName)); UInt16 foundVid, foundPid; DeviceManagement.parsePath(devicePathName, out foundVid, out foundPid); Log.Write(String.Format("USBInterface.connect(): checking VID/PID - foundVID={0} foundPID={1}\n", foundVid, foundPid)); if (vid != 0) { bool bVIDMatch = (foundVid == vid); bool bPIDMatch = (foundPid == pid); Log.Write(String.Format("USBInterface.connect(): initally bVIDMatch={0} bPIDMatch={1}\n", bVIDMatch, bPIDMatch)); // a pid of 0xffff matches guide cameras if (pid == 0xffff) { bPIDMatch = (foundPid == 507) || (foundPid == 509) || (foundPid == 517); } bUseThisDevice = (bVIDMatch && bPIDMatch); Log.Write(String.Format("USBInterface.connect(): pre skip check bVIDMatch={0} bPIDMatch={1} bUseThisDevice={2}\n", bVIDMatch, bPIDMatch, bUseThisDevice)); if (skip) { bUseThisDevice = !bUseThisDevice; } Log.Write(String.Format("USBInterface.connect(): post skip check bVIDMatch={0} bPIDMatch={1} bUseThisDevice={2}\n", bVIDMatch, bPIDMatch, bUseThisDevice)); } if (bUseThisDevice) { // For reasons I don't undersand, we can get a device handle for a device thatis already open, // even though we specify no sharing of the file when we open it. So, in order to make sure // that we don't open the same camera twice we create a mutex that has the same name as // the device (execpt that we have to replace "\" with "/" because // mutex names cannot contain "\"). // If we find that the mutex already existed, we assume the device is already in use and keep looking. String mutexName = devicePathName.Replace("\\", "/"); bool createdNew; m_mutex = new Mutex(true, mutexName, out createdNew); Log.Write(String.Format("USBInterface.connect(): mutexName={0} createdNew={1}\n", mutexName, createdNew)); if (!createdNew) { Log.Write(String.Format("USBInterface.connect(): mutex was already in use - closing handle and continuing search\n")); } else { Log.Write(String.Format("USBInterface: attempting to get a handle for USB Device {0}\n", devicePathName)); if (FileIO.GetDeviceHandle(devicePathName, out deviceHandle)) { Log.Write(String.Format("USBInterface.connect(): deviceHandle.IsInvalid={0}\n", deviceHandle.IsInvalid)); connected = true; vid = foundVid; pid = foundPid; break; } Log.Write(String.Format("USBInterface.connect(): Unable to get a device handle for GUID {0} using path {1} - skipping", Guid, devicePathName)); } m_mutex.Close(); } else { Log.Write(String.Format("USBInterface.connect(): skipping USB Device {0} because of skip/vid/pid\n", devicePathName)); } } } }
/// <summary> /// Uses a series of API calls to locate a HID-class device /// by its Vendor ID and Product ID. /// </summary> /// /// <returns> /// True if the device is detected, False if not detected. /// </returns> public static Boolean FindTheHid( int myVendorID , int myProductID , ref IntPtr FrmMyHandle , ref IntPtr deviceNotificationHandle , ref Boolean exclusiveAccess , ref String hidUsage , ref Boolean myDeviceDetected , ref String myDevicePathName , ref FileStream fileStreamDeviceData , ref SafeFileHandle hidHandle , ref DeviceManagement MyDeviceManagement , ref Hid MyHid , ref string message , ref string txtInputReportBufferSize ) { Boolean deviceFound = false; String[] devicePathName = new String[128]; Guid hidGuid = Guid.Empty; Int32 memberIndex = 0; //Int32 myProductID = 0; //Int32 myVendorID = 0; Boolean success = false; try { myDeviceDetected = false; CloseCommunications( ref myDeviceDetected , ref fileStreamDeviceData , ref hidHandle ); // Get the device's Vendor ID and Product ID //myVendorID = Main.CardReader_VID; //myProductID = Main.CardReader_PID; // *** // API function: 'HidD_GetHidGuid // Purpose: Retrieves the interface class GUID for the HID class. // Accepts: 'A System.Guid object for storing the GUID. // *** Hid.HidD_GetHidGuid(ref hidGuid); // Fill an array with the device path names of all attached HIDs. deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName); // If there is at least one HID, attempt to read the Vendor ID and Product ID // of each device until there is a match or all devices have been examined. if (deviceFound) { memberIndex = 0; do { // *** // API function: // CreateFile // Purpose: // Retrieves a handle to a device. // Accepts: // A device path name returned by SetupDiGetDeviceInterfaceDetail // The type of access requested (read/write). // FILE_SHARE attributes to allow other processes to access the device while this handle is open. // A Security structure or IntPtr.Zero. // A creation disposition value. Use OPEN_EXISTING for devices. // Flags and attributes for files. Not used for devices. // Handle to a template file. Not used. // Returns: a handle without read or write access. // This enables obtaining information about all HIDs, even system // keyboards and mice. // Separate handles are used for reading and writing. // *** // Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice. hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); if (!hidHandle.IsInvalid) { // The returned handle is valid, // so find out if this is the device we're looking for. // Set the Size property of DeviceAttributes to the number of bytes in the structure. MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes); // *** // API function: // HidD_GetAttributes // Purpose: // Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, // Product ID, and Product Version Number for a device. // Accepts: // A handle returned by CreateFile. // A pointer to receive a HIDD_ATTRIBUTES structure. // Returns: // True on success, False on failure. // *** success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes); if (success) { // Find out if the device matches the one we're looking for. if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID)) { // Display the information in form's list box. message = "was found."; myDeviceDetected = true; // Save the DevicePathName for OnDeviceChange(). myDevicePathName = devicePathName[memberIndex]; } else { // It's not a match, so close the handle. myDeviceDetected = false; hidHandle.Close(); } } else { // There was a problem in retrieving the information. //Debug.WriteLine(" Error in filling HIDD_ATTRIBUTES structure."); myDeviceDetected = false; hidHandle.Close(); } } // Keep looking until we find the device or there are no devices left to examine. memberIndex = memberIndex + 1; }while (!((myDeviceDetected || (memberIndex == devicePathName.Length)))); } if (myDeviceDetected) { // The device was detected. // Register to receive notifications if the device is removed or attached. success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, FrmMyHandle, hidGuid, ref deviceNotificationHandle); // Learn the capabilities of the device. MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle); if (success) { // Find out if the device is a system mouse or keyboard. hidUsage = MyHid.GetHidUsage(MyHid.Capabilities); // Get the Input report buffer size. GetInputReportBufferSize( ref exclusiveAccess , ref hidHandle , ref MyHid , ref txtInputReportBufferSize ); //Close the handle and reopen it with read/write access. hidHandle.Close(); hidHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ | FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); if (hidHandle.IsInvalid) { exclusiveAccess = true; } else { if (MyHid.Capabilities.InputReportByteLength > 0) { // Set the size of the Input report buffer. Byte[] inputReportBuffer = null; inputReportBuffer = new Byte[MyHid.Capabilities.InputReportByteLength]; fileStreamDeviceData = new FileStream(hidHandle, FileAccess.Read | FileAccess.Write, inputReportBuffer.Length, false); } if (MyHid.Capabilities.OutputReportByteLength > 0) { Byte[] outputReportBuffer = null; outputReportBuffer = new Byte[MyHid.Capabilities.OutputReportByteLength]; } // Flush any waiting reports in the input buffer. (optional) MyHid.FlushQueue(hidHandle); } } } else { // The device wasn't detected. myDeviceDetected = false; message = "not found."; } return(myDeviceDetected); } catch (Exception ex) { DisplayException("FindTheHid", ex); //throw; } return(false); }
//TODO: Refatorar método public bool Conectado() { if (UpdatedAt == null || (DateTime.Now - UpdatedAt).Seconds > 2) { string[] devicePathName = new string[128]; try { Guid empty = Guid.Empty; MyDeviceDetected = false; FileIOApiDeclarations.SECURITY_ATTRIBUTES lpSecurityAttributes = new FileIOApiDeclarations.SECURITY_ATTRIBUTES(); lpSecurityAttributes.lpSecurityDescriptor = 0; lpSecurityAttributes.bInheritHandle = -1; lpSecurityAttributes.nLength = Strings.Len(lpSecurityAttributes); //short num1 = checked((short)Math.Round(Conversion.Val("&h" + vid))); //short num2 = checked((short)Math.Round(Conversion.Val("&h" + pid))); short num1 = checked ((short)Math.Round(Conversion.Val("&h0483"))); short num2 = checked ((short)Math.Round(Conversion.Val("&h0035"))); HidApiDeclarations.HidD_GetHidGuid(ref empty); empty.ToString(); if (MyDeviceManagement.FindDeviceFromGuid(empty, ref devicePathName)) { int index = 0; do { HIDHandle = FileIOApiDeclarations.CreateFile(devicePathName[index], 0, 3, ref lpSecurityAttributes, 3, 0, 0); if (HIDHandle != -1) { MyHID.DeviceAttributes.Size = Marshal.SizeOf((object)MyHID.DeviceAttributes); bool flag; if (HidApiDeclarations.HidD_GetAttributes(HIDHandle, ref MyHID.DeviceAttributes)) { if ((int)MyHID.DeviceAttributes.VendorId == (int)num1 & (int)MyHID.DeviceAttributes.ProductId == (int)num2) { MyDeviceDetected = true; MyDevicePathName = devicePathName[index]; NobreakInfo.StatusComunicacaoOk = true; } else { MyDeviceDetected = false; flag = FileIOApiDeclarations.CloseHandle(HIDHandle); } } else { MyDeviceDetected = false; flag = FileIOApiDeclarations.CloseHandle(HIDHandle); } } checked { ++index; } }while (!(MyDeviceDetected | index == checked (Information.UBound((Array)devicePathName, 1) + 1))); } lastStatusConectado = MyDeviceDetected; UpdatedAt = DateTime.Now; return(MyDeviceDetected); } catch (Exception ex) { Console.WriteLine("ERRO!!! " + ex.Message); //throw new NobreakNotConnectedException("Não foi possível conectar-se ao Nobreak"); } } return(lastStatusConectado); }
public static bool FindNia(IntPtr Handle) { bool success = false; try { // Get the guid for the system hid class Guid hidGuid = Guid.Empty; GenericHid.Hid.HidD_GetHidGuid(ref hidGuid); // Find all devices of type hid string[] deviceCollection = new String[128]; DeviceManagement deviceManagement = new DeviceManagement(); bool devicesFound = deviceManagement.FindDeviceFromGuid(hidGuid, ref deviceCollection); // Did we find any hid devices ? if (devicesFound) { int memberIndex = 0; do { // try to get a handle on the current hid device in the list hidHandle = GenericHid.FileIO.CreateFile(deviceCollection[memberIndex], 0, GenericHid.FileIO.FILE_SHARE_READ | GenericHid.FileIO.FILE_SHARE_WRITE, null, GenericHid.FileIO.OPEN_EXISTING, 0, 0); if (!hidHandle.IsInvalid) { // Set the Size property of DeviceAttributes to the number of bytes in the structure. MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes); // try to get the hid's information success = GenericHid.Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes); if (success) { if ((MyHid.DeviceAttributes.VendorID == 4660) & (MyHid.DeviceAttributes.ProductID == 0)) { NiaDetected = true; // Save the DevicePathName for OnDeviceChange(). NiaPathName = deviceCollection[memberIndex]; } else { NiaDetected = false; hidHandle.Close(); } } else { NiaDetected = false; hidHandle.Close(); } } // Keep looking until we find the device or there are no devices left to examine. memberIndex = memberIndex + 1; } while (!((NiaDetected | (memberIndex == deviceCollection.Length)))); // Did we find a NIA ? if (NiaDetected) { // The device was detected. // Register to receive notifications if the device is removed or attached. success = deviceManagement.RegisterForDeviceNotifications(NiaPathName, Handle, hidGuid, ref deviceNotificationHandle); if (success) { // Get handles to use in requesting Input and Output reports. readHandle = GenericHid.FileIO.CreateFile(NiaPathName, GenericHid.FileIO.GENERIC_READ, GenericHid.FileIO.FILE_SHARE_READ | GenericHid.FileIO.FILE_SHARE_WRITE, null, GenericHid.FileIO.OPEN_EXISTING, GenericHid.FileIO.FILE_FLAG_OVERLAPPED, 0); if (!readHandle.IsInvalid) { writeHandle = GenericHid.FileIO.CreateFile(NiaPathName, GenericHid.FileIO.GENERIC_WRITE, GenericHid.FileIO.FILE_SHARE_READ | GenericHid.FileIO.FILE_SHARE_WRITE, null, GenericHid.FileIO.OPEN_EXISTING, 0, 0); MyHid.FlushQueue(readHandle); } } } } return(NiaDetected); } catch (Exception ex) { throw ex; } }