📄 io.c
字号:
* * The wLength field placed in the setup packet must be the length you would * expect to be sent in the setup packet: the length of the payload that * follows (or the expected maximum number of bytes to receive). However, * the length field of the libusb_transfer object must be the length of * the data buffer - i.e. it should be wLength <em>plus</em> the size of * the setup packet (LIBUSB_CONTROL_SETUP_SIZE). * * If you use the helper functions, this is simplified for you: * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the * data you are sending/requesting. * -# Call libusb_fill_control_setup() on the data buffer, using the transfer * request size as the wLength value (i.e. do not include the extra space you * allocated for the control setup). * -# If this is a host-to-device transfer, place the data to be transferred * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE. * -# Call libusb_fill_control_transfer() to associate the data buffer with * the transfer (and to set the remaining details such as callback and timeout). * - Note that there is no parameter to set the length field of the transfer. * The length is automatically inferred from the wLength field of the setup * packet. * -# Submit the transfer. * * The multi-byte control setup fields (wValue, wIndex and wLength) must * be given in little-endian byte order (the endianness of the USB bus). * Endianness conversion is transparently handled by * libusb_fill_control_setup() which is documented to accept host-endian * values. * * Further considerations are needed when handling transfer completion in * your callback function: * - As you might expect, the setup packet will still be sitting at the start * of the data buffer. * - If this was a device-to-host transfer, the received data will be sitting * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer. * - The actual_length field of the transfer structure is relative to the * wLength of the setup packet, rather than the size of the data buffer. So, * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you * should expect an <tt>actual_length</tt> of 4 to indicate that the data was * transferred in entirity. * * To simplify parsing of setup packets and obtaining the data from the * correct offset, you may wish to use the libusb_control_transfer_get_data() * and libusb_control_transfer_get_setup() functions within your transfer * callback. * * Even though control endpoints do not halt, a completed control transfer * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control * request was not supported. * * \section asyncintr Considerations for interrupt transfers * * All interrupt transfers are performed using the polling interval presented * by the bInterval value of the endpoint descriptor. * * \section asynciso Considerations for isochronous transfers * * Isochronous transfers are more complicated than transfers to * non-isochronous endpoints. * * To perform I/O to an isochronous endpoint, allocate the transfer by calling * libusb_alloc_transfer() with an appropriate number of isochronous packets. * * During filling, set \ref libusb_transfer::type "type" to * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than * or equal to the number of packets you requested during allocation. * libusb_alloc_transfer() does not set either of these fields for you, given * that you might not even use the transfer on an isochronous endpoint. * * Next, populate the length field for the first num_iso_packets entries in * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section * 5.6.3 of the USB2 specifications describe how the maximum isochronous * packet length is determined by wMaxPacketSize field in the endpoint * descriptor. Two functions can help you here: * * - libusb_get_max_packet_size() is an easy way to determine the max * packet size for an endpoint. * - libusb_set_iso_packet_lengths() assigns the same length to all packets * within a transfer, which is usually what you want. * * For outgoing transfers, you'll obviously fill the buffer and populate the * packet descriptors in hope that all the data gets transferred. For incoming * transfers, you must ensure the buffer has sufficient capacity for * the situation where all packets transfer the full amount of requested data. * * Completion handling requires some extra consideration. The * \ref libusb_transfer::actual_length "actual_length" field of the transfer * is meaningless and should not be examined; instead you must refer to the * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of * each individual packet. * * The \ref libusb_transfer::status "status" field of the transfer is also a * little misleading: * - If the packets were submitted and the isochronous data microframes * completed normally, status will have value * \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED * "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred * delays are not counted as transfer errors; the transfer.status field may * indicate COMPLETED even if some or all of the packets failed. Refer to * the \ref libusb_iso_packet_descriptor::status "status" field of each * individual packet to determine packet failures. * - The status field will have value * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR * "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered. * - Other transfer status codes occur with normal behaviour. * * The data for each packet will be found at an offset into the buffer that * can be calculated as if each prior packet completed in full. The * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple() * functions may help you here. * * \section asyncmem Memory caveats * * In most circumstances, it is not safe to use stack memory for transfer * buffers. This is because the function that fired off the asynchronous * transfer may return before libusb has finished using the buffer, and when * the function returns it's stack gets destroyed. This is true for both * host-to-device and device-to-host transfers. * * The only case in which it is safe to use stack memory is where you can * guarantee that the function owning the stack space for the buffer does not * return until after the transfer's callback function has completed. In every * other case, you need to use heap memory instead. * * \section asyncflags Fine control * * Through using this asynchronous interface, you may find yourself repeating * a few simple operations many times. You can apply a bitwise OR of certain * flags to a transfer to simplify certain things: * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK * "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred * less than the requested amount of data being marked with status * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR" * (they would normally be regarded as COMPLETED) * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER * "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer * buffer when freeing the transfer. * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER * "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the * transfer after the transfer callback returns. * * \section asyncevent Event handling * * In accordance of the aim of being a lightweight library, libusb does not * create threads internally. This means that libusb code does not execute * at any time other than when your application is calling a libusb function. * However, an asynchronous model requires that libusb perform work at various * points in time - namely processing the results of previously-submitted * transfers and invoking the user-supplied callback function. * * This gives rise to the libusb_handle_events() function which your * application must call into when libusb has work do to. This gives libusb * the opportunity to reap pending transfers, invoke callbacks, etc. * * The first issue to discuss here is how your application can figure out * when libusb has work to do. In fact, there are two naive options which * do not actually require your application to know this: * -# Periodically call libusb_handle_events() in non-blocking mode at fixed * short intervals from your main loop * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated * thread. * * The first option is plainly not very nice, and will cause unnecessary * CPU wakeups leading to increased power usage and decreased battery life. * The second option is not very nice either, but may be the nicest option * available to you if the "proper" approach can not be applied to your * application (read on...). * * The recommended option is to integrate libusb with your application main * event loop. libusb exposes a set of file descriptors which allow you to do * this. Your main loop is probably already calling poll() or select() or a * variant on a set of file descriptors for other event sources (e.g. keyboard * button presses, mouse movements, network sockets, etc). You then add * libusb's file descriptors to your poll()/select() calls, and when activity * is detected on such descriptors you know it is time to call * libusb_handle_events(). * * There is one final event handling complication. libusb supports * asynchronous transfers which time out after a specified time period, and * this requires that libusb is called into at or after the timeout so that * the timeout can be handled. So, in addition to considering libusb's file * descriptors in your main event loop, you must also consider that libusb * sometimes needs to be called into at fixed points in time even when there * is no file descriptor activity. * * For the details on retrieving the set of file descriptors and determining * the next timeout, see the \ref poll "polling and timing" API documentation. *//** * @defgroup poll Polling and timing * * This page documents libusb's functions for polling events and timing. * These functions are only necessary for users of the * \ref asyncio "asynchronous API". If you are only using the simpler * \ref syncio "synchronous API" then you do not need to ever call these * functions. * * The justification for the functionality described here has already been * discussed in the \ref asyncevent "event handling" section of the * asynchronous API documentation. In summary, libusb does not create internal * threads for event processing and hence relies on your application calling * into libusb at certain points in time so that pending events can be handled. * In order to know precisely when libusb needs to be called into, libusb * offers you a set of pollable file descriptors and information about when * the next timeout expires. * * If you are using the asynchronous I/O API, you must take one of the two * following options, otherwise your I/O will not complete. * * \section pollsimple The simple option * * If your application revolves solely around libusb and does not need to * handle other event sources, you can have a program structure as follows:\code// initialize libusb// find and open device// maybe fire off some initial async I/Owhile (user_has_not_requested_exit) libusb_handle_events(ctx);// clean up and exit\endcode * * With such a simple main loop, you do not have to worry about managing * sets of file descriptors or handling timeouts. libusb_handle_events() will * handle those details internally. * * \section pollmain The more advanced option * * In more advanced applications, you will already have a main loop which * is monitoring other event sources: network sockets, X11 events, mouse * movements, etc. Through exposing a set of file descriptors, libusb is * designed to cleanly integrate into such main loops. * * In addition to polling file descriptors for the other event sources, you * take a set of file descriptors from libusb and monitor those too. When you * detect activity on libusb's file descriptors, you call * libusb_handle_events_timeout() in non-blocking mode. * * You must also consider the fact that libusb sometimes has to handle events * at certain known times which do not generate activity on file descriptors. * Your main loop must also consider these times, modify it's poll()/select() * timeout accordingly, and track time so that libusb_handle_events_timeout() * is called in non-blocking mode when timeouts expire. * * In pseudo-code, you want something that looks like:\code// initialise libusblibusb_get_pollfds(ctx)while (user has not requested application exit) { libusb_get_next_timeout(ctx); select(on libusb file descriptors plus any other event sources of interest, using a timeout no larger than the value libusb just suggested) if (select() indicated activity on libusb file descriptors) libusb_handle_events_timeout(ctx, 0); if (time has elapsed to or beyond the libusb timeout) libusb_handle_events_timeout(ctx, 0);}// clean up and exit\endcode * * The set of file descriptors that libusb uses as event sources may change * during the life of your application. Rather than having to repeatedly * call libusb_get_pollfds(), you can set up notification functions for when * the file descriptor set changes using libusb_set_pollfd_notifiers(). * * \section mtissues Multi-threaded considerations * * Unfortunately, the situation is complicated further when multiple threads * come into play. If two threads are monitoring the same file descriptors, * the fact that only one thread will be woken up when an event occurs causes * some headaches. * * The events lock, event waiters lock, and libusb_handle_events_locked() * entities are added to solve these problems. You do not need to be concerned * with these entities otherwise. * * See the extra documentation: \ref mtasync *//** \page mtasync Multi-threaded applications and asynchronous I/O * * libusb is a thread-safe library, but extra considerations must be applied * to applications which interact with libusb from multiple threads. * * The underlying issue that must be addressed is that all libusb I/O * revolves around monitoring file descriptors through the poll()/select() * system calls. This is directly exposed at the * \ref asyncio "asynchronous interface" but it is important to note that the * \ref syncio "synchronous interface" is implemented on top of the * asynchonrous interface, therefore the same considerations apply. * * The issue is that if two or more threads are concurrently calling poll() * or select() on libusb's file descriptors then only one of those threads * will be woken up when an event arrives. The others will be completely * oblivious that anything has happened. * * Consider the following pseudo-code, which submits an asynchronous transfer * then waits for its completion. This style is one way you could implement a * synchronous interface on top of the asynchronous interface (and libusb * does something similar, albeit more advanced due to the complications * explained on this page). *\codevoid cb(struct libusb_transfer *transfer){ int *completed = transfer->user_data; *completed = 1;}void myfunc() { const struct timeval timeout = { 120, 0 }; struct libusb_transfer *transfer; unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE]; int completed = 0; transfer = libusb_alloc_transfer(0); libusb_fill_control_setup(buffer, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0); libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000); libusb_submit_transfer(transfer); while (!completed) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -