From fc56ae70ee147c8665a818b95cbd3d2b7a5fd80b Mon Sep 17 00:00:00 2001 From: Igor Biletskyy Date: Thu, 19 Aug 2021 19:06:24 -0700 Subject: [PATCH] Add argument to Panda to connect by serial number (#21905) * Add list() to panda.cc * add default * change var names * comments * advices * revert * ... * .. * connect by serial Co-authored-by: Adeeb Shihadeh --- selfdrive/boardd/panda.cc | 31 ++++++++++++++++++++++++++++--- selfdrive/boardd/panda.h | 2 +- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/selfdrive/boardd/panda.cc b/selfdrive/boardd/panda.cc index d75585065..7930a7d57 100644 --- a/selfdrive/boardd/panda.cc +++ b/selfdrive/boardd/panda.cc @@ -11,8 +11,10 @@ #include "selfdrive/common/swaglog.h" #include "selfdrive/common/util.h" -Panda::Panda() { +Panda::Panda(std::string serial) { // init libusb + ssize_t num_devices; + libusb_device **dev_list = NULL; int err = libusb_init(&ctx); if (err != 0) { goto fail; } @@ -22,8 +24,28 @@ Panda::Panda() { libusb_set_debug(ctx, 3); #endif - dev_handle = libusb_open_device_with_vid_pid(ctx, 0xbbaa, 0xddcc); - if (dev_handle == NULL) { goto fail; } + // connect by serial + num_devices = libusb_get_device_list(ctx, &dev_list); + if (num_devices < 0) { goto fail; } + for (size_t i = 0; i < num_devices; ++i) { + libusb_device_descriptor desc; + libusb_get_device_descriptor(dev_list[i], &desc); + if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { + libusb_open(dev_list[i], &dev_handle); + if (dev_handle == NULL) { goto fail; } + + unsigned char desc_serial[25]; + int ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, sizeof(desc_serial)); + if (ret < 0) { goto fail; } + + if (serial.empty() || serial.compare(reinterpret_cast(desc_serial)) == 0) { + break; + } + libusb_close(dev_handle); + dev_handle = NULL; + } + } + libusb_free_device_list(dev_list, 1); if (libusb_kernel_driver_active(dev_handle, 0) == 1) { libusb_detach_kernel_driver(dev_handle, 0); @@ -47,6 +69,9 @@ Panda::Panda() { fail: cleanup(); + if (dev_list != NULL) { + libusb_free_device_list(dev_list, 1); + } throw std::runtime_error("Error connecting to panda"); } diff --git a/selfdrive/boardd/panda.h b/selfdrive/boardd/panda.h index 92bd7fcf2..d3d929724 100644 --- a/selfdrive/boardd/panda.h +++ b/selfdrive/boardd/panda.h @@ -49,7 +49,7 @@ class Panda { void cleanup(); public: - Panda(); + Panda(std::string serial=""); ~Panda(); std::atomic connected = true;