From bb37f1ed4d7d331d0483109979bc4366f47ddc14 Mon Sep 17 00:00:00 2001 From: Gwenhael Goavec-Merou Date: Thu, 12 Mar 2026 18:45:25 +0100 Subject: [PATCH] dirtyJtag: rework error messages in constructor. Added a method to close USB (and to avoids to have multiple time the same piece of code) --- src/dirtyJtag.cpp | 42 ++++++++++++++++++++++++++---------------- src/dirtyJtag.hpp | 3 +++ 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/src/dirtyJtag.cpp b/src/dirtyJtag.cpp index d165ac6..e8fa7e3 100644 --- a/src/dirtyJtag.cpp +++ b/src/dirtyJtag.cpp @@ -67,41 +67,51 @@ DirtyJtag::DirtyJtag(uint32_t clkHz, int8_t verbose, uint16_t vid, uint16_t pid) { int ret; - if (libusb_init(&usb_ctx) < 0) { - cerr << "libusb init failed" << endl; - throw std::exception(); - } + if (libusb_init(&usb_ctx) < 0) + throw std::runtime_error("DirtyJtag: libusb init failed"); dev_handle = libusb_open_device_with_vid_pid(usb_ctx, vid, pid); if (!dev_handle) { - cerr << "fails to open device" << endl; libusb_exit(usb_ctx); - throw std::exception(); + throw std::runtime_error("DirtyJtag: fails to open device"); } ret = libusb_claim_interface(dev_handle, DIRTYJTAG_INTF); if (ret) { - cerr << "libusb error while claiming DirtyJTAG interface" << endl; libusb_close(dev_handle); + dev_handle = NULL; libusb_exit(usb_ctx); - throw std::exception(); + usb_ctx = NULL; + throw std::runtime_error("DirtyJtag: libusb error while claiming interface"); } - if (!getVersion()) - throw std::runtime_error("Fail to get version"); + if (!getVersion()) { + close_usb(); + throw std::runtime_error("DirtyJtag: Fail to get version"); + } if (setClkFreq(clkHz) < 0) { - cerr << "Fail to set frequency" << endl; - throw std::exception(); + close_usb(); + throw std::runtime_error("Fail to set frequency"); + } +} + +void DirtyJtag::close_usb() +{ + if (dev_handle) { + libusb_release_interface(dev_handle, DIRTYJTAG_INTF); + libusb_close(dev_handle); + dev_handle = NULL; + } + if (usb_ctx) { + libusb_exit(usb_ctx); + usb_ctx = NULL; } } DirtyJtag::~DirtyJtag() { - if (dev_handle) - libusb_close(dev_handle); - if (usb_ctx) - libusb_exit(usb_ctx); + close_usb(); } bool DirtyJtag::getVersion() diff --git a/src/dirtyJtag.hpp b/src/dirtyJtag.hpp index 39e30bf..c8c0223 100644 --- a/src/dirtyJtag.hpp +++ b/src/dirtyJtag.hpp @@ -76,8 +76,11 @@ class DirtyJtag : public JtagInterface { bool getVersion(); bool _set_gpio_level(uint8_t gpio, uint8_t val); + /* USB */ + void close_usb(); libusb_device_handle *dev_handle; libusb_context *usb_ctx; + uint8_t _tdi; uint8_t _tms; uint8_t _version;