Skip to content

Commit

Permalink
Do not wait for USB for non-USB HID devices
Browse files Browse the repository at this point in the history
  • Loading branch information
dhalbert committed Nov 29, 2023
1 parent 30b7cda commit 426f3b8
Showing 1 changed file with 26 additions and 18 deletions.
44 changes: 26 additions & 18 deletions adafruit_hid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,32 @@

try:
from typing import Sequence
import usb_hid
except ImportError:
pass

# usb_hid may not exist on some boards that still provide BLE or other HID devices.
try:
from usb_hid import Device
except ImportError:
Device = None

__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_HID.git"


def find_device(
devices: Sequence[usb_hid.Device],
devices: Sequence[object],
*,
usage_page: int,
usage: int,
timeout: int = None,
) -> usb_hid.Device:
) -> object:
"""Search through the provided sequence of devices to find the one with the matching
usage_page and usage.
:param timeout: Time in seconds to wait for USB to become ready before timing out.
Defaults to None to wait indefinitely."""
Defaults to None to wait indefinitely.
Ignored if device is not a `usb_hid.Device`; it might be BLE, for instance."""

if hasattr(devices, "send_report"):
devices = [devices] # type: ignore
Expand All @@ -63,20 +69,22 @@ def find_device(
if device is None:
raise ValueError("Could not find matching HID device.")

if supervisor is None:
# Blinka doesn't have supervisor (see issue Adafruit_Blinka#711), so wait
# one second for USB to become ready
time.sleep(1.0)
elif timeout is None:
# default behavior: wait indefinitely for USB to become ready
while not supervisor.runtime.usb_connected:
time.sleep(1.0)
else:
# wait up to timeout seconds for USB to become ready
for _ in range(timeout):
if supervisor.runtime.usb_connected:
return device
# Wait for USB to be connected only if this is a usb_hid.Device.
if Device and isinstance(device, Device):
if supervisor is None:
# Blinka doesn't have supervisor (see issue Adafruit_Blinka#711), so wait
# one second for USB to become ready
time.sleep(1.0)
raise OSError("Failed to initialize HID device. Is USB connected?")
elif timeout is None:
# default behavior: wait indefinitely for USB to become ready
while not supervisor.runtime.usb_connected:
time.sleep(1.0)
else:
# wait up to timeout seconds for USB to become ready
for _ in range(timeout):
if supervisor.runtime.usb_connected:
return device
time.sleep(1.0)
raise OSError("Failed to initialize HID device. Is USB connected?")

return device

0 comments on commit 426f3b8

Please sign in to comment.