2 * This file is part of the libsigrok project.
4 * Copyright (C) 2017-2019 Gerhard Sittig <gerhard.sittig@gmx.net>
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.
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.
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/>.
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
27 #include "serial_hid.h"
31 #include <windows.h> /* for HANDLE */
35 #define LOG_PREFIX "serial-hid"
38 #ifdef HAVE_SERIAL_COMM
43 * Serial port handling, HIDAPI library specific support code.
47 * @defgroup grp_serial_hid Serial port handling, HID group
49 * Make serial-over-HID communication appear like a regular serial port.
55 /* {{{ helper routines */
57 /* Strip off parity bits for "odd" data bit counts like in 7e1 frames. */
58 static void ser_hid_mask_databits(struct sr_serial_dev_inst *serial,
59 uint8_t *data, size_t len)
65 if ((serial->comm_params.data_bits % 8) == 0)
68 mask32 = (1UL << serial->comm_params.data_bits) - 1;
70 for (idx = 0; idx < len; idx++)
75 /* {{{ open/close/list/find HIDAPI connection, exchange HID requests and data */
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.
82 * Since conn= is passed with -d where multiple options (among them conn=)
83 * are separated by colons, port names themselves cannot contain colons.
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.
92 static char *get_hidapi_path_copy(const char *path)
94 static const char *accept = "0123456789abcdefABCDEF:";
95 static const char *keep = "0123456789abcdefABCDEF";
101 has_colon = strchr(path, ':') != NULL;
102 is_hex_colon = strspn(path, accept) == strlen(path);
103 if (has_colon && !is_hex_colon) {
104 sr_err("Unsupported HIDAPI path format: %s", path);
108 name = g_strdup_printf("%s%s", SER_HID_USB_PREFIX, path);
109 g_strcanon(name + strlen(SER_HID_USB_PREFIX), keep, '.');
111 name = g_strdup_printf("%s%s", SER_HID_RAW_PREFIX, path);
118 * Undo the port name construction that was done during scan. Extract
119 * the HIDAPI path from a conn= input spec (the part after the hid/
120 * prefix and chip type).
122 * Strip off the "raw" prefix, or undo colon substitution. See @ref
123 * get_hidapi_path_copy() for details.
125 static const char *extract_hidapi_path(char *buffer)
127 static const char *keep = "0123456789abcdefABCDEF:";
135 if (strncmp(p, SER_HID_RAW_PREFIX, strlen(SER_HID_RAW_PREFIX)) == 0) {
136 p += strlen(SER_HID_RAW_PREFIX);
139 if (strncmp(p, SER_HID_USB_PREFIX, strlen(SER_HID_USB_PREFIX)) == 0) {
140 p += strlen(SER_HID_USB_PREFIX);
141 g_strcanon(buffer, keep, ':');
149 * The HIDAPI specific list() callback, invoked by common serial.c code.
150 * Enumerate all devices (no VID:PID is involved).
151 * Invoke an 'append' callback with "path" and "name".
153 static GSList *ser_hid_hidapi_list(GSList *list, sr_ser_list_append_t append)
155 struct hid_device_info *devs, *curdev;
156 const char *chipname;
158 wchar_t *manuf, *prod, *serno;
162 devs = hid_enumerate(0x0000, 0x0000);
163 for (curdev = devs; curdev; curdev = curdev->next) {
165 * Determine the chip name from VID:PID (if it's one of
166 * the supported types with an ID known to us).
168 vid = curdev->vendor_id;
169 pid = curdev->product_id;
170 sr_dbg("DIAG: hidapi enum, vid:pid %04x:%04x, path %s\n",
171 curdev->vendor_id, curdev->product_id, curdev->path);
172 chipname = ser_hid_chip_find_name_vid_pid(vid, pid);
177 * Prefix port names such that open() calls with this
178 * conn= spec will end up here and contain all details
179 * that are essential for processing.
181 path = get_hidapi_path_copy(curdev->path);
184 name = g_strdup_printf("%s/%s/%s",
185 SER_HID_CONN_PREFIX, chipname, path);
189 * Print whatever information was available. Construct
190 * the description text from pieces. Absence of fields
191 * is not fatal, we have seen perfectly usable cables
192 * that only had a VID and PID (permissions were not an
195 manuf = curdev->manufacturer_string;
196 prod = curdev->product_string;
197 serno = curdev->serial_number;
198 vid = curdev->vendor_id;
199 pid = curdev->product_id;
200 desc = g_string_sized_new(128);
201 g_string_append_printf(desc, "HID");
203 g_string_append_printf(desc, " %ls", manuf);
205 g_string_append_printf(desc, " %ls", prod);
207 g_string_append_printf(desc, " %ls", serno);
209 g_string_append_printf(desc, " %04hx:%04hx", vid, pid);
210 list = append(list, name, desc->str);
211 g_string_free(desc, TRUE);
214 hid_free_enumeration(devs);
220 * The HIDAPI specific find_usb() callback, invoked by common serial.c code.
221 * Enumerate devices for the specified VID:PID pair.
222 * Invoke an "append" callback with 'path' for the device.
224 static GSList *ser_hid_hidapi_find_usb(GSList *list, sr_ser_find_append_t append,
225 uint16_t vendor_id, uint16_t product_id)
227 struct hid_device_info *devs, *curdev;
230 devs = hid_enumerate(vendor_id, product_id);
231 for (curdev = devs; curdev; curdev = curdev->next) {
233 list = append(list, name);
235 hid_free_enumeration(devs);
240 /* Get the serial number of a device specified by path. */
241 static int ser_hid_hidapi_get_serno(const char *path, char *buf, size_t blen)
251 usbpath = g_strdup(path);
252 hidpath = extract_hidapi_path(usbpath);
253 dev = hidpath ? hid_open_path(hidpath) : NULL;
258 serno_wch = g_malloc0(blen * sizeof(*serno_wch));
259 rc = hid_get_serial_number_string(dev, serno_wch, blen - 1);
266 snprintf(buf, blen, "%ls", serno_wch);
272 /* Get the VID and PID of a device specified by path. */
273 static int ser_hid_hidapi_get_vid_pid(const char *path,
274 uint16_t *vid, uint16_t *pid)
278 * Bummer! It would have been most reliable to just open the
279 * device by the specified path, and grab its VID:PID. But
280 * there is no way to get these parameters, neither in the
281 * HIDAPI itself, nor when cheating and reaching behind the API
282 * and accessing the libusb handle in dirty ways. :(
288 dev = hid_open_path(path);
292 *vid = dev->vendor_id;
294 *pid = dev->product_id;
300 * The fallback approach. Enumerate all devices, compare the
301 * enumerated USB path, and grab the VID:PID. Unfortunately the
302 * caller can provide path specs that differ from enumerated
303 * paths yet mean the same (address the same device). This needs
304 * more attention. Though the specific format of the path and
305 * its meaning are said to be OS specific, which is why we may
306 * not assume anything about it...
310 struct hid_device_info *devs, *dev;
313 usbpath = g_strdup(path);
314 hidpath = extract_hidapi_path(usbpath);
320 devs = hid_enumerate(0x0000, 0x0000);
322 for (dev = devs; dev; dev = dev->next) {
323 if (strcmp(dev->path, hidpath) != 0)
326 *vid = dev->vendor_id;
328 *pid = dev->product_id;
332 hid_free_enumeration(devs);
335 return found ? SR_OK : SR_ERR_NA;
339 static int ser_hid_hidapi_open_dev(struct sr_serial_dev_inst *serial)
343 if (!serial->usb_path || !*serial->usb_path)
347 * A path is available, assume that either a GUI or a
348 * user has copied what a previous listing has provided.
349 * Or a scan determined a matching device's USB path.
351 if (!serial->hid_path)
352 serial->hid_path = extract_hidapi_path(serial->usb_path);
353 hid_dev = hid_open_path(serial->hid_path);
354 sr_dbg("DBG: %s(), hid_open_path(\"%s\") => %p", __func__,
355 serial->hid_path, hid_dev);
357 serial->hid_path = NULL;
361 serial->hid_dev = hid_dev;
362 hid_set_nonblocking(hid_dev, 1);
367 static void ser_hid_hidapi_close_dev(struct sr_serial_dev_inst *serial)
369 if (serial->hid_dev) {
370 hid_close(serial->hid_dev);
371 serial->hid_dev = NULL;
372 serial->hid_path = NULL;
374 g_slist_free_full(serial->hid_source_args, g_free);
375 serial->hid_source_args = NULL;
378 struct hidapi_source_args_t {
379 /* Application callback. */
380 sr_receive_data_callback cb;
382 /* The serial device, to store RX data. */
383 struct sr_serial_dev_inst *serial;
387 * Gets periodically invoked by the glib main loop. "Drives" (checks)
388 * progress of USB communication, and invokes the application's callback
389 * which processes RX data (when some has become available), as well as
390 * handles application level timeouts.
392 static int hidapi_source_cb(int fd, int revents, void *cb_data)
394 struct hidapi_source_args_t *args;
395 uint8_t rx_buf[SER_HID_CHUNK_SIZE];
398 sr_dbg("DBG: %s() fd %d, evt 0x%x, data %p.", __func__, fd, revents, cb_data);
402 * Drain receive data which the chip might have pending. This is
403 * "a copy" of the "background part" of ser_hid_read(), without
404 * the timeout support code, and not knowing how much data the
405 * application is expecting.
408 rc = args->serial->hid_chip_funcs->read_bytes(args->serial,
409 rx_buf, sizeof(rx_buf), 0);
411 sr_dbg("DBG: %s() queueing %d bytes.", __func__, rc);
412 ser_hid_mask_databits(args->serial, rx_buf, rc);
413 sr_ser_queue_rx_data(args->serial, rx_buf, rc);
418 * When RX data became available (now or earlier), pass this
419 * condition to the application callback. Always periodically
420 * run the application callback, since it handles timeouts and
421 * might carry out other tasks as well like signalling progress.
423 if (sr_ser_has_queued_data(args->serial))
425 rc = args->cb(fd, revents, args->cb_data);
426 sr_dbg("DBG: %s() rc %d.", __func__, rc);
431 #define WITH_MAXIMUM_TIMEOUT_VALUE 10
432 static int ser_hid_hidapi_setup_source_add(struct sr_session *session,
433 struct sr_serial_dev_inst *serial, int events, int timeout,
434 sr_receive_data_callback cb, void *cb_data)
436 struct hidapi_source_args_t *args;
439 sr_dbg("DBG: %s() evt 0x%x, to %d.", __func__, events, timeout);
442 /* Optionally enforce a minimum poll period. */
443 if (WITH_MAXIMUM_TIMEOUT_VALUE && timeout > WITH_MAXIMUM_TIMEOUT_VALUE)
444 timeout = WITH_MAXIMUM_TIMEOUT_VALUE;
446 /* Allocate status container for background data reception. */
447 args = g_malloc0(sizeof(*args));
449 args->cb_data = cb_data;
450 args->serial = serial;
453 * Have a periodic timer installed. Register the allocated block
454 * with the serial device, since the GSource's finalizer won't
455 * free the memory, and we haven't bothered to create a custom
456 * HIDAPI specific GSource.
458 rc = sr_session_source_add(session, -1, events, timeout,
459 hidapi_source_cb, args);
460 sr_dbg("DBG: %s() added, rc %d.", __func__, rc);
465 serial->hid_source_args = g_slist_append(serial->hid_source_args, args);
470 static int ser_hid_hidapi_setup_source_remove(struct sr_session *session,
471 struct sr_serial_dev_inst *serial)
475 sr_dbg("DBG: %s().", __func__);
476 (void)sr_session_source_remove(session, -1);
478 * Release callback args here already? Can there be more than
479 * one source registered at any time, given that we pass fd -1
480 * which is used as the key for the session?
486 SR_PRIV int ser_hid_hidapi_get_report(struct sr_serial_dev_inst *serial,
487 uint8_t *data, size_t len)
491 rc = hid_get_feature_report(serial->hid_dev, data, len);
498 SR_PRIV int ser_hid_hidapi_set_report(struct sr_serial_dev_inst *serial,
499 const uint8_t *data, size_t len)
502 const wchar_t *err_text;
504 rc = hid_send_feature_report(serial->hid_dev, data, len);
506 err_text = hid_error(serial->hid_dev);
507 sr_dbg("%s() hidapi error: %ls", __func__, err_text);
514 SR_PRIV int ser_hid_hidapi_get_data(struct sr_serial_dev_inst *serial,
515 uint8_t ep, uint8_t *data, size_t len, int timeout)
522 rc = hid_read_timeout(serial->hid_dev, data, len, timeout);
524 rc = hid_read(serial->hid_dev, data, len);
533 SR_PRIV int ser_hid_hidapi_set_data(struct sr_serial_dev_inst *serial,
534 uint8_t ep, const uint8_t *data, size_t len, int timeout)
541 rc = hid_write(serial->hid_dev, data, len);
549 /* {{{ support for serial-over-HID chips */
551 static struct ser_hid_chip_functions **chips[SER_HID_CHIP_LAST] = {
552 [SER_HID_CHIP_UNKNOWN] = NULL,
553 [SER_HID_CHIP_BTC_BU86X] = &ser_hid_chip_funcs_bu86x,
554 [SER_HID_CHIP_SIL_CP2110] = &ser_hid_chip_funcs_cp2110,
555 [SER_HID_CHIP_VICTOR_DMM] = &ser_hid_chip_funcs_victor,
556 [SER_HID_CHIP_WCH_CH9325] = &ser_hid_chip_funcs_ch9325,
559 static struct ser_hid_chip_functions *get_hid_chip_funcs(enum ser_hid_chip_t chip)
561 struct ser_hid_chip_functions *funcs;
563 if (chip >= ARRAY_SIZE(chips))
567 funcs = *chips[chip];
574 static int ser_hid_setup_funcs(struct sr_serial_dev_inst *serial)
580 if (serial->hid_chip && !serial->hid_chip_funcs) {
581 serial->hid_chip_funcs = get_hid_chip_funcs(serial->hid_chip);
582 if (!serial->hid_chip_funcs)
590 * Takes a pointer to the chip spec with potentially trailing data,
591 * returns the chip index and advances the spec pointer upon match,
592 * returns SER_HID_CHIP_UNKNOWN upon mismatch.
594 static enum ser_hid_chip_t ser_hid_chip_find_enum(char **spec_p)
597 enum ser_hid_chip_t idx;
598 struct ser_hid_chip_functions *desc;
600 if (!spec_p || !*spec_p)
601 return SER_HID_CHIP_UNKNOWN;
604 return SER_HID_CHIP_UNKNOWN;
605 for (idx = 0; idx < SER_HID_CHIP_LAST; idx++) {
606 desc = get_hid_chip_funcs(idx);
611 if (!g_str_has_prefix(spec, desc->chipname))
613 spec += strlen(desc->chipname);
618 return SER_HID_CHIP_UNKNOWN;
621 /* See if we can find a chip name for a VID:PID spec. */
622 SR_PRIV const char *ser_hid_chip_find_name_vid_pid(uint16_t vid, uint16_t pid)
625 struct ser_hid_chip_functions *desc;
626 const struct vid_pid_item *vid_pids;
628 for (chip_idx = 0; chip_idx < SER_HID_CHIP_LAST; chip_idx++) {
629 desc = get_hid_chip_funcs(chip_idx);
634 vid_pids = desc->vid_pid_items;
637 while (vid_pids->vid) {
638 if (vid_pids->vid == vid && vid_pids->pid == pid) {
639 return desc->chipname;
648 static const char *ser_hid_chip_get_text(enum ser_hid_chip_t idx)
650 struct ser_hid_chip_functions *desc;
652 desc = get_hid_chip_funcs(idx);
656 return desc->chipdesc;
660 * See if a text string is a valid USB path for a HID device.
661 * @param[in] serial The serial port that is about to get opened.
662 * @param[in] path The (assumed) USB path specification.
663 * @return SR_OK upon success, SR_ERR* upon failure.
665 static int try_open_path(struct sr_serial_dev_inst *serial, const char *path)
669 serial->usb_path = g_strdup(path);
670 rc = ser_hid_hidapi_open_dev(serial);
671 ser_hid_hidapi_close_dev(serial);
672 g_free(serial->usb_path);
673 serial->usb_path = NULL;
679 * Parse conn= specs for serial over HID communication.
681 * @param[in] serial The serial port that is about to get opened.
682 * @param[in] spec The caller provided conn= specification.
683 * @param[out] chip_ref Pointer to a chip type (enum).
684 * @param[out] path_ref Pointer to a USB path (text string).
685 * @param[out] serno_ref Pointer to a serial number (text string).
687 * @return 0 upon success, non-zero upon failure. Fills the *_ref output
692 * Summary of parsing rules as they are implemented:
693 * - Insist on the "hid" prefix. Accept "hid" alone without any other
695 * - The first field that follows can be a chip spec, yet is optional.
696 * - Any other field is assumed to be either a USB path or a serial
697 * number. There is no point in specifying both of these, as either
698 * of them uniquely identifies a device.
700 * Supported formats resulting from these rules:
702 * hid[/<chip>]/usb=<bus>.<dev>[.<if>]
703 * hid[/<chip>]/raw=<path> (may contain slashes!)
704 * hid[/<chip>]/sn=serno
706 * This routine just parses the conn= spec, which either was provided by
707 * a user, or may reflect (cite) an item of a previously gathered listing
708 * (clipboard provided by CLI clients, or selected from a GUI form).
709 * Another routine will fill in the blanks, and do the cable selection
710 * when a filter was specified.
712 * Users will want to use short forms when they need to come up with the
713 * specs by themselves. The "verbose" or seemingly redundant forms (chip
714 * _and_ path/serno spec) are useful when the cable uses non-standard or
715 * not-yet-supported VID:PID items when automatic chip detection fails.
717 static int ser_hid_parse_conn_spec(
718 struct sr_serial_dev_inst *serial, const char *spec,
719 enum ser_hid_chip_t *chip_ref, char **path_ref, char **serno_ref)
722 enum ser_hid_chip_t chip;
727 *chip_ref = SER_HID_CHIP_UNKNOWN;
732 chip = SER_HID_CHIP_UNKNOWN;
735 if (!serial || !spec || !*spec)
737 sr_dbg("DBG: %s(), input spec: %s", __func__, spec);
740 /* The "hid" prefix is mandatory. */
741 if (!g_str_has_prefix(p, SER_HID_CONN_PREFIX)) {
742 sr_dbg("DBG: %s(), not a HID port", __func__);
745 p += strlen(SER_HID_CONN_PREFIX);
748 * Check for prefixed fields, assume chip type spec otherwise.
749 * Paths and serial numbers "are greedy" (span to the end of
750 * the input spec). Chip types are optional, and cannot repeat
758 if (g_str_has_prefix(p, SER_HID_USB_PREFIX)) {
759 rc = try_open_path(serial, p);
760 sr_dbg("DBG: %s(), open usb path %s => rc %d", __func__, p, rc);
765 } else if (g_str_has_prefix(p, SER_HID_RAW_PREFIX)) {
766 rc = try_open_path(serial, p);
767 sr_dbg("DBG: %s(), open raw path %s => rc %d", __func__, p, rc);
772 } else if (g_str_has_prefix(p, SER_HID_SNR_PREFIX)) {
773 p += strlen(SER_HID_SNR_PREFIX);
774 sr_dbg("DBG: %s(), snr %s", __func__, p);
782 chip = ser_hid_chip_find_enum(&endptr);
783 sr_dbg("DBG: %s(), chip search, %s => %u", __func__, p, chip);
790 name = ser_hid_chip_get_text(chip);
791 sr_dbg("DBG: %s(), chip %s", __func__, name);
793 sr_err("unsupported conn= spec %s, error at %s", spec, p);
802 sr_dbg("DBG: %s() done, chip %d, path %s, serno %s", __func__, chip, path, serno);
805 if (path_ref && path)
807 if (serno_ref && serno)
813 /* Get and compare serial number. Boolean return value. */
814 static int check_serno(const char *path, const char *serno_want)
817 const char *hid_path;
821 sr_dbg("DBG: %s(\"%s\", \"%s\")", __func__, path, serno_want);
823 usb_path = g_strdup(path);
824 hid_path = extract_hidapi_path(usb_path);
825 rc = ser_hid_hidapi_get_serno(hid_path, serno_got, sizeof(serno_got));
826 sr_dbg("DBG: %s(), usb %s, hidapi %s => rc %d", __func__, usb_path, hid_path, rc);
829 sr_dbg("DBG: %s(), could not get serial number", __func__);
832 sr_dbg("DBG: %s(), got serno \"%s\"", __func__, serno_got);
834 rc = strcmp(serno_got, serno_want) == 0;
835 sr_dbg("DBG: %s(), return %d", __func__, rc);
840 static GSList *append_find(GSList *devs, const char *path)
847 copy = g_strdup(path);
848 devs = g_slist_append(devs, copy);
853 static GSList *list_paths_for_vids_pids(const struct vid_pid_item *vid_pids)
860 for (idx = 0; /* EMPTY */; idx++) {
863 } else if (!vid_pids[idx].vid) {
866 vid = vid_pids[idx].vid;
867 pid = vid_pids[idx].pid;
869 sr_dbg("DBG: %s(), searching VID:PID %04hx:%04hx",
871 list = ser_hid_hidapi_find_usb(list, append_find, vid, pid);
880 * Search for a matching USB device for HID communication.
882 * @param[inout] chip The HID chip type (enum).
883 * @param[inout] usbpath The USB path for the device (string).
884 * @param[in] serno The serial number to search for.
886 * @retval SR_OK upon success
887 * @retval SR_ERR_* upon failure.
891 * This routine fills in blanks which the conn= spec parser left open.
892 * When not specified yet, the HID chip type gets determined. When a
893 * serial number was specified, then search the corresponding device.
894 * Upon completion, the chip type and USB path for the device shall be
895 * known, as these are essential for subsequent operation.
897 static int ser_hid_chip_search(enum ser_hid_chip_t *chip_ref,
898 char **path_ref, const char *serno)
900 enum ser_hid_chip_t chip;
902 int have_chip, have_path, have_serno;
903 struct ser_hid_chip_functions *chip_funcs;
908 const struct vid_pid_item *vid_pids;
909 GSList *list, *matched, *matched2, *tmplist;
917 sr_dbg("DBG: %s() enter, chip %d, path %s, serno %s", __func__,
918 chip, path, serno ? serno : "<none>");
921 * Simplify the more complex conditions somewhat by assigning
922 * to local variables. Handle the easiest conditions first.
923 * - Either path or serial number can be specified, but not both
925 * - When a USB path is given, immediately see which HID chip
926 * the device has, without the need for enumeration.
927 * - When a serial number is given, enumerate the devices and
928 * search for that number. Either enumerate all devices of the
929 * specified HID chip type (try the VID:PID pairs that we are
930 * aware of), or try all HID devices for unknown chip types.
931 * Not finding the serial number is fatal.
932 * - When no path was found yet, enumerate the devices and pick
933 * one of them. Try known VID:PID pairs for a HID chip, or all
934 * devices for unknown chips. Make sure to pick a device of a
935 * supported chip type if the chip was not specified.
936 * - Determine the chip type if not yet known. There should be
937 * a USB path by now, determined in one of the above blocks.
939 have_chip = (chip != SER_HID_CHIP_UNKNOWN) ? 1 : 0;
940 have_path = (path && *path) ? 1 : 0;
941 have_serno = (serno && *serno) ? 1 : 0;
942 sr_dbg("DBG: %s(), have chip %d, path %d, serno %d", __func__,
943 have_chip, have_path, have_serno);
944 if (have_path && have_serno) {
945 sr_err("Unsupported combination of USB path and serno");
948 chip_funcs = have_chip ? get_hid_chip_funcs(chip) : NULL;
949 if (have_chip && !chip_funcs)
951 if (have_chip && !chip_funcs->vid_pid_items)
953 if (have_path && !have_chip) {
954 sr_dbg("DBG: %s(), searching chip for path %s", __func__, path);
956 rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
957 sr_dbg("DBG: %s(), rc %d, VID:PID %04x:%04x", __func__, rc, vid, pid);
960 name = ser_hid_chip_find_name_vid_pid(vid, pid);
961 sr_dbg("DBG: %s(), name %s", __func__, name);
964 chip = ser_hid_chip_find_enum((char **)&name);
965 sr_dbg("DBG: %s(), chip %d", __func__, chip);
966 if (chip == SER_HID_CHIP_UNKNOWN)
971 sr_dbg("DBG: %s(), searching path for serno %s", __func__, serno);
972 vid_pids = have_chip ? chip_funcs->vid_pid_items : NULL;
973 list = list_paths_for_vids_pids(vid_pids);
974 sr_dbg("DBG: %s(), vid/pid list for chip type %p", __func__, list);
978 for (tmplist = list; tmplist; tmplist = tmplist->next) {
979 path = get_hidapi_path_copy(tmplist->data);
980 sr_dbg("DBG: %s(), checking %s", __func__, path);
981 serno_matched = check_serno(path, serno);
990 path = g_strdup(matched->data);
991 sr_dbg("DBG: %s(), match, path %s", __func__, path);
993 g_slist_free_full(list, g_free);
996 sr_dbg("DBG: %s(), searching path, chip %d", __func__, chip);
997 vid_pids = have_chip ? chip_funcs->vid_pid_items : NULL;
998 list = list_paths_for_vids_pids(vid_pids);
1001 for (tmplist = list; tmplist; tmplist = tmplist->next) {
1002 path = tmplist->data;
1003 sr_dbg("DBG: %s(), path %s", __func__, path);
1005 matched = matched2 = NULL;
1007 /* List already only contains specified chip. */
1009 path = matched->data;
1010 sr_dbg("DBG: %s(), match 1 %s", __func__, path);
1011 matched2 = list->next;
1013 path = matched2->data;
1014 sr_dbg("DBG: %s(), match 2 %s", __func__, path);
1017 /* Works for lists with one or multiple chips. Saves indentation. */
1018 for (tmplist = list; tmplist; tmplist = tmplist->next) {
1021 path = tmplist->data;
1022 rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
1023 if (rc || !ser_hid_chip_find_name_vid_pid(vid, pid))
1027 sr_dbg("DBG: %s(), match 1 %s", __func__, path);
1032 sr_dbg("DBG: %s(), match 2 %s", __func__, path);
1037 g_slist_free_full(list, g_free);
1041 * TODO Optionally fail harder, expect users to provide
1042 * unambiguous cable specs.
1045 sr_info("More than one cable matches, random pick.");
1046 path = get_hidapi_path_copy(matched->data);
1047 sr_dbg("DBG: %s(), match, path %s", __func__, path);
1049 g_slist_free_full(list, g_free);
1051 if (have_path && !have_chip) {
1052 sr_dbg("DBG: %s(), searching chip for path %s", __func__, path);
1054 rc = ser_hid_hidapi_get_vid_pid(path, &vid, &pid);
1055 sr_dbg("DBG: %s(), rc %d, VID:PID %04x:%04x", __func__, rc, vid, pid);
1058 name = ser_hid_chip_find_name_vid_pid(vid, pid);
1059 sr_dbg("DBG: %s(), name %s", __func__, name);
1060 if (!name || !*name)
1062 chip = ser_hid_chip_find_enum((char **)&name);
1063 sr_dbg("DBG: %s(), chip %d", __func__, chip);
1064 if (chip == SER_HID_CHIP_UNKNOWN)
1069 sr_dbg("DBG: %s() leave, chip %d, path %s", __func__, chip, path);
1079 /* {{{ transport methods called by the common serial.c code */
1081 /* See if a serial port's name refers to an HID type. */
1082 SR_PRIV int ser_name_is_hid(struct sr_serial_dev_inst *serial)
1089 if (!serial->port || !*serial->port)
1092 /* Accept either "hid" alone, or "hid/" as a prefix. */
1093 if (!g_str_has_prefix(serial->port, SER_HID_CONN_PREFIX))
1095 off = strlen(SER_HID_CONN_PREFIX);
1096 sep = serial->port[off];
1097 if (sep != '\0' && sep != '/')
1103 static int ser_hid_open(struct sr_serial_dev_inst *serial, int flags)
1105 enum ser_hid_chip_t chip;
1106 char *usbpath, *serno;
1111 if (ser_hid_setup_funcs(serial) != 0) {
1112 sr_err("Cannot determine HID communication library.");
1116 rc = ser_hid_parse_conn_spec(serial, serial->port,
1117 &chip, &usbpath, &serno);
1122 * When a serial number was specified, or when the chip type or
1123 * the USB path were not specified, do a search to determine the
1124 * device's USB path.
1126 if (!chip || !usbpath || serno) {
1127 sr_dbg("DBG: %s(), searching ...", __func__);
1128 rc = ser_hid_chip_search(&chip, &usbpath, serno);
1134 * Open the HID device. Only store chip type and device handle
1135 * when open completes successfully.
1137 serial->hid_chip = chip;
1138 if (ser_hid_setup_funcs(serial) != 0) {
1139 sr_err("Cannot determine HID chip specific routines.");
1142 if (usbpath && *usbpath)
1143 serial->usb_path = usbpath;
1144 if (serno && *serno)
1145 serial->usb_serno = serno;
1147 rc = ser_hid_hidapi_open_dev(serial);
1149 sr_err("Failed to open HID device.");
1150 serial->hid_chip = 0;
1151 g_free(serial->usb_path);
1152 serial->usb_path = NULL;
1153 g_free(serial->usb_serno);
1154 serial->usb_serno = NULL;
1157 sr_dbg("DBG: %s() done, OK", __func__);
1159 if (!serial->rcv_buffer)
1160 serial->rcv_buffer = g_string_sized_new(SER_HID_CHUNK_SIZE);
1165 static int ser_hid_close(struct sr_serial_dev_inst *serial)
1167 sr_dbg("DBG: %s()", __func__);
1168 ser_hid_hidapi_close_dev(serial);
1173 static int ser_hid_set_params(struct sr_serial_dev_inst *serial,
1174 int baudrate, int bits, int parity, int stopbits,
1175 int flowcontrol, int rts, int dtr)
1179 sr_dbg("DBG: %s() enter", __func__);
1180 if (ser_hid_setup_funcs(serial) != 0)
1182 sr_dbg("DBG: %s() chip funcs set", __func__);
1183 if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->set_params)
1185 sr_dbg("DBG: %s() set params avail", __func__);
1186 rc = serial->hid_chip_funcs->set_params(serial,
1187 baudrate, bits, parity, stopbits,
1188 flowcontrol, rts, dtr);
1189 sr_dbg("DBG: %s() set params rc %d", __func__, rc);
1194 static int ser_hid_setup_source_add(struct sr_session *session,
1195 struct sr_serial_dev_inst *serial, int events, int timeout,
1196 sr_receive_data_callback cb, void *cb_data)
1198 return ser_hid_hidapi_setup_source_add(session, serial,
1199 events, timeout, cb, cb_data);
1202 static int ser_hid_setup_source_remove(struct sr_session *session,
1203 struct sr_serial_dev_inst *serial)
1205 return ser_hid_hidapi_setup_source_remove(session, serial);
1208 static GSList *ser_hid_list(GSList *list, sr_ser_list_append_t append)
1210 return ser_hid_hidapi_list(list, append);
1213 static GSList *ser_hid_find_usb(GSList *list, sr_ser_find_append_t append,
1214 uint16_t vendor_id, uint16_t product_id)
1216 return ser_hid_hidapi_find_usb(list, append, vendor_id, product_id);
1219 static int ser_hid_flush(struct sr_serial_dev_inst *serial)
1221 if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->flush)
1224 return serial->hid_chip_funcs->flush(serial);
1227 static int ser_hid_drain(struct sr_serial_dev_inst *serial)
1229 if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->drain)
1232 return serial->hid_chip_funcs->drain(serial);
1235 static int ser_hid_write(struct sr_serial_dev_inst *serial,
1236 const void *buf, size_t count,
1237 int nonblocking, unsigned int timeout_ms)
1239 int total, max_chunk, chunk_len;
1242 if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->write_bytes)
1244 if (!serial->hid_chip_funcs->max_bytes_per_request)
1247 sr_dbg("DBG: %s() shall send %zu bytes TX data.", __func__, count);
1249 max_chunk = serial->hid_chip_funcs->max_bytes_per_request;
1252 if (max_chunk && chunk_len > max_chunk)
1253 chunk_len = max_chunk;
1254 rc = serial->hid_chip_funcs->write_bytes(serial, buf, chunk_len);
1256 sr_err("Error sending transmit data to HID device.");
1259 if (rc != chunk_len) {
1260 sr_warn("Short transmission to HID device (%d/%d bytes)?",
1268 * Need we wait here? For data to drain through the slow
1269 * UART. Not all UART-over-HID chips will have FIFOs.
1280 static int ser_hid_read(struct sr_serial_dev_inst *serial,
1281 void *buf, size_t count,
1282 int nonblocking, unsigned int timeout_ms)
1284 gint64 deadline_us, now_us;
1285 uint8_t buffer[SER_HID_CHUNK_SIZE];
1289 sr_dbg("DBG: %s() count %zd, block %d, to %u", __func__,
1290 count, !nonblocking, timeout_ms);
1292 if (!serial->hid_chip_funcs || !serial->hid_chip_funcs->read_bytes)
1294 if (!serial->hid_chip_funcs->max_bytes_per_request)
1298 * Immediately satisfy the caller's request from the RX buffer
1299 * if the requested amount of data is available already.
1301 if (sr_ser_has_queued_data(serial) >= count) {
1302 rc = sr_ser_unqueue_rx_data(serial, buf, count);
1307 * When a timeout was specified, then determine the deadline
1308 * where to stop reception.
1311 now_us = 0; /* Silence a (false) compiler warning. */
1313 now_us = g_get_monotonic_time();
1314 deadline_us = now_us + timeout_ms * 1000;
1318 * Keep receiving from the port until the caller's requested
1319 * amount of data has become available, or the timeout has
1320 * expired. In the absence of a timeout, stop reading when an
1321 * attempt no longer yields receive data.
1323 * This implementation assumes that applications will call the
1324 * read routine often enough, or that reception continues in
1325 * background, such that data is not lost and hardware and
1326 * software buffers won't overrun.
1330 * Determine the timeout (in milliseconds) for this
1331 * iteration. The 'now_us' timestamp was initially
1332 * determined above, and gets updated at the bottom of
1336 timeout_ms = (deadline_us - now_us) / 1000;
1339 } else if (nonblocking) {
1346 * Check the HID transport for the availability of more
1349 rc = serial->hid_chip_funcs->read_bytes(serial,
1350 buffer, sizeof(buffer), timeout_ms);
1352 sr_dbg("DBG: %s() read error %d.", __func__, rc);
1356 sr_dbg("DBG: %s() queueing %d bytes.", __func__, rc);
1357 ser_hid_mask_databits(serial, buffer, rc);
1358 sr_ser_queue_rx_data(serial, buffer, rc);
1360 got = sr_ser_has_queued_data(serial);
1363 * Stop reading when the requested amount is available,
1364 * or when the timeout has expired.
1366 * TODO Consider whether grabbing all RX data is more
1367 * desirable. Implementing this approach requires a cheap
1368 * check for the availability of more data on the USB level.
1372 if (nonblocking && !rc)
1375 now_us = g_get_monotonic_time();
1376 if (now_us >= deadline_us) {
1377 sr_dbg("DBG: %s() read loop timeout.", __func__);
1384 * Satisfy the caller's demand for receive data from previously
1385 * queued incoming data.
1389 sr_dbg("DBG: %s() passing %d bytes.", __func__, got);
1390 rc = sr_ser_unqueue_rx_data(serial, buf, count);
1395 static struct ser_lib_functions serlib_hid = {
1396 .open = ser_hid_open,
1397 .close = ser_hid_close,
1398 .flush = ser_hid_flush,
1399 .drain = ser_hid_drain,
1400 .write = ser_hid_write,
1401 .read = ser_hid_read,
1402 .set_params = ser_hid_set_params,
1403 .setup_source_add = ser_hid_setup_source_add,
1404 .setup_source_remove = ser_hid_setup_source_remove,
1405 .list = ser_hid_list,
1406 .find_usb = ser_hid_find_usb,
1407 .get_frame_format = NULL,
1409 SR_PRIV struct ser_lib_functions *ser_lib_funcs_hid = &serlib_hid;
1414 SR_PRIV int ser_name_is_hid(struct sr_serial_dev_inst *serial)
1421 SR_PRIV struct ser_lib_functions *ser_lib_funcs_hid = NULL;