| 1239 | } |
| 1240 | |
| 1241 | int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) |
| 1242 | { |
| 1243 | int bytes_read = -1; |
| 1244 | |
| 1245 | /* Lock the access to the report list. */ |
| 1246 | pthread_mutex_lock(&dev->mutex); |
| 1247 | |
| 1248 | /* There's an input report queued up. Return it. */ |
| 1249 | if (dev->input_reports) { |
| 1250 | /* Return the first one */ |
| 1251 | bytes_read = return_data(dev, data, length); |
| 1252 | goto ret; |
| 1253 | } |
| 1254 | |
| 1255 | /* Return if the device has been disconnected. */ |
| 1256 | if (dev->disconnected) { |
| 1257 | bytes_read = -1; |
| 1258 | register_device_error(dev, "hid_read_timeout: device disconnected"); |
| 1259 | goto ret; |
| 1260 | } |
| 1261 | |
| 1262 | if (dev->shutdown_thread) { |
| 1263 | /* This means the device has been closed (or there |
| 1264 | has been an error. An error code of -1 should |
| 1265 | be returned. */ |
| 1266 | bytes_read = -1; |
| 1267 | register_device_error(dev, "hid_read_timeout: thread shutdown"); |
| 1268 | goto ret; |
| 1269 | } |
| 1270 | |
| 1271 | /* There is no data. Go to sleep and wait for data. */ |
| 1272 | |
| 1273 | if (milliseconds == -1) { |
| 1274 | /* Blocking */ |
| 1275 | int res; |
| 1276 | res = cond_wait(dev, &dev->condition, &dev->mutex); |
| 1277 | if (res == 0) |
| 1278 | bytes_read = return_data(dev, data, length); |
| 1279 | else { |
| 1280 | /* There was an error, or a device disconnection. */ |
| 1281 | register_device_error(dev, "hid_read_timeout: error waiting for more data"); |
| 1282 | bytes_read = -1; |
| 1283 | } |
| 1284 | } |
| 1285 | else if (milliseconds > 0) { |
| 1286 | /* Non-blocking, but called with timeout. */ |
| 1287 | int res; |
| 1288 | struct timespec ts; |
| 1289 | struct timeval tv; |
| 1290 | gettimeofday(&tv, NULL); |
| 1291 | TIMEVAL_TO_TIMESPEC(&tv, &ts); |
| 1292 | ts.tv_sec += milliseconds / 1000; |
| 1293 | ts.tv_nsec += (milliseconds % 1000) * 1000000; |
| 1294 | if (ts.tv_nsec >= 1000000000L) { |
| 1295 | ts.tv_sec++; |
| 1296 | ts.tv_nsec -= 1000000000L; |
| 1297 | } |
| 1298 |
no test coverage detected