Skip to content

Commit c91727b

Browse files
committed
tools: Fix pydfu.py to work with old and new versions of PyUSB
Update pydfu.py to match with the version from openmv. I just updated the openmv version to work with both of the PyUSB 1.0.0.b1 and 1.0.0.b2 See: https://github.com/walac/pyusb/blob/master/ReleaseNotes.rst
1 parent 9f76dcd commit c91727b

1 file changed

Lines changed: 22 additions & 13 deletions

File tree

tools/pydfu.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,16 @@
6161
# USB DFU interface
6262
__DFU_INTERFACE = 0
6363

64+
import inspect
65+
if 'length' in inspect.getargspec(usb.util.get_string).args:
66+
# PyUSB 1.0.0.b1 has the length argument
67+
def get_string(dev, index):
68+
return usb.util.get_string(dev, 255, index)
69+
else:
70+
# PyUSB 1.0.0.b2 dropped the length argument
71+
def get_string(dev, index):
72+
return usb.util.get_string(dev, index)
73+
6474

6575
def init():
6676
"""Initializes the found DFU device so that we can program it."""
@@ -216,12 +226,15 @@ def exit_dfu():
216226
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE,
217227
None, __TIMEOUT)
218228

219-
# Execute last command
220-
if get_status() != __DFU_STATE_DFU_MANIFEST:
221-
print("Failed to reset device")
229+
try:
230+
# Execute last command
231+
if get_status() != __DFU_STATE_DFU_MANIFEST:
232+
print("Failed to reset device")
222233

223-
# Release device
224-
usb.util.dispose_resources(__dev)
234+
# Release device
235+
usb.util.dispose_resources(__dev)
236+
except:
237+
pass
225238

226239

227240
def named(values, names):
@@ -239,7 +252,7 @@ def consume(fmt, data, names):
239252

240253
def cstring(string):
241254
"""Extracts a null-terminated string from a byte array."""
242-
return string.split(b'\0', 1)[0]
255+
return string.decode('utf-8').split('\0', 1)[0]
243256

244257

245258
def compute_crc(data):
@@ -360,7 +373,7 @@ def get_dfu_devices(*args, **kwargs):
360373
Additional filters (like idProduct and idVendor) can be passed in to
361374
refine the search.
362375
"""
363-
376+
# convert to list for compatibility with newer pyusb
364377
return list(usb.core.find(*args, find_all=True,
365378
custom_match=FilterDFU(), **kwargs))
366379

@@ -376,7 +389,7 @@ def get_memory_layout(device):
376389
"""
377390
cfg = device[0]
378391
intf = cfg[(0, 0)]
379-
mem_layout_str = usb.util.get_string(device, 255, intf.iInterface)
392+
mem_layout_str = get_string(device, intf.iInterface)
380393
mem_layout = mem_layout_str.split('/')
381394
addr = int(mem_layout[1], 0)
382395
segments = mem_layout[2].split(',')
@@ -504,11 +517,7 @@ def main():
504517
list_dfu_devices(idVendor=__VID, idProduct=__PID)
505518
return
506519

507-
try:
508-
init()
509-
except ValueError as er:
510-
print(str(er))
511-
sys.exit(1)
520+
init()
512521

513522
if args.mass_erase:
514523
print ("Mass erase...")

0 commit comments

Comments
 (0)