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