USB HID learning: a little development record

Former colleague one day, once I find that there is a USB projects. Knowing that I was leaving in looking for work, then forwarded to me, and then introduce clients to me.

After understanding the needs, I analyzed, mainly communication with the host computer USB devices, MFC I am familiar with, find an open source USB library hidapi, cross-platform operation, download code, trying to read the mouse information, access to information. So you can take to determine, agreed customers. After in-depth understanding of the needs. I think the difficulty is that MFC graphics and HID protocol interaction. Phased implementation of the final decision, of course, the cost is paid in stages.

The first stage

Pre-made interface, complete 2 versions to the customer, the customer select one paragraph. At the same time send a hardware device over.
Prior to the board yet to come, to complete the main interface window as well as the main layout. MFC research program at startup, system tray and other functions.

After the board, he began to study HID communication. Sent a client tool read parameter may be the normal communication with the device. However, since the preparation of the code can not be read parameters. Re-examine the HID protocol, install the USB bus hound grab bag, packet control protocol analysis, there is little understanding of HID. In-depth tracking hidapi source code, found an error opening USB device, specifically, the enumeration phase to read the way open, followed by the use of reading and writing, but failed to return ERROR_ACCESS_DENIED (error code 5L), then re-use reading open for success. So I suspect the reason is because of the failure to read and write the way open. Online said windows10 system not to open for reading and writing HID, switching win7 virtual machines, test, the same effect. In the Linux system to run code with the same root privileges, but normal. He was in trouble.

Research a few days, I can not, reflect the difficulty with the customer, the customer got a C # code, which saw the marks of time, though some years, but also try to run, it can be found. Namely: use the same windows10 system is normal and (in fact, the previous tool parameters can be read also proved) to communicate HID device. So analyze C # code, transceivers feature report found that where there are problems. The original feature report to a predetermined size, to know the current character 32 (using hidapi code, etc., must pay a byte ID, a total of 33 bytes), if the length does not meet the requirements, an error is returned, an error code 87L (i.e. ERROR_INVALID_PARAMETER). Modified, as usual, to solve problems.

Then study write data onto flash on the board via USB, also encountered problems. By bus hound analysis of the data found written some programming with binary files do not correspond. Looking for a long time, found that the offset range of the code in question. Since the feature report is only 32 bytes, 512 bytes is to be written, so to cycle times, the offset variables uint8, 255 range only, so the content is 512 bytes, the first 128 bytes of the contents of the error, of course, failure. After the correction, everything is normal.

This, the first phase is completed, the interface layout, language switching operation flash, completed, from the first day to the completion of the contact, takes three weeks. To give customers a good impression, catch the progress of the night basically got 1 to 2:00, weekends are out most of the time. While staying at home, but due to the care of children, but also to buy food to cook, daily chores take up a lot of time. Fortunately, customers scheduled play money, temporarily alleviate the immediate need.

Follow-up phase

Subsequent phases basically no real difficulty, to say time-consuming, mainly uncertainty of demand, due to the background and industry knowledge do not know much, very often, the needs of customers are much simpler, but for me and simple, back and forth so many times to communicate.
To mention customer support windows xp and windows 7 system, because there is no confirmation early this point, so I chose VS 2015 development, or can not run on xp has been tested, so with the customer feedback, the final confirmation without support xp system.
Because the calibration process is to be displayed, it is necessary to draw the cursor, and scintillation, maximum support 9:00, about ten years ago knew tslib library, when you see the cross-hair tslib on GitHub, feel at home. Thus realizing a pattern identical in MFC. I do not know is called plagiarism or call salute.
Paint is another piece of relevant coordinates and histogram display, but no matter what, can not find the mouse scaled according to the program, also for this reason, to start learning Qt, want to see the effect of another set of graphics development framework. Of course, this is another topic.

programming

Because individual advocating simple, so in principle the final program has only one exe, it does not depend on other files (of course, some system-level dll, not included). So the hidapi source files directly added to the projects, and then encapsulates the class. Followed by a switch in English, began to consider using po to achieve language translation, but too complex to implement. It is necessary to file written language, but also compile, so give up. Stupid end-use mode, when the interface design using the Chinese, and then switch the code. Language switch and start-up and other signs written in the registry.
This project, the use of the technique: HID read and write data, USB devices plug detector, parent-child communication window, boot, the system tray, registry write, control drawing.

Summary problem

1. Open the HID devices return ERROR_ACCESS_DENIED (error code 5L) problem.
The reason for the failure is, Windows believe mouse, keyboard, should not be used to read and write (the actual impact should be "write") opened. For safety reasons, and therefore it does not provide a mechanism to write. hidapi author also mentioned this point in the GitHub issue.

Open function device open_device, as follows:

static HANDLE open_device(const char *path, BOOL open_rw)
{
    HANDLE handle;
    DWORD desired_access = (open_rw)? (GENERIC_WRITE | GENERIC_READ): 0;
    DWORD share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;

    handle = CreateFileA(path,
        desired_access,
        share_mode,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/
        0);

    return handle;
}

CreateFileA actual function, passing parameters is twofold: the path and permissions (whether reading and writing). When enumeration is not used to read and write. I.e. CreateFileA dwDesiredAccess second parameter is 0. When the official open, first try to read and write (usually fail), and then failed with 0, this time successfully. Strayed into a dead end, be sure to read and write data that is sent to open the way, the key statement:

desired_access = (open_rw)? (GENERIC_WRITE | GENERIC_READ): 0;

Research for a long time, have been set STANDARD_RIGHTS_READ, STANDARD_RIGHTS_WRITE, but failed.
Once you've found a similar problem in the post . Although the question which referred to similar, but different in nature. Post author is the same USB device is recognized the two devices, so you can determine that the HID class by a path. But the author does not succeed, in view of the performance of different issues, did not look at the post (see information in English are jumping).

2, feature report Send questions.
Report transmission, error in hid_send_feature_report function, i.e. HidD_SetFeature with the GetLastError function to obtain an error code, returned 87L (i.e. ERROR_INVALID_PARAMETER). Change report packet size of 0x20 + 1, success, bus hound to be captured. (Observe the bus hound and a number of online message analysis (length 0x20), combined with ERROR_INVALID_PARAMETER, speculation may be the length of the problem, corrections, also successful.)

Experiences

The beginning of the first completed the main frame, and then slowly refined, first, outline, and then there are the details, so with confidence, not afraid to take the time to modify, or to wait for a pre resource, if the resource is not in place, can only wait, all for nothing. In addition, after a good overall structure, not necessarily to demand before and after implementation, it can be switched, that more needs to achieve peak load shifting, so that the potential use of brain time, dark time for us to think. In layman's terms, when faced with a bucket, you can skip a few days might expect solution to the problems. Do other things are similar, such as writing a book.

For the structure, displacement or crc calculation, the limited number of variables need. However, the length, the return value, offset, etc., can be used directly int, developed in the field of PC, without regard to byte savings. This does not pay sufficient attention in the development, leading to take some time.

On demand, in fact, there is no guarantee the outset, very accurate and complete, they are slowly add. Sometimes customers do not know what kind of functions to achieve, what kind of things made at this time, we can guide customers, and even their own ideas to complete a version of the press, to allow customers to evaluate. If we and other customers, such as our customers, so only time-consuming, the project does not help. If nobody mentioned scheme, self-made, if nobody comments, press their views. This is my favorite way of doing things.

In doing this project, previous experience learned, everything from the practical problems, the pursuit of speed, do not expand research technology. To complete, and then slowly reviewed and summarized. In fact, the program for so many years, there will be in the development of their own set of criteria to the present situation, the development must have git version control, code formats and notes, brief development notes, if these do not do, will feel at ease.

Project Summary

To tell the truth, in retrospect, that the initial assessment is somewhat risky. I just use the mouse hidapi get the information, but the data is not written test (Note: Try to write data to the mouse, failure). Therefore, it would face a big problem when you first debug hardware, once thought the case would fail. Fortunately, the C # code to customers, but fortunately there is a little bit of C # based on a final settlement after trace debug. Resolution process to NIC lot of information, also studied hidapi source.
Either way, from the development of the nervous worried now relieved, still a little sense of accomplishment, because the accumulated experience in the development of one aspect, in addition to the adverse consequences of staying up late, the other is good.

发布了481 篇原创文章 · 获赞 244 · 访问量 110万+

Guess you like

Origin blog.csdn.net/subfate/article/details/104304343