| 945 | |
| 946 | |
| 947 | int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) |
| 948 | { |
| 949 | int bytes_read = -1; |
| 950 | |
| 951 | #if 0 |
| 952 | int transferred; |
| 953 | int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000); |
| 954 | LOG("transferred: %d\n", transferred); |
| 955 | return transferred; |
| 956 | #endif |
| 957 | |
| 958 | pthread_mutex_lock(&dev->mutex); |
| 959 | pthread_cleanup_push(&cleanup_mutex, dev); |
| 960 | |
| 961 | /* There's an input report queued up. Return it. */ |
| 962 | if (dev->input_reports) { |
| 963 | /* Return the first one */ |
| 964 | bytes_read = return_data(dev, data, length); |
| 965 | goto ret; |
| 966 | } |
| 967 | |
| 968 | if (dev->shutdown_thread) { |
| 969 | /* This means the device has been disconnected. |
| 970 | An error code of -1 should be returned. */ |
| 971 | bytes_read = -1; |
| 972 | goto ret; |
| 973 | } |
| 974 | |
| 975 | if (milliseconds == -1) { |
| 976 | /* Blocking */ |
| 977 | while (!dev->input_reports && !dev->shutdown_thread) { |
| 978 | pthread_cond_wait(&dev->condition, &dev->mutex); |
| 979 | } |
| 980 | if (dev->input_reports) { |
| 981 | bytes_read = return_data(dev, data, length); |
| 982 | } |
| 983 | } |
| 984 | else if (milliseconds > 0) { |
| 985 | /* Non-blocking, but called with timeout. */ |
| 986 | int res; |
| 987 | struct timespec ts; |
| 988 | clock_gettime(CLOCK_REALTIME, &ts); |
| 989 | ts.tv_sec += milliseconds / 1000; |
| 990 | ts.tv_nsec += (milliseconds % 1000) * 1000000; |
| 991 | if (ts.tv_nsec >= 1000000000L) { |
| 992 | ts.tv_sec++; |
| 993 | ts.tv_nsec -= 1000000000L; |
| 994 | } |
| 995 | |
| 996 | while (!dev->input_reports && !dev->shutdown_thread) { |
| 997 | res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts); |
| 998 | if (res == 0) { |
| 999 | if (dev->input_reports) { |
| 1000 | bytes_read = return_data(dev, data, length); |
| 1001 | break; |
| 1002 | } |
| 1003 | |
| 1004 | /* If we're here, there was a spurious wake up |
no test coverage detected