@@ -68,11 +68,14 @@ def get_ports(device_id):
6868 import usb
6969 vid , pid = [int (x , 16 ) for x in device_id .split (":" )]
7070
71- ports += [
72- UsbPort (d )
73- for d in usb .core .find (idVendor = vid , idProduct = pid , find_all = True )
74- if not d .is_kernel_driver_active (1 )
75- ]
71+ try :
72+ ports += [
73+ UsbPort (usb , d )
74+ for d in usb .core .find (idVendor = vid , idProduct = pid , find_all = True )
75+ if not d .is_kernel_driver_active (1 )
76+ ]
77+ except usb .core .USBError as e :
78+ raise PortError ("Failed to open USB:\n %s" % str (e ))
7679
7780 # MacOS is not playing nicely with the serial drivers for the bootloader
7881 if platform .system () != "Darwin" or use_pyserial :
@@ -127,7 +130,8 @@ def read(self, length):
127130 raise PortError ("Failed to read from serial port:\n %s" % str (e ))
128131
129132class UsbPort (object ):
130- def __init__ (self , device ):
133+ def __init__ (self , usb , device ):
134+ self .usb = usb
131135 self .device = device
132136 usb_interface = device .configurations ()[0 ].interfaces ()[1 ]
133137 self .OUT = usb_interface .endpoints ()[0 ]
@@ -143,19 +147,24 @@ def __exit__(self, exc_type, exc_val, exc_tb):
143147 pass
144148
145149 def write (self , data ):
146- self .OUT .write (data )
150+ try :
151+ self .OUT .write (data )
152+ except self .usb .core .USBError as e :
153+ raise PortError ("Failed to write to USB:\n %s" % str (e ))
147154
148155 def flush (self ):
149156 # i don't think there's a comparable function on pyusb endpoints
150157 pass
151158
152159 def read (self , length ):
153- if length > 0 :
154- data = self .IN .read (length )
155- return bytearray (data )
156- else :
157- return ""
158-
160+ try :
161+ if length > 0 :
162+ data = self .IN .read (length )
163+ return bytearray (data )
164+ else :
165+ return ""
166+ except self .usb .core .USBError as e :
167+ raise PortError ("Failed to read from USB:\n %s" % str (e ))
159168
160169def _mirror_byte (b ):
161170 return bit_reverse_table [to_int (b )]
0 commit comments