[PATCH v2] Add api to get index by usb bus and port number

Nicolas Sugino nsugino at 3way.com.ar
Mon Jan 7 18:55:18 UTC 2019


This allows to get the device index based on the usb bus and port number

Signed-off-by: Nicolas Sugino <nsugino at 3way.com.ar>
---
 include/rtl-sdr.h | 12 ++++++++++++
 src/librtlsdr.c   | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 53 insertions(+)

diff --git a/include/rtl-sdr.h b/include/rtl-sdr.h
index 3ed13ae..d1e3c1e 100644
--- a/include/rtl-sdr.h
+++ b/include/rtl-sdr.h
@@ -60,6 +60,18 @@ RTLSDR_API int rtlsdr_get_device_usb_strings(uint32_t index,
  */
 RTLSDR_API int rtlsdr_get_index_by_serial(const char *serial);
 
+/*!
+ * Get device index by USB bus and port number
+ *
+ * \param bus bus number where the device is connected
+ * \param port port number where the device is connected
+ * \return device index of first device where the name matched
+ * \return -1 on libusb initialization failure
+ * \return -2 if no devices were found at all
+ * \return -3 if devices were found, but none with matching bus and port
+ */
+RTLSDR_API int rtlsdr_get_index_by_usb_bus_port(uint8_t bus, uint8_t port);
+
 RTLSDR_API int rtlsdr_open(rtlsdr_dev_t **dev, uint32_t index);
 
 RTLSDR_API int rtlsdr_close(rtlsdr_dev_t *dev);
diff --git a/src/librtlsdr.c b/src/librtlsdr.c
index 89ec903..12a196f 100644
--- a/src/librtlsdr.c
+++ b/src/librtlsdr.c
@@ -1436,6 +1436,47 @@ int rtlsdr_get_index_by_serial(const char *serial)
 	return -3;
 }
 
+int rtlsdr_get_index_by_usb_bus_port(uint8_t bus, uint8_t port)
+{
+	int r = -2, index = -3;
+	int i;
+	libusb_context *ctx;
+	libusb_device **list;
+	struct libusb_device_descriptor dd;
+	uint8_t reg, dev_bus, dev_port;
+	ssize_t cnt;
+
+	r = libusb_init(&ctx);
+	if(r < 0){
+		return -1;
+	}
+
+	cnt = libusb_get_device_list(ctx, &list);
+	if (!cnt) {
+		libusb_exit(ctx);
+		return -2;
+	}
+
+	for (i = 0; i < cnt; i++) {
+		libusb_get_device_descriptor(list[i], &dd);
+
+		if (find_known_device(dd.idVendor, dd.idProduct)) {
+			index == -3 ? index = 0 : index++;
+			dev_bus = libusb_get_bus_number(list[i]);
+			dev_port = libusb_get_port_number(list[i]);
+			if(bus == dev_bus && port == dev_port) {
+				break;
+			}
+		}
+	}
+
+	libusb_free_device_list(list, 1);
+
+	libusb_exit(ctx);
+
+	return index;
+}
+
 int rtlsdr_open(rtlsdr_dev_t **out_dev, uint32_t index)
 {
 	int r;
-- 
2.13.6



More information about the osmocom-sdr mailing list