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

Signed-off-by: Nicolas Sugino <[email protected]>
---
 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..eca093a 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++) {
+               dev_bus = libusb_get_bus_number(list[i]);
+               dev_port = libusb_get_port_number(list[i]);
+
+               libusb_get_device_descriptor(list[i], &dd);
+
+               if (find_known_device(dd.idVendor, dd.idProduct) &&
+                  bus == dev_bus && port == dev_port) {
+                       index = i;
+                       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

Reply via email to