USB Application Development

Source: Internet
Author: User

1 PrefaceUSB development is the same as the development of other file devices (such as serial ports). The difficulty is to find the path of the USB device. This article uses the src/USB/bulkusb in DDK as a reference, describe the development process of a non-hid USB debugger software. 2 device guidGenerally, the device has two guids, one of which is the class guid. In the INF file, the other is the device guid, which is in the SYS file. Createfile uses the guid in SYS. There are two ways to get it: 1. Ask for the guid from the device provider. 2. search in the registry, which is generally found in: HKEY_LOCAL_MACHINE/system/controlset001/control/deviceclasses/ 3 device pathEnumerate all USB hosts according to the guid of the device, find the matched USB device, and obtain its path. 3.1 header file USB port. h# Define winver 0x0500 # include <windows. h> # include <setupapi. h> # include <basetyps. h> # include <usbdi. h> # include <initguid. h> # include <stdio. h> # pragma comment (Lib, "setupapi. lib ") # pragma comment (Lib," hid. lib ") # pragma comment (Lib," comctl32.lib ") # ifndef bulkusbh_inc # define limit 0x0000 # define limit ctl_code (limit,/limit,/method_buffered, /file_any_access) # define incluctl_code (response,/consumed + 1,/method_buffered,/file_any_access) # define incluctl_code (response,/consumed + 2,/method_buffered,/file_any_access) extern handle open_file (char * filename); extern int getusbpath (char * path); extern int writeusb (handle husb, char * outbuff, int Len); extern int readusb (handle husb, byte inbuff [], DWORD & nbytesread, int ntoread ); 3.2 source file USB port. cpp# Include "USB port. H "// values (guid_class_i82930_bulk, 0x8a3bf75d, 0x83c7, 0x0000e, 0x82, 0x76, 0x5a, 0xe3, 0xf3, 0xea, 0x6e, 0x77 ); bool getusbdevicefilename (lpguid pguid, char * outnamebuf); handle openusbdevice (lpguid pguid, char * outnamebuf); handle openonedevice (hdevinfo identifier, deviceinfodata, char * devname); int getusbp Ath (char * path); int writeusb (handle husb, char * outbuff, int Len); int readusb (handle husb, byte inbuff [], DWORD & nbytesread, int ntoread ); /* Name: open_file function: Enable the USB device parameter: filename is defined as "pipe00" pipe name for bulk input pipe on our test board, "pipe01" pipe name for bulk output pipe on our test board. Pipe00 and pipe01 refer to src/USB/bulkusb. The two functions are the same in actual use. To avoid the crash caused by USB exceptions, I use non-blocking mode to open the file. */Handle open_file (char * filename) {int success = 1; handle h; char completedevicename [256] = ""; // generated from the guid registered by the driver itself if (! Getusbdevicefilename (lpguid) & complete, completedevicename) {// noisy ("failed to getusbdevicefilename/N", getlasterror (); Return identifier;} strcat (completedevicename, "//"); strcat (completedevicename, filename); // printf ("completedevicename = (% s)/n", completedevicename); H = createfile (completedevicename, generic_write | generic_read, file_pai_write | file_share _ Read, null, open_existing, file_attribute_normal | file_flag_overlapped, null); If (H = invalid_handle_value) {// noisy ("failed to open (% S) = % d ", completedevicename, getlasterror (); success = 0;} else {// noisy ("opened successfully. /n ");} return h;}/* Name: getusbdevicefilename function: Obtain the path parameter of the USB device: pguid returned: outnamebuf USB device path */bool getusbdevicefilename (lpguid pguid, char * outnamebuf) {handle HD Ev = openusbdevice (pguid, outnamebuf); If (hdev! = Invalid_handle_value) {closehandle (hdev); Return true;} return false;}/* Name: openusbdevice function: Get the USB device path parameter: pguid returned: outnamebuf USB device path */handle openusbdevice (lpguid pguid, char * outnamebuf) {ulong numberdevices; handle Hout = handle; hdevinfo handle; using deviceinfodata; ulong I; Boolean done; using usbdeviceinst; pusb_devi Ce_descriptor * usbdevices = & usbdeviceinst; * usbdevices = NULL; numberdevices = 0; // open a handle to the plug and play Dev node. // setupdigetclassdevs () returns a device information set that contains info on all // installed devices of a specified class. // hardwaredeviceinfo = setupdigetclassdevs (pguid, null, // define no enumerator (global) null, // define no (digcf_present | // only Dev ICES present digcf_interfacedevice); // function class devices. /// take a wild guess at the number of devices we have; // be prepared to realloc and retry if there are more than we guessed // numberdevices = 4; done = false; deviceinfodata. cbsize = sizeof (sp_interface_device_data); I = 0; while (! Done) {numberdevices * = 2; If (* usbdevices) {* usbdevices = (pusb_device_descriptor) realloc (* usbdevices, (numberdevices * sizeof (usb_device_descriptor )));} else {* usbdevices = (pusb_device_descriptor) calloc (numberdevices, sizeof (usb_device_descriptor);} If (null = * usbdevices) {// setupdidestroydeviceinfolist destroys a device information set // and frees all associated memory. setupdide Stroydeviceinfolist (hardwaredeviceinfo); Return invalid_handle_value;} usbdeviceinst = * usbdevices + I; for (; I <numberdevices; I ++) {// setupdienumdeviceinterfaces () returns information about device interfaces // exposed by one or more devices. each call returns information about one interface; // The routine can be called repeatedly to get information about Several Interfaces // exposed One or more devices. if (outputs (hardwaredeviceinfo, 0, // We don't care about specific PDOS pguid, I, & deviceinfodata) {Hout = openonedevice (hardwaredeviceinfo, & deviceinfodata, outnamebuf ); if (Hout! = Invalid_handle_value) {done = true; break ;}} else {If (error_no_more_items = getlasterror () {done = true; break ;}}} numberdevices = I; // setupdidestroydeviceinfolist () destroys a device information set // and frees all associated memory. setupdidestroydeviceinfolist (hardwaredeviceinfo); free (* usbdevices); Return Hout;} Handle openonedevice (in hdevinfo hardwaredeviceinfo, in PSP _ Interface_device_data deviceinfodata, In char * devname) {functions functionclassdevicedata = NULL; ulong predictedlength = 0; ulong requiredlength = 0; handle Hout = invalid_handle_value; /// allocate a function class device data structure to receive the // goods about this special device. // setupdigetinterfacedevicedetail (hardwaredeviceinfo, deviceinfodata, null, // Probing so no output buffer yet 0, // probing so output buffer length of zero & requiredlength, null); // not interested in the specific Dev-node predictedlength = requiredlength; // sizeof (sp_fnclass_device_data) + 512; functionclassdevicedata = (optional) malloc (predictedlength); functionclassdevicedata-> cbsize = sizeof (optional); // retrieve The information from Plug and Play. // If (! Response (response, deviceinfodata, functionclassdevicedata, predictedlength, & requiredlength, null) {free (functionclassdevicedata); return response;} strcpy (devname, response-> devicepath ); // printf ("attempting to open % s/n", devname); Hout = createfile (functionclassdevicedata-> devicepath, generic_read | generic_write, file_sha Re_read | file_pai_write, null, // No security_attributes structure open_existing, // no special create flags 0, // no special attributes null ); // no template file if (invalid_handle_value = Hout) {// printf ("failed to open % s/n", devname);} Free (functionclassdevicedata); Return Hout ;} /* Name: getusbpath function: Return USB device path parameter: pguid return: Path */INT getusbpath (char * path) {If (! Getusbdevicefilename (lpguid) & guid_class_i82930_bulk, PATH) {return 0;} return 1;}/* Name: writeusb function: Write Data parameter to USB: husb handle, outbut Data Pointer, Len Data Length */INT writeusb (handle husb, char * outbuff, int Len) {DWORD nbyteswrite, endtime, LRC; static overlapped ol; DWORD dwerrormask, dwerror; COMSTAT; If (husb = NULL) return 0; ol. offset = 0; // specify 0 ol for the device. offsethigh = 0; // specify 0 ol for the device. hevent = NULL; // identifies an event as a non-signal state and transmits data When sending is complete, it will be set to the signal status ol. hevent = createevent (null, true, false, null); If (! Writefile (husb, outbuff, Len, & nbyteswrite, & ol) {// error message processing -------------------------------- if (LRC = getlasterror () = error_io_pending) {endtime = gettickcount () + 1000; while (! Getoverlappedresult (husb, & ol, & nbyteswrite, false) {dwerror = getlasterror (); If (gettickcount ()> endtime) {MessageBox (null, "writing a serial port takes too long, currently, the number of data in the serial sending buffer is null, null, null); break;} If (dwerror = error_io_incomplete) continue; // If the returned result else is not fully read, an error occurs. Try to restore it! Break; }}// ------------------------------------------------------- //} closehandle (ol. hevent); flushfilebuffers (husb); return 1;}/* Name: readusb function: read data from USB device parameters: husb handle, ntoread read length returned: data read by inbuff, length of nbytesread */INT readusb (handle husb, byte inbuff [], DWORD & nbytesread, int ntoread) {dword lrc; /// longitudinal redundancy check DWORD endtime; ////// jiesuo static overlapped ol; int readnumber = 0; int numcount = 0; // Control DWORD dwerrormask, DWORD dwevtmask, DWORD ntoread, int readtime, readtime = 2000, ntoread = ntoread, ol. offset = 0; // The Byte offset relative to the start of the file ol. offsethigh = 0; // The high character of the byte offset from which data is transmitted. The Calling process can be ignored during pipelines and communication. Ol. hevent = NULL; // identifies the event. When data transmission is complete, set it to the signal state ol. hevent = createevent (null, true, false, null); If (! Readfile (husb, inbuff, ntoread, & nbytesread, & ol) {If (LRC = getlasterror () = error_io_pending) {// endtime = gettickcount () + readtime; // gettickcount () the time (in milliseconds) used to retrieve the start time of the system while (! Getoverlappedresult (husb, & ol, & nbytesread, false) // This function retrieves the result of the overlapped operation {If (gettickcount ()> endtime) Break ;}} closehandle (ol. hevent); return 1 ;} 4. PrerequisitesDevelopment of USB program, need to download microsotft DDK (driver develop kit) Library, the library configuration please refer to the http://blog.csdn.net/skdev/archive/2007/01/26/1494635.aspx 5 results

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.