diff --git a/python/__init__.py b/python/__init__.py index 5d6f3e9fc..e396fb36f 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -315,8 +315,9 @@ class Panda: @staticmethod def usb_connect(serial, claim=True, wait=False): handle, usb_serial, bootstub, bcd = None, None, None, None - context = usb1.USBContext() while 1: + context = usb1.USBContext() + context.open() try: for device in context.getDeviceList(skip_on_error=True): if device.getVendorID() == 0xbbaa and device.getProductID() in (0xddcc, 0xddee): @@ -347,7 +348,7 @@ class Panda: logging.exception("USB connect error") if not wait or handle is not None: break - context = usb1.USBContext() # New context needed so new devices show up + context.close() usb_handle = None if handle is not None: @@ -363,21 +364,21 @@ class Panda: @staticmethod def usb_list(): - context = usb1.USBContext() ret = [] try: - for device in context.getDeviceList(skip_on_error=True): - if device.getVendorID() == 0xbbaa and device.getProductID() in (0xddcc, 0xddee): - try: - serial = device.getSerialNumber() - if len(serial) == 24: - ret.append(serial) - else: - warnings.warn(f"found device with panda descriptors but invalid serial: {serial}", RuntimeWarning) - except Exception: - continue + with usb1.USBContext() as context: + for device in context.getDeviceList(skip_on_error=True): + if device.getVendorID() == 0xbbaa and device.getProductID() in (0xddcc, 0xddee): + try: + serial = device.getSerialNumber() + if len(serial) == 24: + ret.append(serial) + else: + warnings.warn(f"found device with panda descriptors but invalid serial: {serial}", RuntimeWarning) + except Exception: + continue except Exception: - pass + logging.exception("exception while listing pandas") return ret @staticmethod diff --git a/python/dfu.py b/python/dfu.py index 15e018c5b..f724bf15d 100644 --- a/python/dfu.py +++ b/python/dfu.py @@ -27,6 +27,7 @@ class PandaDFU: def usb_connect(dfu_serial: Optional[str]) -> Optional[STBootloaderUSBHandle]: handle = None context = usb1.USBContext() + context.open() for device in context.getDeviceList(skip_on_error=True): if device.getVendorID() == 0x0483 and device.getProductID() == 0xdf11: try: @@ -64,15 +65,15 @@ class PandaDFU: @staticmethod def usb_list() -> List[str]: - context = usb1.USBContext() dfu_serials = [] try: - for device in context.getDeviceList(skip_on_error=True): - if device.getVendorID() == 0x0483 and device.getProductID() == 0xdf11: - try: - dfu_serials.append(device.open().getASCIIStringDescriptor(3)) - except Exception: - pass + with usb1.USBContext() as context: + for device in context.getDeviceList(skip_on_error=True): + if device.getVendorID() == 0x0483 and device.getProductID() == 0xdf11: + try: + dfu_serials.append(device.open().getASCIIStringDescriptor(3)) + except Exception: + pass except Exception: pass return dfu_serials