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