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