]> sigrok.org Git - libsigrok.git/blob - hardware/common/scpi_usbtmc_libusb.c
scpi: add a libusb based implementation of usbtmc
[libsigrok.git] / hardware / common / 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 <string.h>
21 #include "libsigrok.h"
22 #include "libsigrok-internal.h"
23
24 #define LOG_PREFIX "scpi_usbtmc"
25
26 #define MAX_TRANSFER_LENGTH 2048
27 #define TRANSFER_TIMEOUT 1000
28
29 struct scpi_usbtmc_libusb {
30         struct sr_context *ctx;
31         struct sr_usb_dev_inst *usb;
32         int detached_kernel_driver;
33         uint8_t interface;
34         uint8_t bulk_in_ep;
35         uint8_t bulk_out_ep;
36         uint8_t interrupt_ep;
37         uint8_t usbtmc_int_cap;
38         uint8_t usbtmc_dev_cap;
39         uint8_t usb488_dev_cap;
40         uint8_t bTag;
41         uint8_t bulkin_attributes;
42         uint8_t buffer[MAX_TRANSFER_LENGTH];
43         int response_length;
44         int response_bytes_read;
45         int remaining_length;
46 };
47
48 /* Some USBTMC-specific enums, as defined in the USBTMC standard. */
49 #define SUBCLASS_USBTMC  0x03
50 #define USBTMC_USB488    0x01
51
52 enum {
53         /* USBTMC control requests */
54         INITIATE_ABORT_BULK_OUT     =   1,
55         CHECK_ABORT_BULK_OUT_STATUS =   2,
56         INITIATE_ABORT_BULK_IN      =   3,
57         CHECK_ABORT_BULK_IN_STATUS  =   4,
58         INITIATE_CLEAR              =   5,
59         CHECK_CLEAR_STATUS          =   6,
60         GET_CAPABILITIES            =   7,
61         INDICATOR_PULSE             =  64,
62
63         /* USB488 control requests */
64         READ_STATUS_BYTE            = 128,
65         REN_CONTROL                 = 160,
66         GO_TO_LOCAL                 = 161,
67         LOCAL_LOCKOUT               = 162,
68 };
69
70 /* USBTMC capabilities */
71 #define USBTMC_INT_CAP_LISTEN_ONLY 0x01
72 #define USBTMC_INT_CAP_TALK_ONLY   0x02
73 #define USBTMC_INT_CAP_INDICATOR   0x04
74
75 #define USBTMC_DEV_CAP_TERMCHAR    0x01
76
77 #define USB488_DEV_CAP_DT1         0x01
78 #define USB488_DEV_CAP_RL1         0x02
79 #define USB488_DEV_CAP_SR1         0x04
80 #define USB488_DEV_CAP_SCPI        0x08
81
82 /* Bulk messages constants */
83 #define USBTMC_BULK_HEADER_SIZE  12
84
85 /* Bulk MsgID values */
86 #define DEV_DEP_MSG_OUT         1
87 #define REQUEST_DEV_DEP_MSG_IN  2
88 #define DEV_DEP_MSG_IN          2
89
90 /* bmTransferAttributes */
91 #define EOM                0x01
92 #define TERM_CHAR_ENABLED  0x02
93
94
95 static GSList *scpi_usbtmc_libusb_scan(struct drv_context *drvc)
96 {
97         struct libusb_device **devlist;
98         struct libusb_device_descriptor des;
99         struct libusb_config_descriptor *confdes;
100         const struct libusb_interface_descriptor *intfdes;
101         GSList *resources = NULL;
102         int confidx, intfidx, ret, i;
103         char *res;
104
105         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
106         for (i = 0; devlist[i]; i++) {
107                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
108                         sr_err("Failed to get device descriptor: %s.",
109                                libusb_error_name(ret));
110                         continue;
111                 }
112
113                 for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
114                         if (libusb_get_config_descriptor(devlist[i], confidx, &confdes) != 0) {
115                                 sr_err("Failed to get configuration descriptor.");
116                                 break;
117                         }
118                         for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
119                                 intfdes = confdes->interface[intfidx].altsetting;
120                                 if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
121                                     intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
122                                     intfdes->bInterfaceProtocol != USBTMC_USB488)
123                                         continue;
124                                 sr_dbg("Found USBTMC device (VID:PID = %04x:%04x, "
125                                        "bus.address = %d.%d).", des.idVendor, des.idProduct,
126                                        libusb_get_bus_number(devlist[i]),
127                                        libusb_get_device_address(devlist[i]));
128                                 res = g_strdup_printf("usbtmc/%d.%d",
129                                                       libusb_get_bus_number(devlist[i]),
130                                                       libusb_get_device_address(devlist[i]));
131                                 resources = g_slist_append(resources, res);
132                         }
133                         libusb_free_config_descriptor(confdes);
134                 }
135         }
136         libusb_free_device_list(devlist, 1);
137
138         sr_dbg("Found %d device(s).", g_slist_length(resources));
139
140         return resources;
141 }
142
143 static int scpi_usbtmc_libusb_dev_inst_new(void *priv, struct drv_context *drvc,
144                 const char *resource, char **params, const char *serialcomm)
145 {
146         struct scpi_usbtmc_libusb *uscpi = priv;
147         GSList *devices;
148
149         (void)resource;
150         (void)serialcomm;
151
152         if (!params || !params[1]) {
153                 sr_err("Invalid parameters.");
154                 return SR_ERR;
155         }
156
157         uscpi->ctx = drvc->sr_ctx;
158         devices = sr_usb_find(uscpi->ctx->libusb_ctx, params[1]);
159         if (g_slist_length(devices) != 1) {
160                 sr_err("Failed to find USB device '%s'.", params[1]);
161                 g_slist_free_full(devices, (GDestroyNotify)sr_usb_dev_inst_free);
162                 return SR_ERR;
163         }
164         uscpi->usb = devices->data;
165         g_slist_free(devices);
166
167         return SR_OK;
168 }
169
170 static int scpi_usbtmc_libusb_open(void *priv)
171 {
172         struct scpi_usbtmc_libusb *uscpi = priv;
173         struct sr_usb_dev_inst *usb = uscpi->usb;
174         struct libusb_device *dev;
175         struct libusb_device_descriptor des;
176         struct libusb_config_descriptor *confdes;
177         const struct libusb_interface_descriptor *intfdes;
178         const struct libusb_endpoint_descriptor *ep;
179         int confidx, intfidx, epidx, config = 0;
180         uint8_t capabilities[24];
181         int ret, found = 0;
182
183         if (usb->devhdl)
184                 return SR_OK;
185
186         if (sr_usb_open(uscpi->ctx->libusb_ctx, usb) != SR_OK)
187                 return SR_ERR;
188
189         dev = libusb_get_device(usb->devhdl);
190         if ((ret = libusb_get_device_descriptor(dev, &des))) {
191                 sr_err("Failed to get device descriptor: %s.",
192                        libusb_error_name(ret));
193                 return SR_ERR;
194         }
195
196         for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
197                 if (libusb_get_config_descriptor(dev, confidx, &confdes) != 0) {
198                         sr_err("Failed to get configuration descriptor.");
199                         continue;
200                 }
201                 for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
202                         intfdes = confdes->interface[intfidx].altsetting;
203                         if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
204                             intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
205                             intfdes->bInterfaceProtocol != USBTMC_USB488)
206                                 continue;
207                         uscpi->interface = intfdes->bInterfaceNumber;
208                         sr_dbg("Interface %d", uscpi->interface);
209                         config = confdes->bConfigurationValue;
210                         sr_dbg("Configuration %d", config);
211                         for (epidx = 0; epidx < intfdes->bNumEndpoints; epidx++) {
212                                 ep = &intfdes->endpoint[epidx];
213                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
214                                     !(ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK))) {
215                                         uscpi->bulk_out_ep = ep->bEndpointAddress;
216                                         sr_dbg("Bulk OUT EP %d", uscpi->bulk_out_ep);
217                                 }
218                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
219                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
220                                         uscpi->bulk_in_ep = ep->bEndpointAddress;
221                                         sr_dbg("Bulk IN EP %d", uscpi->bulk_in_ep);
222                                 }
223                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT &&
224                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
225                                         uscpi->interrupt_ep = ep->bEndpointAddress;
226                                         sr_dbg("Interrupt EP %d", uscpi->interrupt_ep);
227                                 }
228                         }
229                         found = 1;
230                 }
231                 libusb_free_config_descriptor(confdes);
232                 if (found)
233                         break;
234         }
235
236         if (!found) {
237                 sr_err("Failed to find USBTMC interface");
238                 return SR_ERR;
239         }
240
241         if (libusb_kernel_driver_active(usb->devhdl, uscpi->interface) == 1) {
242                 if ((ret = libusb_detach_kernel_driver(usb->devhdl,
243                                                        uscpi->interface)) < 0) {
244                         sr_err("failed to detach kernel driver: %s",
245                                         libusb_error_name(ret));
246                         return SR_ERR;
247                 }
248                 uscpi->detached_kernel_driver = 1;
249         }
250
251         if ((ret = libusb_set_configuration(usb->devhdl, config))) {
252                 sr_err("Failed to set configuration: %s.", libusb_error_name(ret));
253                 return SR_ERR;
254         }
255
256         if ((ret = libusb_claim_interface(usb->devhdl, uscpi->interface))) {
257                 sr_err("Failed to claim interface: %s.", libusb_error_name(ret));
258                 return SR_ERR;
259         }
260
261         libusb_clear_halt(usb->devhdl, uscpi->bulk_in_ep);
262         libusb_clear_halt(usb->devhdl, uscpi->bulk_out_ep);
263         libusb_clear_halt(usb->devhdl, uscpi->interrupt_ep);
264
265         /* get capabilities */
266         ret = libusb_control_transfer(usb->devhdl,
267                                       LIBUSB_ENDPOINT_IN         |
268                                       LIBUSB_REQUEST_TYPE_CLASS  |
269                                       LIBUSB_RECIPIENT_INTERFACE,
270                                       GET_CAPABILITIES, 0,
271                                       uscpi->interface,
272                                       capabilities, sizeof(capabilities),
273                                       TRANSFER_TIMEOUT);
274         if (ret == sizeof(capabilities)) {
275                 uscpi->usbtmc_int_cap = capabilities[ 4];
276                 uscpi->usbtmc_dev_cap = capabilities[ 5];
277                 uscpi->usb488_dev_cap = capabilities[15];
278         }
279         sr_dbg("device capabilities: %s%s%s%s%s, %s, %s",
280                uscpi->usb488_dev_cap & USB488_DEV_CAP_SCPI       ? "SCPI, "    : "",
281                uscpi->usbtmc_dev_cap & USBTMC_DEV_CAP_TERMCHAR   ? "TermChar, ": "",
282                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? "L3, " :
283                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? ""     : "L4, ",
284                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? "T5, " :
285                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? ""     : "T6, ",
286                uscpi->usb488_dev_cap & USB488_DEV_CAP_SR1        ? "SR1"  : "SR0",
287                uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1        ? "RL1"  : "RL0",
288                uscpi->usb488_dev_cap & USB488_DEV_CAP_DT1        ? "DT1"  : "DT0");
289
290         return SR_OK;
291 }
292
293 static int scpi_usbtmc_libusb_source_add(void *priv, int events, int timeout,
294                         sr_receive_data_callback_t cb, void *cb_data)
295 {
296         struct scpi_usbtmc_libusb *uscpi = priv;
297         (void)events;
298         return usb_source_add(uscpi->ctx, timeout, cb, cb_data);
299 }
300
301 static int scpi_usbtmc_libusb_source_remove(void *priv)
302 {
303         struct scpi_usbtmc_libusb *uscpi = priv;
304         return usb_source_remove(uscpi->ctx);
305 }
306
307 static void usbtmc_bulk_out_header_write(void *header, uint8_t MsgID,
308                                          uint8_t bTag,
309                                          uint32_t TransferSize,
310                                          uint8_t bmTransferAttributes,
311                                          char TermChar)
312 {
313           W8(header+ 0, MsgID);
314           W8(header+ 1, bTag);
315           W8(header+ 2, ~bTag);
316           W8(header+ 3, 0);
317         WL32(header+ 4, TransferSize);
318           W8(header+ 8, bmTransferAttributes);
319           W8(header+ 9, TermChar);
320         WL16(header+10, 0);
321 }
322
323 static int usbtmc_bulk_in_header_read(void *header, uint8_t MsgID,
324                                       unsigned char bTag,
325                                       int32_t *TransferSize,
326                                       uint8_t *bmTransferAttributes)
327 {
328         if (R8(header+0) != MsgID ||
329             R8(header+1) != bTag  ||
330             R8(header+2) != (unsigned char)~bTag)
331                 return SR_ERR;
332         if (TransferSize)
333                 *TransferSize = RL32(header+4);
334         if (bmTransferAttributes)
335                 *bmTransferAttributes = R8(header+8);
336         return SR_OK;
337 }
338
339 static int scpi_usbtmc_bulkout(struct scpi_usbtmc_libusb *uscpi,
340                                uint8_t msg_id, const void *data, int32_t size,
341                                uint8_t transfer_attributes)
342 {
343         struct sr_usb_dev_inst *usb = uscpi->usb;
344         int padded_size, ret, transferred;
345
346         if (data && size+USBTMC_BULK_HEADER_SIZE+3 > (int)sizeof(uscpi->buffer)) {
347                 sr_err("USBTMC bulk out transfer too big");
348                 return SR_ERR;
349         }
350
351         uscpi->bTag++;
352         uscpi->bTag += !uscpi->bTag;  /* bTag == 0 is invalid so avoid it */
353
354         usbtmc_bulk_out_header_write(uscpi->buffer, msg_id, uscpi->bTag,
355                                      size, transfer_attributes, 0);
356         if (data)
357                 memcpy(uscpi->buffer+USBTMC_BULK_HEADER_SIZE, data, size);
358         else
359                 size = 0;
360         size += USBTMC_BULK_HEADER_SIZE;
361         padded_size = (size + 3) & ~0x3;
362         memset(uscpi->buffer+size, 0, padded_size - size);
363
364         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_out_ep,
365                                    uscpi->buffer, padded_size, &transferred,
366                                    TRANSFER_TIMEOUT);
367         if (ret) {
368                 sr_err("USBTMC bulk out transfer error: %d", ret);
369                 return SR_ERR;
370         }
371
372         if (transferred < padded_size) {
373                 sr_dbg("USBTMC bulkout partial transfer (%d/%d bytes)",
374                        transferred, padded_size);
375                 return SR_ERR;
376         }
377
378         return transferred - USBTMC_BULK_HEADER_SIZE;
379 }
380
381 static int scpi_usbtmc_bulkin_start(struct scpi_usbtmc_libusb *uscpi,
382                                     uint8_t msg_id, void *data, int32_t size,
383                                     uint8_t *transfer_attributes)
384 {
385         struct sr_usb_dev_inst *usb = uscpi->usb;
386         int ret, transferred, message_size;
387
388         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
389                                    &transferred, TRANSFER_TIMEOUT);
390         if (ret) {
391                 sr_err("USBTMC bulk in transfer error: %d", ret);
392                 return SR_ERR;
393         }
394
395         if (usbtmc_bulk_in_header_read(data, msg_id, uscpi->bTag, &message_size,
396                                        transfer_attributes) != SR_OK) {
397                 sr_err("USBTMC invalid bulk in header");
398                 return SR_ERR;
399         }
400
401         message_size += USBTMC_BULK_HEADER_SIZE;
402         uscpi->response_length = MIN(transferred, message_size);
403         uscpi->response_bytes_read = USBTMC_BULK_HEADER_SIZE;
404         uscpi->remaining_length = message_size - uscpi->response_length;
405
406         return transferred - USBTMC_BULK_HEADER_SIZE;
407 }
408
409 static int scpi_usbtmc_bulkin_continue(struct scpi_usbtmc_libusb *uscpi,
410                                        void *data, int size)
411 {
412         struct sr_usb_dev_inst *usb = uscpi->usb;
413         int ret, transferred;
414
415         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
416                                    &transferred, TRANSFER_TIMEOUT);
417         if (ret) {
418                 sr_err("USBTMC bulk in transfer error: %d", ret);
419                 return SR_ERR;
420         }
421
422         uscpi->response_length = MIN(transferred, uscpi->remaining_length);
423         uscpi->response_bytes_read = 0;
424         uscpi->remaining_length -= uscpi->response_length;
425
426         return transferred;
427 }
428
429 static int scpi_usbtmc_libusb_send(void *priv, const char *command)
430 {
431         struct scpi_usbtmc_libusb *uscpi = priv;
432
433         if (scpi_usbtmc_bulkout(uscpi, DEV_DEP_MSG_OUT,
434                                 command, strlen(command), EOM) <= 0)
435                 return SR_ERR;
436
437         sr_spew("Successfully sent SCPI command: '%s'.", command);
438
439         return SR_OK;
440 }
441
442 static int scpi_usbtmc_libusb_read_begin(void *priv)
443 {
444         struct scpi_usbtmc_libusb *uscpi = priv;
445
446         uscpi->remaining_length = 0;
447
448         if (scpi_usbtmc_bulkout(uscpi, REQUEST_DEV_DEP_MSG_IN,
449             NULL, INT32_MAX, 0) < 0)
450                 return SR_ERR;
451         if (scpi_usbtmc_bulkin_start(uscpi, DEV_DEP_MSG_IN,
452                                      uscpi->buffer, sizeof(uscpi->buffer),
453                                      &uscpi->bulkin_attributes) < 0)
454                 return SR_ERR;
455
456         return SR_OK;
457 }
458
459 static int scpi_usbtmc_libusb_read_data(void *priv, char *buf, int maxlen)
460 {
461         struct scpi_usbtmc_libusb *uscpi = priv;
462         int read_length;
463
464         if (uscpi->response_bytes_read >= uscpi->response_length) {
465                 if (uscpi->remaining_length > 0) {
466                         if (scpi_usbtmc_bulkin_continue(uscpi, uscpi->buffer,
467                                                         sizeof(uscpi->buffer)) <= 0)
468                                 return SR_ERR;
469                 } else {
470                         if (uscpi->bulkin_attributes & EOM)
471                                 return SR_ERR;
472                         if (scpi_usbtmc_libusb_read_begin(uscpi) < 0)
473                                 return SR_ERR;
474                 }
475         }
476
477         read_length = MIN(uscpi->response_length - uscpi->response_bytes_read, maxlen);
478
479         memcpy(buf, uscpi->buffer + uscpi->response_bytes_read, read_length);
480
481         uscpi->response_bytes_read += read_length;
482
483         return read_length;
484 }
485
486 static int scpi_usbtmc_libusb_read_complete(void *priv)
487 {
488         struct scpi_usbtmc_libusb *uscpi = priv;
489         return uscpi->response_bytes_read >= uscpi->response_length &&
490                uscpi->remaining_length <= 0 &&
491                uscpi->bulkin_attributes & EOM;
492 }
493
494 static int scpi_usbtmc_libusb_close(void *priv)
495 {
496         struct scpi_usbtmc_libusb *uscpi = priv;
497         struct sr_usb_dev_inst *usb = uscpi->usb;
498
499         if (!usb->devhdl)
500                 return SR_ERR;
501
502         libusb_clear_halt(usb->devhdl, uscpi->bulk_in_ep);
503         libusb_clear_halt(usb->devhdl, uscpi->bulk_out_ep);
504         libusb_clear_halt(usb->devhdl, uscpi->interrupt_ep);
505         libusb_release_interface(usb->devhdl, uscpi->interface);
506         if (uscpi->detached_kernel_driver) {
507                 libusb_attach_kernel_driver(usb->devhdl, uscpi->interface);
508                 uscpi->detached_kernel_driver = 0;
509         }
510         libusb_close(usb->devhdl);
511         usb->devhdl = NULL;
512
513         return SR_OK;
514 }
515
516 static void scpi_usbtmc_libusb_free(void *priv)
517 {
518         struct scpi_usbtmc_libusb *uscpi = priv;
519         sr_usb_dev_inst_free(uscpi->usb);
520 }
521
522
523 SR_PRIV const struct sr_scpi_dev_inst scpi_usbtmc_libusb_dev = {
524         .name          = "USBTMC",
525         .prefix        = "usbtmc",
526         .priv_size     = sizeof(struct scpi_usbtmc_libusb),
527         .scan          = scpi_usbtmc_libusb_scan,
528         .dev_inst_new  = scpi_usbtmc_libusb_dev_inst_new,
529         .open          = scpi_usbtmc_libusb_open,
530         .source_add    = scpi_usbtmc_libusb_source_add,
531         .source_remove = scpi_usbtmc_libusb_source_remove,
532         .send          = scpi_usbtmc_libusb_send,
533         .read_begin    = scpi_usbtmc_libusb_read_begin,
534         .read_data     = scpi_usbtmc_libusb_read_data,
535         .read_complete = scpi_usbtmc_libusb_read_complete,
536         .close         = scpi_usbtmc_libusb_close,
537         .free          = scpi_usbtmc_libusb_free,
538 };