Skip to content

Commit

Permalink
Merge pull request #122 from dhalbert/ble-device-no-wait
Browse files Browse the repository at this point in the history
Do not wait for USB for non-USB HID devices
  • Loading branch information
dhalbert authored Nov 29, 2023
2 parents 30b7cda + 426f3b8 commit bfb75a1
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 bfb75a1

Please sign in to comment.