]> sigrok.org Git - libsigrok.git/blob - src/serial_hid.c
Doxygen: Properly mark a few symbols as private.
[libsigrok.git] / src / serial_hid.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2017-2019 Gerhard Sittig <gerhard.sittig@gmx.net>
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 <glib.h>
22 #ifdef HAVE_LIBHIDAPI
23 #include <hidapi.h>
24 #endif
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
27 #include "serial_hid.h"
28 #include <stdlib.h>
29 #include <string.h>
30 #ifdef G_OS_WIN32
31 #include <windows.h> /* for HANDLE */
32 #endif
33
34 #define LOG_PREFIX "serial-hid"
35
36 #ifdef HAVE_SERIAL_COMM
37
38 /**
39  * @file
40  *
41  * Serial port handling, HIDAPI library specific support code.
42  */
43
44 /**
45  * @defgroup grp_serial_hid Serial port handling, HID group
46  *
47  * Make serial-over-HID communication appear like a regular serial port.
48  *
49  * @{
50  */
51
52 #ifdef HAVE_LIBHIDAPI
53 /* {{{ helper routines */
54
55 /* Strip off parity bits for "odd" data bit counts like in 7e1 frames. */
56 static void ser_hid_mask_databits(struct sr_serial_dev_inst *serial,
57         uint8_t *data, size_t len)
58 {
59         uint32_t mask32;
60         uint8_t mask;
61         size_t idx;
62
63         if ((serial->comm_params.data_bits % 8) == 0)
64                 return;
65
66         mask32 = (1UL << serial->comm_params.data_bits) - 1;
67         mask = mask32 & 0xff;
68         for (idx = 0; idx < len; idx++)
69                 data[idx] &= mask;
70 }
71
72 /* }}} */
73 /* {{{ open/close/list/find HIDAPI connection, exchange HID requests and data */
74
75 /*
76  * Convert a HIDAPI path (which depends on the target platform, and may
77  * depend on one of several available API variants on that platform) to
78  * something that is usable as a "port name" in conn= specs.
79  *
80  * Since conn= is passed with -d where multiple options (among them conn=)
81  * are separated by colons, port names themselves cannot contain colons.
82  *
83  * Just replace colons by a period in the simple case (Linux platform,
84  * hidapi-libusb implementation, bus/address/interface). Prefix the
85  * HIDAPI path in the complex cases (Linux hidapi-hidraw, Windows, Mac).
86  * Paths with colons outside of libusb based implementations are unhandled
87  * here, but were not yet seen on any sigrok supported platform either.
88  * So just reject them.
89  */
90 static char *get_hidapi_path_copy(const char *path)
91 {
92         static const char *accept = "0123456789abcdefABCDEF:";
93         static const char *keep = "0123456789abcdefABCDEF";
94
95         int has_colon;
96         int is_hex_colon;
97         char *name;
98
99         has_colon = strchr(path, ':') != NULL;
100         is_hex_colon = strspn(path, accept) == strlen(path);
101         if (has_colon && !is_hex_colon) {
102                 sr_err("Unsupported HIDAPI path format: %s", path);
103                 return NULL;
104         }
105         if (is_hex_colon) {
106                 name = g_strdup_printf("%s%s", SER_HID_USB_PREFIX, path);
107                 g_strcanon(name + strlen(SER_HID_USB_PREFIX), keep, '.');
108         } else {
109                 name = g_strdup_printf("%s%s", SER_HID_RAW_PREFIX, path);
110         }
111
112         return name;
113 }
114
115 /*
116  * Undo the port name construction that was done during scan. Extract
117  * the HIDAPI path from a conn= input spec (the part after the hid/
118  * prefix and chip type).
119  *
120  * Strip off the "raw" prefix, or undo colon substitution. See @ref
121  * get_hidapi_path_copy() for details.
122  */
123 static const char *extract_hidapi_path(char *buffer)
124 {
125         static const char *keep = "0123456789abcdefABCDEF:";
126
127         const char *p;
128
129         p = buffer;
130         if (!p || !*p)
131                 return NULL;
132
133         if (strncmp(p, SER_HID_RAW_PREFIX, strlen(SER_HID_RAW_PREFIX)) == 0) {
134                 p += strlen(SER_HID_RAW_PREFIX);
135                 return p;
136         }
137         if (strncmp(p, SER_HID_USB_PREFIX, strlen(SER_HID_USB_PREFIX)) == 0) {
138                 p += strlen(SER_HID_USB_PREFIX);
139                 g_strcanon(buffer, keep, ':');
140                 return p;
141         }
142
143         return NULL;
144 }
145
146 /*
147  * The HIDAPI specific list() callback, invoked by common serial.c code.
148  * Enumerate all devices (no VID:PID is involved).
149  * Invoke an 'append' callback with "path" and "name".
150  */
151 static GSList *ser_hid_hidapi_list(GSList *list, sr_ser_list_append_t append)
152 {
153         struct hid_device_info *devs, *curdev;
154         const char *chipname;
155         char *path, *name;
156         wchar_t *manuf, *prod, *serno;
157         uint16_t vid, pid;
158         GString *desc;
159
160         devs = hid_enumerate(0x0000, 0x0000);
161         for (curdev = devs; curdev; curdev = curdev->next) {
162                 /*
163                  * Determine the chip name from VID:PID (if it's one of
164                  * the supported types with an ID known to us).
165                  */
166                 vid = curdev->vendor_id;
167                 pid = curdev->product_id;
168                 chipname = ser_hid_chip_find_name_vid_pid(vid, pid);
169                 if (!chipname)
170                         chipname = "<chip>";
171
172                 /*
173                  * Prefix port names such that open() calls with this
174                  * conn= spec will end up here and contain all details
175                  * that are essential for processing.
176                  */
177                 path = get_hidapi_path_copy(curdev->path);
178                 if (!path)
179                         continue;
180                 name = g_strdup_printf("%s/%s/%s",
181                         SER_HID_CONN_PREFIX, chipname, path);
182                 g_free(path);
183
184                 /*
185                  * Print whatever information was available. Construct
186                  * the description text from pieces. Absence of fields
187                  * is not fatal, we have seen perfectly usable cables
188                  * that only had a VID and PID (permissions were not an
189                  * issue).
190                  */
191                 manuf = curdev->manufacturer_string;
192                 prod = curdev->product_string;
193                 serno = curdev->serial_number;
194                 vid = curdev->vendor_id;
195                 pid = curdev->product_id;
196                 desc = g_string_sized_new(128);
197                 g_string_append_printf(desc, "HID");
198                 if (manuf && wcslen(manuf) != 0)
199                         g_string_append_printf(desc, " %ls", manuf);
200                 if (prod && wcslen(prod) != 0)
201                         g_string_append_printf(desc, " %ls", prod);
202                 if (serno && wcslen(serno) != 0)
203                         g_string_append_printf(desc, " %ls", serno);
204                 if (vid && pid)
205                         g_string_append_printf(desc, " [%04hx.%04hx]", vid, pid);
206                 list = append(list, name, desc->str);
207                 g_string_free(desc, TRUE);
208                 g_free(name);
209         }
210         hid_free_enumeration(devs);
211
212         return list;
213 }
214
215 /*
216  * The HIDAPI specific find_usb() callback, invoked by common serial.c code.
217  * Enumerate devices for the specified VID:PID pair.
218  * Invoke an "append" callback with 'path' for the device.
219  */
220 static GSList *ser_hid_hidapi_find_usb(GSList *list, sr_ser_find_append_t append,
221                 uint16_t vendor_id, uint16_t product_id)
222 {
223         struct hid_device_info *devs, *curdev;
224         const char *name;
225
226         devs = hid_enumerate(vendor_id, product_id);
227         for (curdev = devs; curdev; curdev = curdev->next) {
228                 name = curdev->path;
229                 list = append(list, name);
230         }
231         hid_free_enumeration(devs);
232
233         return list;
234 }
235
236 /* Get the serial number of a device specified by path. */
237 static int ser_hid_hidapi_get_serno(const char *path, char *buf, size_t blen)
238 {
239         char *usbpath;
240         const char *hidpath;
241         hid_device *dev;
242         wchar_t *serno_wch;
243         int rc;
244
245         if (!path || !*path)
246                 return SR_ERR_ARG;
247         usbpath = g_strdup(path);
248         hidpath = extract_hidapi_path(usbpath);
249         dev = hidpath ? hid_open_path(hidpath) : NULL;
250         g_free(usbpath);
251         if (!dev)
252                 return SR_ERR_IO;
253
254         serno_wch = g_malloc0(blen * sizeof(*serno_wch));
255         rc = hid_get_serial_number_string(dev, serno_wch, blen - 1);
256         hid_close(dev);
257         if (rc != 0) {
258                 g_free(serno_wch);
259                 return SR_ERR_IO;
260         }
261
262         snprintf(buf, blen, "%ls", serno_wch);
263         g_free(serno_wch);
264
265         return SR_OK;
266 }
267
268 /* Get the VID and PID of a device specified by path. */
269 static int ser_hid_hidapi_get_vid_pid(const char *path,
270         uint16_t *vid, uint16_t *pid)
271 {
272 #if 0
273         /*
274          * Bummer! It would have been most reliable to just open the
275          * device by the specified path, and grab its VID:PID. But
276          * there is no way to get these parameters, neither in the
277          * HIDAPI itself, nor when cheating and reaching behind the API
278          * and accessing the libusb handle in dirty ways. :(
279          */
280         hid_device *dev;
281
282         if (!path || !*path)
283                 return SR_ERR_ARG;
284         dev = hid_open_path(path);
285         if (!dev)
286                 return SR_ERR_IO;
287         if (vid)
288                 *vid = dev->vendor_id;
289         if (pid)
290                 *pid = dev->product_id;
291         hid_close(dev);
292
293         return SR_OK;
294 #else
295         /*
296          * The fallback approach. Enumerate all devices, compare the
297          * enumerated USB path, and grab the VID:PID. Unfortunately the
298          * caller can provide path specs that differ from enumerated
299          * paths yet mean the same (address the same device). This needs
300          * more attention. Though the specific format of the path and
301          * its meaning are said to be OS specific, which is why we may
302          * not assume anything about it...
303          */
304         char *usbpath;
305         const char *hidpath;
306         struct hid_device_info *devs, *dev;
307         int found;
308
309         usbpath = g_strdup(path);
310         hidpath = extract_hidapi_path(usbpath);
311         if (!hidpath) {
312                 g_free(usbpath);
313                 return SR_ERR_NA;
314         }
315
316         devs = hid_enumerate(0x0000, 0x0000);
317         found = 0;
318         for (dev = devs; dev; dev = dev->next) {
319                 if (strcmp(dev->path, hidpath) != 0)
320                         continue;
321                 if (vid)
322                         *vid = dev->vendor_id;
323                 if (pid)
324                         *pid = dev->product_id;
325                 found = 1;
326                 break;
327         }
328         hid_free_enumeration(devs);
329         g_free(usbpath);
330
331         return found ? SR_OK : SR_ERR_NA;
332 #endif
333 }
334
335 static int ser_hid_hidapi_open_dev(struct sr_serial_dev_inst *serial)
336 {
337         hid_device *hid_dev;
338
339         if (!serial->usb_path || !*serial->usb_path)
340                 return SR_ERR_ARG;
341
342         /*
343          * A path is available, assume that either a GUI or a
344          * user has copied what a previous listing has provided.
345          * Or a scan determined a matching device's USB path.
346          */
347         if (!serial->hid_path)
348                 serial->hid_path = extract_hidapi_path(serial->usb_path);
349         hid_dev = hid_open_path(serial->hid_path);
350         if (!hid_dev) {
351                 serial->hid_path = NULL;
352                 return SR_ERR_IO;
353         }
354
355         serial->hid_dev = hid_dev;
356         hid_set_nonblocking(hid_dev, 1);
357
358         return SR_OK;
359 }
360
361 static void ser_hid_hidapi_close_dev(struct sr_serial_dev_inst *serial)
362 {
363         if (serial->hid_dev) {
364                 hid_close(serial->hid_dev);
365                 serial->hid_dev = NULL;
366                 serial->hid_path = NULL;
367         }
368         g_slist_free_full(serial->hid_source_args, g_free);
369         serial->hid_source_args = NULL;
370 }
371
372 struct hidapi_source_args_t {
373         /* Application callback. */
374         sr_receive_data_callback cb;
375         void *cb_data;
376         /* The serial device, to store RX data. */
377         struct sr_serial_dev_inst *serial;
378 };
379
380 /*
381  * Gets periodically invoked by the glib main loop. "Drives" (checks)
382  * progress of USB communication, and invokes the application's callback
383  * which processes RX data (when some has become available), as well as
384  * handles application level timeouts.
385  */
386 static int hidapi_source_cb(int fd, int revents, void *cb_data)
387 {
388         struct hidapi_source_args_t *args;
389         uint8_t rx_buf[SER_HID_CHUNK_SIZE];
390         int rc;
391
392         args = cb_data;
393
394         /*
395          * Drain receive data which the chip might have pending. This is
396          * "a copy" of the "background part" of ser_hid_read(), without
397          * the timeout support code, and not knowing how much data the
398          * application is expecting.
399          */
400         do {
401                 rc = args->serial->hid_chip_funcs->read_bytes(args->serial,
402                                 rx_buf, sizeof(rx_buf), 0);
403                 if (rc > 0) {
404                         ser_hid_mask_databits(args->serial, rx_buf, rc);
405                         sr_ser_queue_rx_data(args->serial, rx_buf, rc);
406                 }
407         } while (rc > 0);
408
409         /*
410          * When RX data became available (now or earlier), pass this
411          * condition to the application callback. Always periodically
412          * run the application callback, since it handles timeouts and
413          * might carry out other tasks as well like signalling progress.
414          */
415         if (sr_ser_has_queued_data(args->serial))
416                 revents |= G_IO_IN;
417         rc = args->cb(fd, revents, args->cb_data);
418
419         return rc;
420 }
421
422 #define WITH_MAXIMUM_TIMEOUT_VALUE      10
423 static int ser_hid_hidapi_setup_source_add(struct sr_session *session,
424         struct sr_serial_dev_inst *serial, int events, int timeout,
425         sr_receive_data_callback cb, void *cb_data)
426 {
427         struct hidapi_source_args_t *args;
428         int rc;
429
430         (void)events;
431
432         /* Optionally enforce a minimum poll period. */
433         if (WITH_MAXIMUM_TIMEOUT_VALUE && timeout > WITH_MAXIMUM_TIMEOUT_VALUE)
434                 timeout = WITH_MAXIMUM_TIMEOUT_VALUE;
435
436         /* Allocate status container for background data reception. */
437         args = g_malloc0(sizeof(*args));
438         args->cb = cb;
439         args->cb_data = cb_data;
440         args->serial = serial;
441
442         /*
443          * Have a periodic timer installed. Register the allocated block
444          * with the serial device, since the GSource's finalizer won't
445          * free the memory, and we haven't bothered to create a custom
446          * HIDAPI specific GSource.
447          */
448         rc = sr_session_source_add(session, -1, events, timeout,
449                         hidapi_source_cb, args);
450         if (rc != SR_OK) {
451                 g_free(args);
452                 return rc;
453         }
454         serial->hid_source_args = g_slist_append(serial->hid_source_args, args);
455
456         return SR_OK;
457 }
458
459 static int ser_hid_hidapi_setup_source_remove(struct sr_session *session,
460         struct sr_serial_dev_inst *serial)
461 {
462         (void)serial;
463
464         (void)sr_session_source_remove(session, -1);
465         /*
466          * Release callback args here already? Can there be more than
467          * one source registered at any time, given that we pass fd -1
468          * which is used as the key for the session?
469          */
470
471         return SR_OK;
472 }
473
474 SR_PRIV int ser_hid_hidapi_get_report(struct sr_serial_dev_inst *serial,
475         uint8_t *data, size_t len)
476 {
477         int rc;
478
479         rc = hid_get_feature_report(serial->hid_dev, data, len);
480         if (rc < 0)
481                 return SR_ERR_IO;
482
483         return rc;
484 }
485
486 SR_PRIV int ser_hid_hidapi_set_report(struct sr_serial_dev_inst *serial,
487         const uint8_t *data, size_t len)
488 {
489         int rc;
490         const wchar_t *err_text;
491
492         rc = hid_send_feature_report(serial->hid_dev, data, len);
493         if (rc < 0) {
494                 err_text = hid_error(serial->hid_dev);
495                 sr_dbg("%s() hidapi error: %ls", __func__, err_text);
496                 return SR_ERR_IO;
497         }
498
499         return rc;
500 }
501
502 SR_PRIV int ser_hid_hidapi_get_data(struct sr_serial_dev_inst *serial,
503         uint8_t ep, uint8_t *data, size_t len, int timeout)
504 {
505         int rc;
506
507         (void)ep;
508
509         if (timeout)
510                 rc = hid_read_timeout(serial->hid_dev, data, len, timeout);
511         else
512                 rc = hid_read(serial->hid_dev, data, len);
513         if (rc < 0)
514                 return SR_ERR_IO;
515         if (rc == 0)
516                 return 0;
517
518         return rc;
519 }
520
521 SR_PRIV int ser_hid_hidapi_set_data(struct sr_serial_dev_inst *serial,
522         uint8_t ep, const uint8_t *data, size_t len, int timeout)
523 {
524         int rc;
525
526         (void)ep;
527         (void)timeout;
528
529         rc = hid_write(serial->hid_dev, data, len);
530         if (rc < 0)
531                 return SR_ERR_IO;
532
533         return rc;
534 }
535
536 /* }}} */
537 /* {{{ support for serial-over-HID chips */
538
539 static struct ser_hid_chip_functions **chips[SER_HID_CHIP_LAST] = {
540         [SER_HID_CHIP_UNKNOWN] = NULL,
541         [SER_HID_CHIP_BTC_BU86X] = &ser_hid_chip_funcs_bu86x,
542         [SER_HID_CHIP_SIL_CP2110] = &ser_hid_chip_funcs_cp2110,
543         [SER_HID_CHIP_VICTOR_DMM] = &ser_hid_chip_funcs_victor,
544         [SER_HID_CHIP_WCH_CH9325] = &ser_hid_chip_funcs_ch9325,
545 };
546
547 static struct ser_hid_chip_functions *get_hid_chip_funcs(enum ser_hid_chip_t chip)
548 {
549         struct ser_hid_chip_functions *funcs;
550
551         if (chip >= ARRAY_SIZE(chips))
552                 return NULL;
553         if (!chips[chip])
554                 return NULL;
555         funcs = *chips[chip];
556         if (!funcs)
557                 return NULL;
558
559         return funcs;
560 }
561
562 static int ser_hid_setup_funcs(struct sr_serial_dev_inst *serial)
563 {
564
565         if (!serial)
566                 return -1;
567
568         if (serial->hid_chip && !serial->hid_chip_funcs) {
569                 serial->hid_chip_funcs = get_hid_chip_funcs(serial->hid_chip);
570                 if (!serial->hid_chip_funcs)
571                         return -1;
572         }
573
574         return 0;
575 }
576
577 /*
578  * Takes a pointer to the chip spec with potentially trailing data,
579  * returns the chip index and advances the spec pointer upon match,
580  * returns SER_HID_CHIP_UNKNOWN upon mismatch.
581  */
582 static enum ser_hid_chip_t ser_hid_chip_find_enum(const char **spec_p)
583 {
584         const gchar *spec;
585         enum ser_hid_chip_t idx;
586         struct ser_hid_chip_functions *desc;
587
588         if (!spec_p || !*spec_p)
589                 return SER_HID_CHIP_UNKNOWN;
590         spec = *spec_p;
591         if (!*spec)
592                 return SER_HID_CHIP_UNKNOWN;
593         for (idx = 0; idx < SER_HID_CHIP_LAST; idx++) {
594                 desc = get_hid_chip_funcs(idx);
595                 if (!desc)
596                         continue;
597                 if (!desc->chipname)
598                         continue;
599                 if (!g_str_has_prefix(spec, desc->chipname))
600                         continue;
601                 spec += strlen(desc->chipname);
602                 *spec_p = spec;
603                 return idx;
604         }
605
606         return SER_HID_CHIP_UNKNOWN;
607 }
608
609 /* See if we can find a chip name for a VID:PID spec. */
610 SR_PRIV const char *ser_hid_chip_find_name_vid_pid(uint16_t vid, uint16_t pid)
611 {
612         size_t chip_idx;
613         struct ser_hid_chip_functions *desc;
614         const struct vid_pid_item *vid_pids;
615
616         for (chip_idx = 0; chip_idx < SER_HID_CHIP_LAST; chip_idx++) {
617                 desc = get_hid_chip_funcs(chip_idx);
618                 if (!desc)
619                         continue;
620                 if (!desc->chipname)
621                         continue;
622                 vid_pids = desc->vid_pid_items;
623                 if (!vid_pids)
624                         continue;
625                 while (vid_pids->vid) {
626                         if (vid_pids->vid == vid && vid_pids->pid == pid)
627                                 return desc->chipname;
628                         vid_pids++;
629                 }
630         }
631
632         return NULL;
633 }
634
635 /**
636  * See if a text string is a valid USB path for a HID device.
637  * @param[in] serial The serial port that is about to get opened.
638  * @param[in] path The (assumed) USB path specification.
639  * @return SR_OK upon success, SR_ERR* upon failure.
640  */
641 static int try_open_path(struct sr_serial_dev_inst *serial, const char *path)
642 {
643         int rc;
644
645         serial->usb_path = g_strdup(path);
646         rc = ser_hid_hidapi_open_dev(serial);
647         ser_hid_hidapi_close_dev(serial);
648         g_free(serial->usb_path);
649         serial->usb_path = NULL;
650
651         return rc;
652 }
653
654 /**
655  * Parse conn= specs for serial over HID communication.
656  *
657  * @param[in] serial The serial port that is about to get opened.
658  * @param[in] spec The caller provided conn= specification.
659  * @param[out] chip_ref Pointer to a chip type (enum).
660  * @param[out] path_ref Pointer to a USB path (text string).
661  * @param[out] serno_ref Pointer to a serial number (text string).
662  *
663  * @return 0 upon success, non-zero upon failure. Fills the *_ref output
664  * values.
665  *
666  * Summary of parsing rules as they are implemented:
667  * - Insist on the "hid" prefix. Accept "hid" alone without any other
668  *   additional field.
669  * - The first field that follows can be a chip spec, yet is optional.
670  * - Any other field is assumed to be either a USB path or a serial
671  *   number. There is no point in specifying both of these, as either
672  *   of them uniquely identifies a device.
673  *
674  * Supported formats resulting from these rules:
675  *   hid[/<chip>]
676  *   hid[/<chip>]/usb=<bus>.<dev>[.<if>]
677  *   hid[/<chip>]/raw=<path>    (may contain slashes!)
678  *   hid[/<chip>]/sn=serno
679  *
680  * This routine just parses the conn= spec, which either was provided by
681  * a user, or may reflect (cite) an item of a previously gathered listing
682  * (clipboard provided by CLI clients, or selected from a GUI form).
683  * Another routine will fill in the blanks, and do the cable selection
684  * when a filter was specified.
685  *
686  * Users will want to use short forms when they need to come up with the
687  * specs by themselves. The "verbose" or seemingly redundant forms (chip
688  * _and_ path/serno spec) are useful when the cable uses non-standard or
689  * not-yet-supported VID:PID items when automatic chip detection fails.
690  */
691 static int ser_hid_parse_conn_spec(
692         struct sr_serial_dev_inst *serial, const char *spec,
693         enum ser_hid_chip_t *chip_ref, char **path_ref, char **serno_ref)
694 {
695         const char *p;
696         enum ser_hid_chip_t chip;
697         char *path, *serno;
698         int rc;
699
700         if (chip_ref)
701                 *chip_ref = SER_HID_CHIP_UNKNOWN;
702         if (path_ref)
703                 *path_ref = NULL;
704         if (serno_ref)
705                 *serno_ref = NULL;
706         chip = SER_HID_CHIP_UNKNOWN;
707         path = serno = NULL;
708
709         if (!serial || !spec || !*spec)
710                 return SR_ERR_ARG;
711         p = spec;
712
713         /* The "hid" prefix is mandatory. */
714         if (!g_str_has_prefix(p, SER_HID_CONN_PREFIX))
715                 return SR_ERR_ARG;
716         p += strlen(SER_HID_CONN_PREFIX);
717
718         /*
719          * Check for prefixed fields, assume chip type spec otherwise.
720          * Paths and serial numbers "are greedy" (span to the end of
721          * the input spec). Chip types are optional, and cannot repeat
722          * multiple times.
723          */
724         while (*p) {
725                 if (*p == '/')
726                         p++;
727                 if (!*p)
728                         break;
729                 if (g_str_has_prefix(p, SER_HID_USB_PREFIX)) {
730                         rc = try_open_path(serial, p);
731                         if (rc != SR_OK)
732                                 return rc;
733                         path = g_strdup(p);
734                         p += strlen(p);
735                 } else if (g_str_has_prefix(p, SER_HID_RAW_PREFIX)) {
736                         rc = try_open_path(serial, p);
737                         if (rc != SR_OK)
738                                 return rc;
739                         path = g_strdup(p);
740                         p += strlen(p);
741                 } else if (g_str_has_prefix(p, SER_HID_SNR_PREFIX)) {
742                         p += strlen(SER_HID_SNR_PREFIX);
743                         serno = g_strdup(p);
744                         p += strlen(p);
745                 } else if (!chip) {
746                         char *copy;
747                         const char *endptr;
748                         copy = g_strdup(p);
749                         endptr = copy;
750                         chip = ser_hid_chip_find_enum(&endptr);
751                         if (!chip) {
752                                 g_free(copy);
753                                 return SR_ERR_ARG;
754                         }
755                         p += endptr - copy;
756                         g_free(copy);
757                 } else {
758                         sr_err("unsupported conn= spec %s, error at %s", spec, p);
759                         return SR_ERR_ARG;
760                 }
761                 if (*p == '/')
762                         p++;
763                 if (path || serno)
764                         break;
765         }
766
767         if (chip_ref)
768                 *chip_ref = chip;
769         if (path_ref && path)
770                 *path_ref = path;
771         if (serno_ref && serno)
772                 *serno_ref = serno;
773
774         return SR_OK;
775 }
776
777 /* Get and compare serial number. Boolean return value. */
778 static int check_serno(const char *path, const char *serno_want)
779 {
780         char *usb_path;
781         const char *hid_path;
782         char serno_got[128];
783         int rc;
784
785         usb_path = g_strdup(path);
786         hid_path = extract_hidapi_path(usb_path);
787         rc = ser_hid_hidapi_get_serno(hid_path, serno_got, sizeof(serno_got));
788         g_free(usb_path);
789         if (rc) {
790                 sr_dbg("DBG: %s(), could not get serial number", __func__);
791                 return 0;
792         }
793
794         return strcmp(serno_got, serno_want) == 0;
795 }
796
797 static GSList *append_find(GSList *devs, const char *path)
798 {
799         char *copy;
800
801         if (!path || !*path)
802                 return devs;
803
804         copy = g_strdup(path);
805         devs = g_slist_append(devs, copy);
806
807         return devs;
808 }
809
810 static GSList *list_paths_for_vids_pids(const struct vid_pid_item *vid_pids)
811 {
812         GSList *list;
813         size_t idx;
814         uint16_t vid, pid;
815
816         list = NULL;
817         for (idx = 0; /* EMPTY */; idx++) {
818                 if (!vid_pids) {
819                         vid = pid = 0;
820                 } else if (!vid_pids[idx].vid) {
821                         break;
822                 } else {
823                         vid = vid_pids[idx].vid;
824                         pid = vid_pids[idx].pid;
825                 }
826                 list = ser_hid_hidapi_find_usb(list, append_find, vid, pid);
827                 if (!vid_pids)
828                         break;
829         }
830
831         return list;
832 }
833
834 /**
835  * Search for a matching USB device for HID communication.
836  *
837  * @param[inout] chip The HID chip type (enum).
838  * @param[inout] usbpath The USB path for the device (string).
839  * @param[in] serno The serial number to search for.
840  *
841  * @retval SR_OK upon success
842  * @retval SR_ERR_* upon failure.
843  *
844  * This routine fills in blanks which the conn= spec parser left open.
845  * When not specified yet, the HID chip type gets determined. When a
846  * serial number was specified, then search the corresponding device.
847  * Upon completion, the chip type and USB path for the device shall be
848  * known, as these are essential for subsequent operation.
849  */
850 static int ser_hid_chip_search(enum ser_hid_chip_t *chip_ref,
851         char **path_ref, const char *serno)
852 {
853         enum ser_hid_chip_t chip;
854         char *path;
855         int have_chip, have_path, have_serno;
856         struct ser_hid_chip_functions *chip_funcs;
857         int rc;
858         int serno_matched;
859         uint16_t vid, pid;
860         const char *name;
861         const struct vid_pid_item *vid_pids;
862         GSList *list, *matched, *matched2, *tmplist;
863
864         if (!chip_ref)
865                 return SR_ERR_ARG;
866         chip = *chip_ref;
867         if (!path_ref)
868                 return SR_ERR_ARG;
869         path = *path_ref;
870
871         /*
872          * Simplify the more complex conditions somewhat by assigning
873          * to local variables. Handle the easiest conditions first.
874          * - Either path or serial number can be specified, but not both
875          *   at the same time.
876          * - When a USB path is given, immediately see which HID chip
877          *   the device has, without the need for enumeration.
878          * - When a serial number is given, enumerate the devices and
879          *   search for that number. Either enumerate all devices of the
880          *   specified HID chip type (try the VID:PID pairs that we are
881          *   aware of), or try all HID devices for unknown chip types.
882          *   Not finding the serial number is fatal.
883          * - When no path was found yet, enumerate the devices and pick
884          *   one of them. Try known VID:PID pairs for a HID chip, or all
885          *   devices for unknown chips. Make sure to pick a device of a
886          *   supported chip type if the chip was not specified.
887          * - Determine the chip type if not yet known. There should be
888          *   a USB path by now, determined in one of the above blocks.
889          */
890         have_chip = (chip != SER_HID_CHIP_UNKNOWN) ? 1 : 0;
891         have_path = (path && *path) ? 1 : 0;
892         have_serno = (serno && *serno) ? 1 : 0;
893         if (have_path && have_serno) {
894                 sr_err("Unsupported combination of USB path and serno");
895                 return SR_ERR_ARG;
896         }
897         chip_funcs = have_chip ? get_hid_chip_funcs(chip) : NULL;
898         if (have_chip && !chip_funcs)
899                 return SR_ERR_NA;
900         if (have_chip && !chip_funcs->vid_pid_items)
901                 return SR_ERR_NA;
902         if (have_path && !have_chip) {
903                 vid = pid = 0;
904                 rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
905                 if (rc != SR_OK)
906                         return rc;
907                 name = ser_hid_chip_find_name_vid_pid(vid, pid);
908                 if (!name || !*name)
909                         return SR_ERR_NA;
910                 chip = ser_hid_chip_find_enum(&name);
911                 if (chip == SER_HID_CHIP_UNKNOWN)
912                         return SR_ERR_NA;
913                 have_chip = 1;
914         }
915         if (have_serno) {
916                 vid_pids = have_chip ? chip_funcs->vid_pid_items : NULL;
917                 list = list_paths_for_vids_pids(vid_pids);
918                 if (!list)
919                         return SR_ERR_NA;
920                 matched = NULL;
921                 for (tmplist = list; tmplist; tmplist = tmplist->next) {
922                         path = get_hidapi_path_copy(tmplist->data);
923                         serno_matched = check_serno(path, serno);
924                         g_free(path);
925                         if (!serno_matched)
926                                 continue;
927                         matched = tmplist;
928                         break;
929                 }
930                 if (!matched)
931                         return SR_ERR_NA;
932                 path = g_strdup(matched->data);
933                 have_path = 1;
934                 g_slist_free_full(list, g_free);
935         }
936         if (!have_path) {
937                 vid_pids = have_chip ? chip_funcs->vid_pid_items : NULL;
938                 list = list_paths_for_vids_pids(vid_pids);
939                 if (!list)
940                         return SR_ERR_NA;
941                 matched = matched2 = NULL;
942                 if (have_chip) {
943                         /* List already only contains specified chip. */
944                         matched = list;
945                         matched2 = list->next;
946                 }
947                 /* Works for lists with one or multiple chips. Saves indentation. */
948                 for (tmplist = list; tmplist; tmplist = tmplist->next) {
949                         if (have_chip)
950                                 break;
951                         path = tmplist->data;
952                         rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
953                         if (rc || !ser_hid_chip_find_name_vid_pid(vid, pid))
954                                 continue;
955                         if (!matched) {
956                                 matched = tmplist;
957                                 continue;
958                         }
959                         if (!matched2) {
960                                 matched2 = tmplist;
961                                 break;
962                         }
963                 }
964                 if (!matched) {
965                         g_slist_free_full(list, g_free);
966                         return SR_ERR_NA;
967                 }
968                 /*
969                  * TODO Optionally fail harder, expect users to provide
970                  * unambiguous cable specs.
971                  */
972                 if (matched2)
973                         sr_info("More than one cable matches, random pick.");
974                 path = get_hidapi_path_copy(matched->data);
975                 have_path = 1;
976                 g_slist_free_full(list, g_free);
977         }
978         if (have_path && !have_chip) {
979                 vid = pid = 0;
980                 rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
981                 if (rc != SR_OK)
982                         return rc;
983                 name = ser_hid_chip_find_name_vid_pid(vid, pid);
984                 if (!name || !*name)
985                         return SR_ERR_NA;
986                 chip = ser_hid_chip_find_enum(&name);
987                 if (chip == SER_HID_CHIP_UNKNOWN)
988                         return SR_ERR_NA;
989                 have_chip = 1;
990         }
991
992         if (chip_ref)
993                 *chip_ref = chip;
994         if (path_ref)
995                 *path_ref = path;
996
997         return SR_OK;
998 }
999
1000 /* }}} */
1001 /* {{{ transport methods called by the common serial.c code */
1002
1003 /* See if a serial port's name refers to an HID type. */
1004 SR_PRIV int ser_name_is_hid(struct sr_serial_dev_inst *serial)
1005 {
1006         size_t off;
1007         char sep;
1008
1009         if (!serial)
1010                 return 0;
1011         if (!serial->port || !*serial->port)
1012                 return 0;
1013
1014         /* Accept either "hid" alone, or "hid/" as a prefix. */
1015         if (!g_str_has_prefix(serial->port, SER_HID_CONN_PREFIX))
1016                 return 0;
1017         off = strlen(SER_HID_CONN_PREFIX);
1018         sep = serial->port[off];
1019         if (sep != '\0' && sep != '/')
1020                 return 0;
1021
1022         return 1;
1023 }
1024
1025 static int ser_hid_open(struct sr_serial_dev_inst *serial, int flags)
1026 {
1027         enum ser_hid_chip_t chip;
1028         char *usbpath, *serno;
1029         int rc;
1030
1031         (void)flags;
1032
1033         if (ser_hid_setup_funcs(serial) != 0) {
1034                 sr_err("Cannot determine HID communication library.");
1035                 return SR_ERR_NA;
1036         }
1037
1038         rc = ser_hid_parse_conn_spec(serial, serial->port,
1039                         &chip, &usbpath, &serno);
1040         if (rc != SR_OK)
1041                 return SR_ERR_ARG;
1042
1043         /*
1044          * When a serial number was specified, or when the chip type or
1045          * the USB path were not specified, do a search to determine the
1046          * device's USB path.
1047          */
1048         if (!chip || !usbpath || serno) {
1049                 rc = ser_hid_chip_search(&chip, &usbpath, serno);
1050                 if (rc != 0)
1051                         return SR_ERR_NA;
1052         }
1053
1054         /*
1055          * Open the HID device. Only store chip type and device handle
1056          * when open completes successfully.
1057          */
1058         serial->hid_chip = chip;
1059         if (ser_hid_setup_funcs(serial) != 0) {
1060                 sr_err("Cannot determine HID chip specific routines.");
1061                 return SR_ERR_NA;
1062         }
1063         if (usbpath && *usbpath)
1064                 serial->usb_path = usbpath;
1065         if (serno && *serno)
1066                 serial->usb_serno = serno;
1067
1068         rc = ser_hid_hidapi_open_dev(serial);
1069         if (rc) {
1070                 sr_err("Failed to open HID device.");
1071                 serial->hid_chip = 0;
1072                 g_free(serial->usb_path);
1073                 serial->usb_path = NULL;
1074                 g_free(serial->usb_serno);
1075                 serial->usb_serno = NULL;
1076                 return SR_ERR_IO;
1077         }
1078
1079         if (!serial->rcv_buffer)
1080                 serial->rcv_buffer = g_string_sized_new(SER_HID_CHUNK_SIZE);
1081
1082         return SR_OK;
1083 }
1084
1085 static int ser_hid_close(struct sr_serial_dev_inst *serial)
1086 {
1087         ser_hid_hidapi_close_dev(serial);
1088
1089         return SR_OK;
1090 }
1091
1092 static int ser_hid_set_params(struct sr_serial_dev_inst *serial,
1093         int baudrate, int bits, int parity, int stopbits,
1094         int flowcontrol, int rts, int dtr)
1095 {
1096         if (ser_hid_setup_funcs(serial) != 0)
1097                 return SR_ERR_NA;
1098         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->set_params)
1099                 return SR_ERR_NA;
1100
1101         return serial->hid_chip_funcs->set_params(serial,
1102                 baudrate, bits, parity, stopbits,
1103                 flowcontrol, rts, dtr);
1104 }
1105
1106 static int ser_hid_setup_source_add(struct sr_session *session,
1107         struct sr_serial_dev_inst *serial, int events, int timeout,
1108         sr_receive_data_callback cb, void *cb_data)
1109 {
1110         return ser_hid_hidapi_setup_source_add(session, serial,
1111                 events, timeout, cb, cb_data);
1112 }
1113
1114 static int ser_hid_setup_source_remove(struct sr_session *session,
1115         struct sr_serial_dev_inst *serial)
1116 {
1117         return ser_hid_hidapi_setup_source_remove(session, serial);
1118 }
1119
1120 static GSList *ser_hid_list(GSList *list, sr_ser_list_append_t append)
1121 {
1122         return ser_hid_hidapi_list(list, append);
1123 }
1124
1125 static GSList *ser_hid_find_usb(GSList *list, sr_ser_find_append_t append,
1126         uint16_t vendor_id, uint16_t product_id)
1127 {
1128         return ser_hid_hidapi_find_usb(list, append, vendor_id, product_id);
1129 }
1130
1131 static int ser_hid_flush(struct sr_serial_dev_inst *serial)
1132 {
1133         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->flush)
1134                 return SR_ERR_NA;
1135
1136         return serial->hid_chip_funcs->flush(serial);
1137 }
1138
1139 static int ser_hid_drain(struct sr_serial_dev_inst *serial)
1140 {
1141         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->drain)
1142                 return SR_ERR_NA;
1143
1144         return serial->hid_chip_funcs->drain(serial);
1145 }
1146
1147 static int ser_hid_write(struct sr_serial_dev_inst *serial,
1148         const void *buf, size_t count,
1149         int nonblocking, unsigned int timeout_ms)
1150 {
1151         int total, max_chunk, chunk_len;
1152         int rc;
1153
1154         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->write_bytes)
1155                 return SR_ERR_NA;
1156         if (!serial->hid_chip_funcs->max_bytes_per_request)
1157                 return SR_ERR_NA;
1158
1159         total = 0;
1160         max_chunk = serial->hid_chip_funcs->max_bytes_per_request;
1161         while (count > 0) {
1162                 chunk_len = count;
1163                 if (max_chunk && chunk_len > max_chunk)
1164                         chunk_len = max_chunk;
1165                 rc = serial->hid_chip_funcs->write_bytes(serial, buf, chunk_len);
1166                 if (rc < 0) {
1167                         sr_err("Error sending transmit data to HID device.");
1168                         return total;
1169                 }
1170                 if (rc != chunk_len) {
1171                         sr_warn("Short transmission to HID device (%d/%d bytes)?",
1172                                         rc, chunk_len);
1173                         return total;
1174                 }
1175                 buf += chunk_len;
1176                 count -= chunk_len;
1177                 total += chunk_len;
1178                 /* TODO
1179                  * Need we wait here? For data to drain through the slow
1180                  * UART. Not all UART-over-HID chips will have FIFOs.
1181                  */
1182                 if (!nonblocking) {
1183                         (void)timeout_ms;
1184                         /* TODO */
1185                 }
1186         }
1187
1188         return total;
1189 }
1190
1191 static int ser_hid_read(struct sr_serial_dev_inst *serial,
1192         void *buf, size_t count,
1193         int nonblocking, unsigned int timeout_ms)
1194 {
1195         gint64 deadline_us, now_us;
1196         uint8_t buffer[SER_HID_CHUNK_SIZE];
1197         int rc;
1198         unsigned int got;
1199
1200         if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->read_bytes)
1201                 return SR_ERR_NA;
1202         if (!serial->hid_chip_funcs->max_bytes_per_request)
1203                 return SR_ERR_NA;
1204
1205         /*
1206          * Immediately satisfy the caller's request from the RX buffer
1207          * if the requested amount of data is available already.
1208          */
1209         if (sr_ser_has_queued_data(serial) >= count)
1210                 return sr_ser_unqueue_rx_data(serial, buf, count);
1211
1212         /*
1213          * When a timeout was specified, then determine the deadline
1214          * where to stop reception.
1215          */
1216         deadline_us = 0;
1217         now_us = 0;             /* Silence a (false) compiler warning. */
1218         if (timeout_ms) {
1219                 now_us = g_get_monotonic_time();
1220                 deadline_us = now_us + timeout_ms * 1000;
1221         }
1222
1223         /*
1224          * Keep receiving from the port until the caller's requested
1225          * amount of data has become available, or the timeout has
1226          * expired. In the absence of a timeout, stop reading when an
1227          * attempt no longer yields receive data.
1228          *
1229          * This implementation assumes that applications will call the
1230          * read routine often enough, or that reception continues in
1231          * background, such that data is not lost and hardware and
1232          * software buffers won't overrun.
1233          */
1234         while (TRUE) {
1235                 /*
1236                  * Determine the timeout (in milliseconds) for this
1237                  * iteration. The 'now_us' timestamp was initially
1238                  * determined above, and gets updated at the bottom of
1239                  * the loop.
1240                  */
1241                 if (deadline_us) {
1242                         timeout_ms = (deadline_us - now_us) / 1000;
1243                         if (!timeout_ms)
1244                                 timeout_ms = 1;
1245                 } else if (nonblocking) {
1246                         timeout_ms = 10;
1247                 } else {
1248                         timeout_ms = 0;
1249                 }
1250
1251                 /*
1252                  * Check the HID transport for the availability of more
1253                  * receive data.
1254                  */
1255                 rc = serial->hid_chip_funcs->read_bytes(serial,
1256                                 buffer, sizeof(buffer), timeout_ms);
1257                 if (rc < 0) {
1258                         sr_dbg("DBG: %s() read error %d.", __func__, rc);
1259                         return SR_ERR;
1260                 }
1261                 if (rc) {
1262                         ser_hid_mask_databits(serial, buffer, rc);
1263                         sr_ser_queue_rx_data(serial, buffer, rc);
1264                 }
1265                 got = sr_ser_has_queued_data(serial);
1266
1267                 /*
1268                  * Stop reading when the requested amount is available,
1269                  * or when the timeout has expired.
1270                  *
1271                  * TODO Consider whether grabbing all RX data is more
1272                  * desirable. Implementing this approach requires a cheap
1273                  * check for the availability of more data on the USB level.
1274                  */
1275                 if (got >= count)
1276                         break;
1277                 if (nonblocking && !rc)
1278                         break;
1279                 if (deadline_us) {
1280                         now_us = g_get_monotonic_time();
1281                         if (now_us >= deadline_us) {
1282                                 sr_dbg("DBG: %s() read loop timeout.", __func__);
1283                                 break;
1284                         }
1285                 }
1286         }
1287
1288         /*
1289          * Satisfy the caller's demand for receive data from previously
1290          * queued incoming data.
1291          */
1292         if (got > count)
1293                 got = count;
1294
1295         return sr_ser_unqueue_rx_data(serial, buf, count);
1296 }
1297
1298 static struct ser_lib_functions serlib_hid = {
1299         .open = ser_hid_open,
1300         .close = ser_hid_close,
1301         .flush = ser_hid_flush,
1302         .drain = ser_hid_drain,
1303         .write = ser_hid_write,
1304         .read = ser_hid_read,
1305         .set_params = ser_hid_set_params,
1306         .setup_source_add = ser_hid_setup_source_add,
1307         .setup_source_remove = ser_hid_setup_source_remove,
1308         .list = ser_hid_list,
1309         .find_usb = ser_hid_find_usb,
1310         .get_frame_format = NULL,
1311 };
1312 SR_PRIV struct ser_lib_functions *ser_lib_funcs_hid = &serlib_hid;
1313
1314 /* }}} */
1315 #else
1316
1317 SR_PRIV int ser_name_is_hid(struct sr_serial_dev_inst *serial)
1318 {
1319         (void)serial;
1320
1321         return 0;
1322 }
1323
1324 SR_PRIV struct ser_lib_functions *ser_lib_funcs_hid = NULL;
1325
1326 #endif
1327 #endif
1328 /** @} */