Skip to content

Do not wait for USB for non-USB HID devices #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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