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