本文整理汇总了Python中usb1.USBContext方法的典型用法代码示例。如果您正苦于以下问题:Python usb1.USBContext方法的具体用法?Python usb1.USBContext怎么用?Python usb1.USBContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类usb1
的用法示例。
在下文中一共展示了usb1.USBContext方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: listAvailableDevices
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def listAvailableDevices(self):
ports = {}
try:
with usb1.USBContext() as context:
for device in context.getDeviceIterator(skip_on_error=True):
vid = device.getVendorID()
pid = device.getProductID()
port_id = "%d:%d" % (vid, pid)
ports[port_id] = {
'vendor_id': device.getVendorID(),
'product_id': device.getProductID(),
'product_name': device.getProduct()
}
except usb1.USBErrorPipe as e:
self._logger.error("USB Error: %s", e)
except usb1.USBErrorIO:
self._logger.error("USB Link can't be opened")
return ports
#
# Setup USB device to start sending receiving data
#
示例2: FindDevices
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def FindDevices(cls, setting_matcher, device_matcher=None,
usb_info='', timeout_ms=None):
"""Find and yield the devices that match.
Args:
setting_matcher: Function that returns the setting to use given a
usb1.USBDevice, or None if the device doesn't have a valid setting.
device_matcher: Function that returns True if the given UsbHandle is
valid. None to match any device.
usb_info: Info string describing device(s).
timeout_ms: Default timeout of commands in milliseconds.
Yields:
Unopened UsbHandle instances
"""
ctx = usb1.USBContext()
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
handle = cls(device, setting, usb_info=usb_info, timeout_ms=timeout_ms)
if device_matcher is None or device_matcher(handle):
yield handle
示例3: enumerate
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def enumerate(cls) -> Iterable["WebUsbTransport"]:
if cls.context is None:
cls.context = usb1.USBContext()
cls.context.open()
atexit.register(cls.context.close)
devices = []
for dev in cls.context.getDeviceIterator(skip_on_error=True):
usb_id = (dev.getVendorID(), dev.getProductID())
if usb_id not in TREZORS:
continue
if not is_vendor_class(dev):
continue
try:
# workaround for issue #223:
# on certain combinations of Windows USB drivers and libusb versions,
# Trezor is returned twice (possibly because Windows know it as both
# a HID and a WebUSB device), and one of the returned devices is
# non-functional.
dev.getProduct()
devices.append(WebUsbTransport(dev))
except:
pass
return devices
示例4: FindDevices
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def FindDevices(cls, setting_matcher, device_matcher=None,
usb_info='', timeout_ms=None):
"""Find and yield the devices that match.
Args:
setting_matcher: Function that returns the setting to use given a
usb1.USBDevice, or None if the device doesn't have a valid setting.
device_matcher: Function that returns True if the given UsbHandle is
valid. None to match any device.
usb_info: Info string describing device(s).
timeout_ms: Default timeout of commands in milliseconds.
Yields:
UsbHandle instances
"""
ctx = usb1.USBContext()
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
handle = cls(device, setting, usb_info=usb_info, timeout_ms=timeout_ms)
if device_matcher is None or device_matcher(handle):
yield handle
示例5: find
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def find(cls, path):
if not path.startswith("usb"):
return
log.debug("using libusb-{0}.{1}.{2}".format(*libusb.getVersion()[0:3]))
usb_or_none = re.compile(r'^(usb|)$')
usb_vid_pid = re.compile(r'^usb(:[0-9a-fA-F]{4})(:[0-9a-fA-F]{4})?$')
usb_bus_dev = re.compile(r'^usb(:[0-9]{1,3})(:[0-9]{1,3})?$')
match = None
for regex in (usb_vid_pid, usb_bus_dev, usb_or_none):
m = regex.match(path)
if m is not None:
log.debug("path matches {0!r}".format(regex.pattern))
if regex is usb_vid_pid:
match = [int(s.strip(':'), 16) for s in m.groups() if s]
match = dict(zip(['vid', 'pid'], match))
if regex is usb_bus_dev:
match = [int(s.strip(':'), 10) for s in m.groups() if s]
match = dict(zip(['bus', 'adr'], match))
if regex is usb_or_none:
match = dict()
break
else:
return None
with libusb.USBContext() as context:
devices = context.getDeviceList(skip_on_error=True)
vid, pid = match.get('vid'), match.get('pid')
bus, dev = match.get('bus'), match.get('adr')
if vid is not None:
devices = [d for d in devices if d.getVendorID() == vid]
if pid is not None:
devices = [d for d in devices if d.getProductID() == pid]
if bus is not None:
devices = [d for d in devices if d.getBusNumber() == bus]
if dev is not None:
devices = [d for d in devices if d.getDeviceAddress() == dev]
return [(d.getVendorID(), d.getProductID(), d.getBusNumber(),
d.getDeviceAddress()) for d in devices]
示例6: __init__
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def __init__(self, usb_bus, dev_adr):
self.context = libusb.USBContext()
self.open(usb_bus, dev_adr)
示例7: openLink
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def openLink(self, port_id, sendEndpoint, receiveEndpoint):
if port_id is not None:
if self._dev_handle is None:
try:
port_parts = port_id.split(':') #port id is "vid:pid"
vid = int(port_parts[0])
pid = int(port_parts[1])
self._context = usb1.USBContext()
self._dev_handle = self._context.openByVendorIDAndProductID(vid, pid, skip_on_error=True)
if self._dev_handle is not None:
self._hasError = False
self._dev_handle.claimInterface(0)
self._port_id = port_id
self._sendEP = sendEndpoint
self._receiveEP = receiveEndpoint
#self._incomingQueue = IncomingQueue(self._eventListener)
#self._incomingQueue.start()
#self._linkReader = LinkReader(self._dev_handle, self._context, receiveEndpoint, self._eventListener, self._incomingQueue, self)
self._linkReader = LinkReader(self._dev_handle, self._context, receiveEndpoint, self._eventListener, self)
self._linkReader.start()
self._serialLoggerEnabled and self._serialLogger.debug("Connected to USB Device -> Vendor: 0x%04x, Product: 0x%04x" % (vid, pid))
self._eventListener.onLinkOpened()
return True
except usb1.USBErrorBusy:
return False
else:
return True #It was already opened
return False
#
# closes communication with the USB device
#
示例8: detect_printer
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def detect_printer(self):
self._device_id = 0
with usb1.USBContext() as usbcontext:
for device in usbcontext.getDeviceIterator(skip_on_error=True):
vendor_id = device.getVendorID()
device_id = device.getProductID()
try:
device_name = device.getProduct()
except:
device_name = 'unknown'
self._logger.debug("Found device '{}' with Vendor ID: {:#06X}, USB ID: {:#06X}".format(device_name, vendor_id, device_id))
# get USB interface details to diagnose connectivity issues
for configuration in device.iterConfigurations():
for interface in configuration:
for setting in interface:
self._logger.debug(
" setting number: 0x{:02x}, class: 0x{:02x}, subclass: 0x{:02x}, protocol: 0x{:02x}, #endpoints: {}, descriptor: {}".format(
setting.getNumber(), setting.getClass(), setting.getSubClass(),
setting.getProtocol(), setting.getNumEndpoints(), setting.getDescriptor()))
for endpoint in setting:
self._logger.debug(
" endpoint address: 0x{:02x}, attributes: 0x{:02x}, max packet size: {}".format(
endpoint.getAddress(), endpoint.getAttributes(),
endpoint.getMaxPacketSize()))
if vendor_id in self.VENDOR_IDS:
vendor_name = self.VENDOR_IDS[vendor_id]
if device_id in self.PRINTER_IDS[vendor_name]:
self._logger.info("Found a {} {}".format(vendor_name, self.PRINTER_IDS[vendor_name][device_id]))
self._vendor_id = vendor_id
self._vendor_name = vendor_name
self._device_id = device_id
break
else:
raise flashforge.FlashForgeError("Found an unsupported {} printer '{}' with USB ID: {:#06X}".format(vendor_name, device_name, device_id))
return self._device_id != 0
示例9: FindDevicesSafe
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def FindDevicesSafe(cls, setting_matcher, device_matcher=None,
usb_info='', timeout_ms=None):
"""Safe version of FindDevices.
Like FindDevices, but catch USB exceptions as devices are iterated through.
Yields:
Unopened UsbHandle instances.
"""
ctx = usb1.USBContext()
try:
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
try:
handle = cls(device, setting, usb_info=usb_info,
timeout_ms=timeout_ms)
if device_matcher is None or device_matcher(handle):
yield handle
except (usb1.USBErrorOther, usb1.USBErrorNoDevice) as e:
logging.error(
'Failed to open USB device, is user in group plugdev? %s', e)
continue
except usb1.USBError as e:
logging.error('Failed to get device list: %s', e)
示例10: _find_devices
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def _find_devices(cls, setting_matcher, device_matcher=None, usb_info='', default_transport_timeout_s=None):
"""_find and yield the devices that match.
Parameters
----------
setting_matcher : TODO
Function that returns the setting to use given a ``usb1.USBDevice``, or ``None``
if the device doesn't have a valid setting.
device_matcher : TODO, None
Function that returns ``True`` if the given ``UsbTransport`` is
valid. ``None`` to match any device.
usb_info : str
Info string describing device(s).
default_transport_timeout_s : TODO, None
Default timeout of commands in seconds.
Yields
------
TODO
UsbTransport instances
"""
ctx = usb1.USBContext()
for device in ctx.getDeviceList(skip_on_error=True):
setting = setting_matcher(device)
if setting is None:
continue
transport = cls(device, setting, usb_info=usb_info, default_transport_timeout_s=default_transport_timeout_s)
if device_matcher is None or device_matcher(transport):
yield transport
示例11: getContext
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def getContext(self):
try:
self.context = usb1.USBContext()
self.hasContext = 1
except:
self.hasContext = 0
示例12: iter_open
# 需要导入模块: import usb1 [as 别名]
# 或者: from usb1 import USBContext [as 别名]
def iter_open(cls, name=None, interface_class=None, interface_subclass=None,
interface_protocol=None, serial_number=None, port_path=None,
default_timeout_ms=None):
"""Find and yield locally connected devices that match.
Note that devices are opened (and interfaces claimd) as they are yielded.
Any devices yielded must be Close()'d.
Args:
name: Name to give *all* returned handles, used for logging only.
interface_class: USB interface_class to match.
interface_subclass: USB interface_subclass to match.
interface_protocol: USB interface_protocol to match.
serial_number: USB serial_number to match.
port_path: USB Port path to match, like X-X.X.X
default_timeout_ms: Default timeout in milliseconds of reads/writes on
the handles yielded.
Yields:
UsbHandle instances that match any non-None args given.
Raises:
LibusbWrappingError: When a libusb call errors during open.
"""
ctx = usb1.USBContext()
try:
devices = ctx.getDeviceList(skip_on_error=True)
except libusb1.USBError as exception:
raise usb_exceptions.LibusbWrappingError(
exception, 'Open(name=%s, class=%s, subclass=%s, protocol=%s, '
'serial=%s, port=%s) failed', name, interface_class,
interface_subclass, interface_protocol, serial_number, port_path)
for device in devices:
try:
if (serial_number is not None and
device.getSerialNumber() != serial_number):
continue
if (port_path is not None and
cls._device_to_sysfs_path(device) != port_path):
continue
for setting in device.iterSettings():
if (interface_class is not None and
setting.getClass() != interface_class):
continue
if (interface_subclass is not None and
setting.getSubClass() != interface_subclass):
continue
if (interface_protocol is not None and
setting.getProtocol() != interface_protocol):
continue
yield cls(device, setting, name=name,
default_timeout_ms=default_timeout_ms)
except libusb1.USBError as exception:
if (exception.value !=
libusb1.libusb_error.forward_dict['LIBUSB_ERROR_ACCESS']):
raise
# pylint: disable=too-many-arguments