Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
raise UsbToolsError("Invalid URL: %s" % urlstr)
try:
if not urlparts.path:
raise UsbToolsError('URL string is missing device port')
path = urlparts.path.strip('/')
if path == '?' or (not path and urlstr.endswith('?')):
report_devices = True
else:
interface = to_int(path)
report_devices = False
except (IndexError, ValueError):
raise UsbToolsError('Invalid device URL: %s' % urlstr)
candidates, idx = cls.enumerate_candidates(urlparts, vdict, pdict,
default_vendor)
if report_devices:
UsbTools.show_devices(scheme, vdict, pdict, candidates)
raise SystemExit(candidates and
'Please specify the USB device' or
'No USB-Serial device has been detected')
if idx is None:
if len(candidates) > 1:
raise UsbToolsError("%d USB devices match URL '%s'" %
(len(candidates), urlstr))
idx = 0
try:
desc, _ = candidates[idx]
vendor, product = desc[:2]
except IndexError:
raise UsbToolsError('No USB device matches URL %s' %
urlstr) from None
if not vendor:
cvendors = {candidate[0] for candidate in candidates}
# Do not attempt to execute the following calls if the
# device has been closed: the ResourceManager may attempt
# to re-open the device that has been already closed, and
# this may lead to a (native) crash in libusb.
try:
self.set_bitmode(0, Ftdi.BitMode.RESET)
self.set_latency_timer(self.LATENCY_MAX)
release_interface(dev, self._index - 1)
except FtdiError as exc:
self.log.warning('FTDI device may be gone: %s', exc)
try:
self._usb_dev.attach_kernel_driver(self._index - 1)
except (NotImplementedError, USBError):
pass
self._usb_dev = None
UsbTools.release_device(dev)
loglevel = max(DEBUG, ERROR - (10 * args.verbose))
loglevel = min(ERROR, loglevel)
if debug:
formatter = Formatter('%(asctime)s.%(msecs)03d %(name)-20s '
'%(message)s', '%H:%M:%S')
else:
formatter = Formatter('%(message)s')
FtdiLogger.set_formatter(formatter)
FtdiLogger.set_level(loglevel)
FtdiLogger.log.addHandler(StreamHandler(stderr))
if args.virtual:
from pyftdi.usbtools import UsbTools
# Force PyUSB to use PyFtdi test framework for USB backends
UsbTools.BACKENDS = ('pyftdi.tests.backend.usbvirt', )
# Ensure the virtual backend can be found and is loaded
backend = UsbTools.find_backend()
loader = backend.create_loader()()
loader.load(args.virtual)
try:
add_custom_devices(Ftdi, args.vidpid)
except ValueError as exc:
argparser.error(str(exc))
eeprom = FtdiEeprom()
eeprom.open(args.device)
if args.erase:
eeprom.erase()
if args.serial_number:
eeprom.set_serial_number(args.serial_number)
"""Open a new interface to the specified FTDI device in bitbang mode.
Bitbang enables direct read or write to FTDI GPIOs.
:param url: a FTDI URL selector
:param direction: a bitfield specifying the FTDI GPIO direction,
where high level defines an output, and low level defines an
input
:param latency: low-level latency to select the USB FTDI poll
delay. The shorter the delay, the higher the host CPU load.
:param baudrate: pace to sequence GPIO exchanges
:param sync: whether to use synchronous or asynchronous bitbang
:return: actual bitbang baudrate in bps
"""
devdesc, interface = self.get_identifiers(url)
device = UsbTools.get_device(devdesc)
return self.open_bitbang_from_device(device, interface,
direction=direction,
latency=latency,
baudrate=baudrate,
sync=sync)
loglevel = max(DEBUG, ERROR - (10 * args.verbose))
loglevel = min(ERROR, loglevel)
if debug:
formatter = Formatter('%(asctime)s.%(msecs)03d %(name)-20s '
'%(message)s', '%H:%M:%S')
else:
formatter = Formatter('%(message)s')
FtdiLogger.set_formatter(formatter)
FtdiLogger.set_level(loglevel)
FtdiLogger.log.addHandler(StreamHandler(stderr))
if args.virtual:
from pyftdi.usbtools import UsbTools
# Force PyUSB to use PyFtdi test framework for USB backends
UsbTools.BACKENDS = ('pyftdi.tests.backend.usbvirt', )
# Ensure the virtual backend can be found and is loaded
backend = UsbTools.find_backend()
loader = backend.create_loader()()
loader.load(args.virtual)
try:
add_custom_devices(Ftdi, args.vidpid)
except ValueError as exc:
argparser.error(str(exc))
Ftdi.show_devices()
except (ImportError, IOError, NotImplementedError, ValueError) as exc:
print('\nError: %s' % exc, file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
loglevel = max(DEBUG, ERROR - (10 * (args.verbose or 0)))
loglevel = min(ERROR, loglevel)
if debug:
formatter = Formatter('%(asctime)s.%(msecs)03d %(name)-20s '
'%(message)s', '%H:%M:%S')
else:
formatter = Formatter('%(message)s')
FtdiLogger.set_formatter(formatter)
FtdiLogger.set_level(loglevel)
FtdiLogger.log.addHandler(StreamHandler(stderr))
if args.virtual:
from pyftdi.usbtools import UsbTools
# Force PyUSB to use PyFtdi test framework for USB backends
UsbTools.BACKENDS = ('pyftdi.tests.backend.usbvirt', )
# Ensure the virtual backend can be found and is loaded
backend = UsbTools.find_backend()
loader = backend.create_loader()()
loader.load(args.virtual)
try:
add_custom_devices(Ftdi, args.vidpid)
except ValueError as exc:
argparser.error(str(exc))
full_mode = args.fullmode if platform != 'win32' else False
init_term(full_mode)
miniterm = MiniTerm(device=args.device,
baudrate=to_bps(args.baudrate),
parity='N',
rtscts=args.hwflow,
def get_identifiers(cls, url: str) -> Tuple[UsbDeviceDescriptor, int]:
"""Extract the identifiers of an FTDI device from URL, if any
:param url: input URL to parse
"""
return UsbTools.parse_url(url,
cls.SCHEME, cls.VENDOR_IDS, cls.PRODUCT_IDS,
cls.DEFAULT_VENDOR)
:param bool nocache: bypass cache to re-enumerate USB devices on
the host
:return: a list of 2-tuple (UsbDeviceDescriptor, interface count)
"""
cls.Lock.acquire()
try:
devs = set()
for vid, pid in vps:
# TODO optimize useless loops
devs.update(UsbTools._find_devices(vid, pid, nocache))
devices = set()
for dev in devs:
ifcount = max([cfg.bNumInterfaces for cfg in dev])
# TODO: handle / is serial number strings
sernum = UsbTools.get_string(dev, dev.iSerialNumber)
description = UsbTools.get_string(dev, dev.iProduct)
descriptor = UsbDeviceDescriptor(dev.idVendor, dev.idProduct,
dev.bus, dev.address,
sernum, None, description)
devices.add((descriptor, ifcount))
return list(devices)
finally:
cls.Lock.release()