]> sigrok.org Git - libsigrok.git/blob - src/scpi/scpi_usbtmc_libusb.c
scpi: Pass SCPI device instance to open and close callbacks.
[libsigrok.git] / src / scpi / scpi_usbtmc_libusb.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <string.h>
22 #include <libsigrok/libsigrok.h>
23 #include "libsigrok-internal.h"
24 #include "scpi.h"
25
26 #define LOG_PREFIX "scpi_usbtmc"
27
28 #define MAX_TRANSFER_LENGTH 2048
29 #define TRANSFER_TIMEOUT 1000
30
31 struct scpi_usbtmc_libusb {
32         struct sr_context *ctx;
33         struct sr_usb_dev_inst *usb;
34         int detached_kernel_driver;
35         uint8_t interface;
36         uint8_t bulk_in_ep;
37         uint8_t bulk_out_ep;
38         uint8_t interrupt_ep;
39         uint8_t usbtmc_int_cap;
40         uint8_t usbtmc_dev_cap;
41         uint8_t usb488_dev_cap;
42         uint8_t bTag;
43         uint8_t bulkin_attributes;
44         uint8_t buffer[MAX_TRANSFER_LENGTH];
45         int response_length;
46         int response_bytes_read;
47         int remaining_length;
48         int rigol_ds1000;
49 };
50
51 /* Some USBTMC-specific enums, as defined in the USBTMC standard. */
52 #define SUBCLASS_USBTMC  0x03
53 #define USBTMC_USB488    0x01
54
55 enum {
56         /* USBTMC control requests */
57         INITIATE_ABORT_BULK_OUT     =   1,
58         CHECK_ABORT_BULK_OUT_STATUS =   2,
59         INITIATE_ABORT_BULK_IN      =   3,
60         CHECK_ABORT_BULK_IN_STATUS  =   4,
61         INITIATE_CLEAR              =   5,
62         CHECK_CLEAR_STATUS          =   6,
63         GET_CAPABILITIES            =   7,
64         INDICATOR_PULSE             =  64,
65
66         /* USB488 control requests */
67         READ_STATUS_BYTE            = 128,
68         REN_CONTROL                 = 160,
69         GO_TO_LOCAL                 = 161,
70         LOCAL_LOCKOUT               = 162,
71 };
72
73 /* USBTMC status codes */
74 #define USBTMC_STATUS_SUCCESS      0x01
75
76 /* USBTMC capabilities */
77 #define USBTMC_INT_CAP_LISTEN_ONLY 0x01
78 #define USBTMC_INT_CAP_TALK_ONLY   0x02
79 #define USBTMC_INT_CAP_INDICATOR   0x04
80
81 #define USBTMC_DEV_CAP_TERMCHAR    0x01
82
83 #define USB488_DEV_CAP_DT1         0x01
84 #define USB488_DEV_CAP_RL1         0x02
85 #define USB488_DEV_CAP_SR1         0x04
86 #define USB488_DEV_CAP_SCPI        0x08
87
88 /* Bulk messages constants */
89 #define USBTMC_BULK_HEADER_SIZE  12
90
91 /* Bulk MsgID values */
92 #define DEV_DEP_MSG_OUT         1
93 #define REQUEST_DEV_DEP_MSG_IN  2
94 #define DEV_DEP_MSG_IN          2
95
96 /* bmTransferAttributes */
97 #define EOM                0x01
98 #define TERM_CHAR_ENABLED  0x02
99
100 struct usbtmc_blacklist {
101         uint16_t vid;
102         uint16_t pid;
103 };
104
105 static struct usbtmc_blacklist blacklist_remote[] = {
106         /* Rigol DS1000 series publishes RL1 support, but doesn't support it. */
107         { 0x1ab1, 0x0588 },
108         ALL_ZERO
109 };
110
111 static GSList *scpi_usbtmc_libusb_scan(struct drv_context *drvc)
112 {
113         struct libusb_device **devlist;
114         struct libusb_device_descriptor des;
115         struct libusb_config_descriptor *confdes;
116         const struct libusb_interface_descriptor *intfdes;
117         GSList *resources = NULL;
118         int confidx, intfidx, ret, i;
119         char *res;
120
121         ret = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
122         if (ret < 0) {
123                 sr_err("Failed to get device list: %s.",
124                        libusb_error_name(ret));
125                 return NULL;
126         }
127         for (i = 0; devlist[i]; i++) {
128                 libusb_get_device_descriptor(devlist[i], &des);
129
130                 for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
131                         if ((ret = libusb_get_config_descriptor(devlist[i], confidx, &confdes)) < 0) {
132                                 sr_dbg("Failed to get configuration descriptor: %s, "
133                                        "ignoring device.", libusb_error_name(ret));
134                                 break;
135                         }
136                         for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
137                                 intfdes = confdes->interface[intfidx].altsetting;
138                                 if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
139                                     intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
140                                     intfdes->bInterfaceProtocol != USBTMC_USB488)
141                                         continue;
142                                 sr_dbg("Found USBTMC device (VID:PID = %04x:%04x, "
143                                        "bus.address = %d.%d).", des.idVendor, des.idProduct,
144                                        libusb_get_bus_number(devlist[i]),
145                                        libusb_get_device_address(devlist[i]));
146                                 res = g_strdup_printf("usbtmc/%d.%d",
147                                                       libusb_get_bus_number(devlist[i]),
148                                                       libusb_get_device_address(devlist[i]));
149                                 resources = g_slist_append(resources, res);
150                         }
151                         libusb_free_config_descriptor(confdes);
152                 }
153         }
154         libusb_free_device_list(devlist, 1);
155
156         sr_dbg("Found %d device(s).", g_slist_length(resources));
157
158         return resources;
159 }
160
161 static int scpi_usbtmc_libusb_dev_inst_new(void *priv, struct drv_context *drvc,
162                 const char *resource, char **params, const char *serialcomm)
163 {
164         struct scpi_usbtmc_libusb *uscpi = priv;
165         GSList *devices;
166
167         (void)resource;
168         (void)serialcomm;
169
170         if (!params || !params[1]) {
171                 sr_err("Invalid parameters.");
172                 return SR_ERR;
173         }
174
175         uscpi->ctx = drvc->sr_ctx;
176         devices = sr_usb_find(uscpi->ctx->libusb_ctx, params[1]);
177         if (g_slist_length(devices) != 1) {
178                 sr_err("Failed to find USB device '%s'.", params[1]);
179                 g_slist_free_full(devices, (GDestroyNotify)sr_usb_dev_inst_free);
180                 return SR_ERR;
181         }
182         uscpi->usb = devices->data;
183         g_slist_free(devices);
184
185         return SR_OK;
186 }
187
188 static int check_usbtmc_blacklist(struct usbtmc_blacklist *blacklist,
189                 uint16_t vid, uint16_t pid)
190 {
191         int i;
192
193         for (i = 0; blacklist[i].vid; i++) {
194                 if (blacklist[i].vid == vid && blacklist[i].pid == pid)
195                         return TRUE;
196         }
197
198         return FALSE;
199 }
200
201 static int scpi_usbtmc_remote(struct scpi_usbtmc_libusb *uscpi)
202 {
203         struct sr_usb_dev_inst *usb = uscpi->usb;
204         struct libusb_device *dev;
205         struct libusb_device_descriptor des;
206         int ret;
207         uint8_t status;
208
209         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
210                 return SR_OK;
211
212         dev = libusb_get_device(usb->devhdl);
213         libusb_get_device_descriptor(dev, &des);
214         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
215                 return SR_OK;
216
217         sr_dbg("Locking out local control.");
218         ret = libusb_control_transfer(usb->devhdl,
219                         LIBUSB_ENDPOINT_IN         |
220                         LIBUSB_REQUEST_TYPE_CLASS  |
221                         LIBUSB_RECIPIENT_INTERFACE,
222                         REN_CONTROL, 1,
223                         uscpi->interface,
224                         &status, 1,
225                         TRANSFER_TIMEOUT);
226         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
227                 if (ret < 0)
228                         sr_dbg("Failed to enter REN state: %s.", libusb_error_name(ret));
229                 else
230                         sr_dbg("Failed to enter REN state: USBTMC status %d.", status);
231                 return SR_ERR;
232         }
233
234         ret = libusb_control_transfer(usb->devhdl,
235                         LIBUSB_ENDPOINT_IN         |
236                         LIBUSB_REQUEST_TYPE_CLASS  |
237                         LIBUSB_RECIPIENT_INTERFACE,
238                         LOCAL_LOCKOUT, 1,
239                         uscpi->interface,
240                         &status, 1,
241                         TRANSFER_TIMEOUT);
242         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
243                 if (ret < 0)
244                         sr_dbg("Failed to enter local lockout state: %s.",
245                                         libusb_error_name(ret));
246                 else
247                         sr_dbg("Failed to enter local lockout state: USBTMC "
248                                         "status %d.", status);
249                 return SR_ERR;
250         }
251
252         return SR_OK;
253 }
254
255 static void scpi_usbtmc_local(struct scpi_usbtmc_libusb *uscpi)
256 {
257         struct sr_usb_dev_inst *usb = uscpi->usb;
258         struct libusb_device *dev;
259         struct libusb_device_descriptor des;
260         int ret;
261         uint8_t status;
262
263         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
264                 return;
265
266         dev = libusb_get_device(usb->devhdl);
267         libusb_get_device_descriptor(dev, &des);
268         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
269                 return;
270
271         sr_dbg("Returning local control.");
272         ret = libusb_control_transfer(usb->devhdl,
273                         LIBUSB_ENDPOINT_IN         |
274                         LIBUSB_REQUEST_TYPE_CLASS  |
275                         LIBUSB_RECIPIENT_INTERFACE,
276                         GO_TO_LOCAL, 1,
277                         uscpi->interface,
278                         &status, 1,
279                         TRANSFER_TIMEOUT);
280         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
281                 if (ret < 0)
282                         sr_dbg("Failed to clear local lockout state: %s.",
283                                         libusb_error_name(ret));
284                 else
285                         sr_dbg("Failed to clear local lockout state: USBTMC "
286                                         "status %d.", status);
287         }
288
289         return;
290 }
291
292 static int scpi_usbtmc_libusb_open(struct sr_scpi_dev_inst *scpi)
293 {
294         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
295         struct sr_usb_dev_inst *usb = uscpi->usb;
296         struct libusb_device *dev;
297         struct libusb_device_descriptor des;
298         struct libusb_config_descriptor *confdes;
299         const struct libusb_interface_descriptor *intfdes;
300         const struct libusb_endpoint_descriptor *ep;
301         int confidx, intfidx, epidx, config = 0;
302         uint8_t capabilities[24];
303         int ret, found = 0;
304
305         if (usb->devhdl)
306                 return SR_OK;
307
308         if (sr_usb_open(uscpi->ctx->libusb_ctx, usb) != SR_OK)
309                 return SR_ERR;
310
311         dev = libusb_get_device(usb->devhdl);
312         libusb_get_device_descriptor(dev, &des);
313
314         for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
315                 if ((ret = libusb_get_config_descriptor(dev, confidx, &confdes)) < 0) {
316                         sr_dbg("Failed to get configuration descriptor: %s, "
317                                "ignoring device.", libusb_error_name(ret));
318                         continue;
319                 }
320                 for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
321                         intfdes = confdes->interface[intfidx].altsetting;
322                         if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
323                             intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
324                             intfdes->bInterfaceProtocol != USBTMC_USB488)
325                                 continue;
326                         uscpi->interface = intfdes->bInterfaceNumber;
327                         config = confdes->bConfigurationValue;
328                         sr_dbg("Interface %d configuration %d.", uscpi->interface, config);
329                         for (epidx = 0; epidx < intfdes->bNumEndpoints; epidx++) {
330                                 ep = &intfdes->endpoint[epidx];
331                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
332                                     !(ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK))) {
333                                         uscpi->bulk_out_ep = ep->bEndpointAddress;
334                                         sr_dbg("Bulk OUT EP %d", uscpi->bulk_out_ep);
335                                 }
336                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
337                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
338                                         uscpi->bulk_in_ep = ep->bEndpointAddress;
339                                         sr_dbg("Bulk IN EP %d", uscpi->bulk_in_ep & 0x7f);
340                                 }
341                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT &&
342                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
343                                         uscpi->interrupt_ep = ep->bEndpointAddress;
344                                         sr_dbg("Interrupt EP %d", uscpi->interrupt_ep & 0x7f);
345                                 }
346                         }
347                         found = 1;
348                         uscpi->rigol_ds1000 = des.idVendor  == 0x1ab1 &&
349                                               des.idProduct == 0x0588;
350                 }
351                 libusb_free_config_descriptor(confdes);
352                 if (found)
353                         break;
354         }
355
356         if (!found) {
357                 sr_err("Failed to find USBTMC interface.");
358                 return SR_ERR;
359         }
360
361         if (libusb_kernel_driver_active(usb->devhdl, uscpi->interface) == 1) {
362                 if ((ret = libusb_detach_kernel_driver(usb->devhdl,
363                                                        uscpi->interface)) < 0) {
364                         sr_err("Failed to detach kernel driver: %s.",
365                                libusb_error_name(ret));
366                         return SR_ERR;
367                 }
368                 uscpi->detached_kernel_driver = 1;
369         }
370
371         if ((ret = libusb_set_configuration(usb->devhdl, config)) < 0) {
372                 sr_err("Failed to set configuration: %s.",
373                        libusb_error_name(ret));
374                 return SR_ERR;
375         }
376
377         if ((ret = libusb_claim_interface(usb->devhdl, uscpi->interface)) < 0) {
378                 sr_err("Failed to claim interface: %s.",
379                        libusb_error_name(ret));
380                 return SR_ERR;
381         }
382
383         if (!uscpi->rigol_ds1000) {
384         if ((ret = libusb_clear_halt(usb->devhdl, uscpi->bulk_in_ep)) < 0) {
385                 sr_err("Failed to clear halt/stall condition for EP %d: %s.",
386                        uscpi->bulk_in_ep, libusb_error_name(ret));
387                 return SR_ERR;
388         }
389         if ((ret = libusb_clear_halt(usb->devhdl, uscpi->bulk_out_ep)) < 0) {
390                 sr_err("Failed to clear halt/stall condition for EP %d: %s.",
391                        uscpi->bulk_out_ep, libusb_error_name(ret));
392                 return SR_ERR;
393         }
394         if ((ret = libusb_clear_halt(usb->devhdl, uscpi->interrupt_ep)) < 0) {
395                 sr_err("Failed to clear halt/stall condition for EP %d: %s.",
396                        uscpi->interrupt_ep, libusb_error_name(ret));
397                 return SR_ERR;
398         }
399         }
400
401         /* Get capabilities. */
402         ret = libusb_control_transfer(usb->devhdl,
403                                       LIBUSB_ENDPOINT_IN         |
404                                       LIBUSB_REQUEST_TYPE_CLASS  |
405                                       LIBUSB_RECIPIENT_INTERFACE,
406                                       GET_CAPABILITIES, 0,
407                                       uscpi->interface,
408                                       capabilities, sizeof(capabilities),
409                                       TRANSFER_TIMEOUT);
410         if (ret == sizeof(capabilities)) {
411                 uscpi->usbtmc_int_cap = capabilities[ 4];
412                 uscpi->usbtmc_dev_cap = capabilities[ 5];
413                 uscpi->usb488_dev_cap = capabilities[15];
414         }
415         sr_dbg("Device capabilities: %s%s%s%s%s, %s, %s",
416                uscpi->usb488_dev_cap & USB488_DEV_CAP_SCPI       ? "SCPI, "    : "",
417                uscpi->usbtmc_dev_cap & USBTMC_DEV_CAP_TERMCHAR   ? "TermChar, ": "",
418                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? "L3, " :
419                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? ""     : "L4, ",
420                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? "T5, " :
421                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? ""     : "T6, ",
422                uscpi->usb488_dev_cap & USB488_DEV_CAP_SR1        ? "SR1"  : "SR0",
423                uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1        ? "RL1"  : "RL0",
424                uscpi->usb488_dev_cap & USB488_DEV_CAP_DT1        ? "DT1"  : "DT0");
425
426         scpi_usbtmc_remote(uscpi);
427
428         return SR_OK;
429 }
430
431 static int scpi_usbtmc_libusb_source_add(struct sr_session *session,
432                 void *priv, int events, int timeout, sr_receive_data_callback cb,
433                 void *cb_data)
434 {
435         struct scpi_usbtmc_libusb *uscpi = priv;
436         (void)events;
437         return usb_source_add(session, uscpi->ctx, timeout, cb, cb_data);
438 }
439
440 static int scpi_usbtmc_libusb_source_remove(struct sr_session *session,
441                 void *priv)
442 {
443         struct scpi_usbtmc_libusb *uscpi = priv;
444         return usb_source_remove(session, uscpi->ctx);
445 }
446
447 static void usbtmc_bulk_out_header_write(void *header, uint8_t MsgID,
448                                          uint8_t bTag,
449                                          uint32_t TransferSize,
450                                          uint8_t bmTransferAttributes,
451                                          char TermChar)
452 {
453           W8(header+ 0, MsgID);
454           W8(header+ 1, bTag);
455           W8(header+ 2, ~bTag);
456           W8(header+ 3, 0);
457         WL32(header+ 4, TransferSize);
458           W8(header+ 8, bmTransferAttributes);
459           W8(header+ 9, TermChar);
460         WL16(header+10, 0);
461 }
462
463 static int usbtmc_bulk_in_header_read(void *header, uint8_t MsgID,
464                                       unsigned char bTag,
465                                       int32_t *TransferSize,
466                                       uint8_t *bmTransferAttributes)
467 {
468         if (R8(header+0) != MsgID ||
469             R8(header+1) != bTag  ||
470             R8(header+2) != (unsigned char)~bTag)
471                 return SR_ERR;
472         if (TransferSize)
473                 *TransferSize = RL32(header+4);
474         if (bmTransferAttributes)
475                 *bmTransferAttributes = R8(header+8);
476         return SR_OK;
477 }
478
479 static int scpi_usbtmc_bulkout(struct scpi_usbtmc_libusb *uscpi,
480                                uint8_t msg_id, const void *data, int32_t size,
481                                uint8_t transfer_attributes)
482 {
483         struct sr_usb_dev_inst *usb = uscpi->usb;
484         int padded_size, ret, transferred;
485
486         if (data && size+USBTMC_BULK_HEADER_SIZE+3 > (int)sizeof(uscpi->buffer)) {
487                 sr_err("USBTMC bulk out transfer is too big.");
488                 return SR_ERR;
489         }
490
491         uscpi->bTag++;
492         uscpi->bTag += !uscpi->bTag;  /* bTag == 0 is invalid so avoid it. */
493
494         usbtmc_bulk_out_header_write(uscpi->buffer, msg_id, uscpi->bTag,
495                                      size, transfer_attributes, 0);
496         if (data)
497                 memcpy(uscpi->buffer+USBTMC_BULK_HEADER_SIZE, data, size);
498         else
499                 size = 0;
500         size += USBTMC_BULK_HEADER_SIZE;
501         padded_size = (size + 3) & ~0x3;
502         memset(uscpi->buffer+size, 0, padded_size - size);
503
504         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_out_ep,
505                                    uscpi->buffer, padded_size, &transferred,
506                                    TRANSFER_TIMEOUT);
507         if (ret < 0) {
508                 sr_err("USBTMC bulk out transfer error: %s.",
509                        libusb_error_name(ret));
510                 return SR_ERR;
511         }
512
513         if (transferred < padded_size) {
514                 sr_dbg("USBTMC bulk out partial transfer (%d/%d bytes).",
515                        transferred, padded_size);
516                 return SR_ERR;
517         }
518
519         return transferred - USBTMC_BULK_HEADER_SIZE;
520 }
521
522 static int scpi_usbtmc_bulkin_start(struct scpi_usbtmc_libusb *uscpi,
523                                     uint8_t msg_id, void *data, int32_t size,
524                                     uint8_t *transfer_attributes)
525 {
526         struct sr_usb_dev_inst *usb = uscpi->usb;
527         int ret, transferred, message_size;
528
529         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
530                                    &transferred, TRANSFER_TIMEOUT);
531         if (ret < 0) {
532                 sr_err("USBTMC bulk in transfer error: %s.",
533                        libusb_error_name(ret));
534                 return SR_ERR;
535         }
536
537         if (usbtmc_bulk_in_header_read(data, msg_id, uscpi->bTag, &message_size,
538                                        transfer_attributes) != SR_OK) {
539                 sr_err("USBTMC invalid bulk in header.");
540                 return SR_ERR;
541         }
542
543         message_size += USBTMC_BULK_HEADER_SIZE;
544         uscpi->response_length = MIN(transferred, message_size);
545         uscpi->response_bytes_read = USBTMC_BULK_HEADER_SIZE;
546         uscpi->remaining_length = message_size - uscpi->response_length;
547
548         return transferred - USBTMC_BULK_HEADER_SIZE;
549 }
550
551 static int scpi_usbtmc_bulkin_continue(struct scpi_usbtmc_libusb *uscpi,
552                                        void *data, int size)
553 {
554         struct sr_usb_dev_inst *usb = uscpi->usb;
555         int ret, transferred;
556
557         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
558                                    &transferred, TRANSFER_TIMEOUT);
559         if (ret < 0) {
560                 sr_err("USBTMC bulk in transfer error: %s.",
561                        libusb_error_name(ret));
562                 return SR_ERR;
563         }
564
565         uscpi->response_length = MIN(transferred, uscpi->remaining_length);
566         uscpi->response_bytes_read = 0;
567         uscpi->remaining_length -= uscpi->response_length;
568
569         return transferred;
570 }
571
572 static int scpi_usbtmc_libusb_send(void *priv, const char *command)
573 {
574         struct scpi_usbtmc_libusb *uscpi = priv;
575
576         if (scpi_usbtmc_bulkout(uscpi, DEV_DEP_MSG_OUT,
577                                 command, strlen(command), EOM) <= 0)
578                 return SR_ERR;
579
580         sr_spew("Successfully sent SCPI command: '%s'.", command);
581
582         return SR_OK;
583 }
584
585 static int scpi_usbtmc_libusb_read_begin(void *priv)
586 {
587         struct scpi_usbtmc_libusb *uscpi = priv;
588
589         uscpi->remaining_length = 0;
590
591         if (scpi_usbtmc_bulkout(uscpi, REQUEST_DEV_DEP_MSG_IN,
592             NULL, INT32_MAX, 0) < 0)
593                 return SR_ERR;
594         if (scpi_usbtmc_bulkin_start(uscpi, DEV_DEP_MSG_IN,
595                                      uscpi->buffer, sizeof(uscpi->buffer),
596                                      &uscpi->bulkin_attributes) < 0)
597                 return SR_ERR;
598
599         return SR_OK;
600 }
601
602 static int scpi_usbtmc_libusb_read_data(void *priv, char *buf, int maxlen)
603 {
604         struct scpi_usbtmc_libusb *uscpi = priv;
605         int read_length;
606
607         if (uscpi->response_bytes_read >= uscpi->response_length) {
608                 if (uscpi->remaining_length > 0) {
609                         if (scpi_usbtmc_bulkin_continue(uscpi, uscpi->buffer,
610                                                         sizeof(uscpi->buffer)) <= 0)
611                                 return SR_ERR;
612                 } else {
613                         if (uscpi->bulkin_attributes & EOM)
614                                 return SR_ERR;
615                         if (scpi_usbtmc_libusb_read_begin(uscpi) < 0)
616                                 return SR_ERR;
617                 }
618         }
619
620         read_length = MIN(uscpi->response_length - uscpi->response_bytes_read, maxlen);
621
622         memcpy(buf, uscpi->buffer + uscpi->response_bytes_read, read_length);
623
624         uscpi->response_bytes_read += read_length;
625
626         return read_length;
627 }
628
629 static int scpi_usbtmc_libusb_read_complete(void *priv)
630 {
631         struct scpi_usbtmc_libusb *uscpi = priv;
632         return uscpi->response_bytes_read >= uscpi->response_length &&
633                uscpi->remaining_length <= 0 &&
634                uscpi->bulkin_attributes & EOM;
635 }
636
637 static int scpi_usbtmc_libusb_close(struct sr_scpi_dev_inst *scpi)
638 {
639         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
640         struct sr_usb_dev_inst *usb = uscpi->usb;
641         int ret;
642
643         if (!usb->devhdl)
644                 return SR_ERR;
645
646         if (!uscpi->rigol_ds1000) {
647         if ((ret = libusb_clear_halt(usb->devhdl, uscpi->bulk_in_ep)) < 0)
648                 sr_err("Failed to clear halt/stall condition for EP %d: %s.",
649                        uscpi->bulk_in_ep, libusb_error_name(ret));
650         if ((ret = libusb_clear_halt(usb->devhdl, uscpi->bulk_out_ep)) < 0)
651                 sr_err("Failed to clear halt/stall condition for EP %d: %s.",
652                        uscpi->bulk_out_ep, libusb_error_name(ret));
653         if ((ret = libusb_clear_halt(usb->devhdl, uscpi->interrupt_ep)) < 0)
654                 sr_err("Failed to clear halt/stall condition for EP %d: %s.",
655                        uscpi->interrupt_ep, libusb_error_name(ret));
656         }
657
658         scpi_usbtmc_local(uscpi);
659
660         if ((ret = libusb_release_interface(usb->devhdl, uscpi->interface)) < 0)
661                 sr_err("Failed to release interface: %s.",
662                        libusb_error_name(ret));
663         
664         if (uscpi->detached_kernel_driver) {
665                 if ((ret = libusb_attach_kernel_driver(usb->devhdl,
666                                                 uscpi->interface)) < 0)
667                         sr_err("Failed to re-attach kernel driver: %s.",
668                                libusb_error_name(ret));
669
670                 uscpi->detached_kernel_driver = 0;
671         }
672         sr_usb_close(usb);
673
674         return SR_OK;
675 }
676
677 static void scpi_usbtmc_libusb_free(void *priv)
678 {
679         struct scpi_usbtmc_libusb *uscpi = priv;
680         sr_usb_dev_inst_free(uscpi->usb);
681 }
682
683 SR_PRIV const struct sr_scpi_dev_inst scpi_usbtmc_libusb_dev = {
684         .name          = "USBTMC",
685         .prefix        = "usbtmc",
686         .priv_size     = sizeof(struct scpi_usbtmc_libusb),
687         .scan          = scpi_usbtmc_libusb_scan,
688         .dev_inst_new  = scpi_usbtmc_libusb_dev_inst_new,
689         .open          = scpi_usbtmc_libusb_open,
690         .source_add    = scpi_usbtmc_libusb_source_add,
691         .source_remove = scpi_usbtmc_libusb_source_remove,
692         .send          = scpi_usbtmc_libusb_send,
693         .read_begin    = scpi_usbtmc_libusb_read_begin,
694         .read_data     = scpi_usbtmc_libusb_read_data,
695         .read_complete = scpi_usbtmc_libusb_read_complete,
696         .close         = scpi_usbtmc_libusb_close,
697         .free          = scpi_usbtmc_libusb_free,
698 };