Skip to content

Commit bfb75a1

Browse files
authored
Merge pull request #122 from dhalbert/ble-device-no-wait
Do not wait for USB for non-USB HID devices
2 parents 30b7cda + 426f3b8 commit bfb75a1

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

adafruit_hid/__init__.py

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,26 +28,32 @@
2828

2929
try:
3030
from typing import Sequence
31-
import usb_hid
3231
except ImportError:
3332
pass
3433

34+
# usb_hid may not exist on some boards that still provide BLE or other HID devices.
35+
try:
36+
from usb_hid import Device
37+
except ImportError:
38+
Device = None
39+
3540
__version__ = "0.0.0+auto.0"
3641
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_HID.git"
3742

3843

3944
def find_device(
40-
devices: Sequence[usb_hid.Device],
45+
devices: Sequence[object],
4146
*,
4247
usage_page: int,
4348
usage: int,
4449
timeout: int = None,
45-
) -> usb_hid.Device:
50+
) -> object:
4651
"""Search through the provided sequence of devices to find the one with the matching
4752
usage_page and usage.
4853
4954
:param timeout: Time in seconds to wait for USB to become ready before timing out.
50-
Defaults to None to wait indefinitely."""
55+
Defaults to None to wait indefinitely.
56+
Ignored if device is not a `usb_hid.Device`; it might be BLE, for instance."""
5157

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

66-
if supervisor is None:
67-
# Blinka doesn't have supervisor (see issue Adafruit_Blinka#711), so wait
68-
# one second for USB to become ready
69-
time.sleep(1.0)
70-
elif timeout is None:
71-
# default behavior: wait indefinitely for USB to become ready
72-
while not supervisor.runtime.usb_connected:
73-
time.sleep(1.0)
74-
else:
75-
# wait up to timeout seconds for USB to become ready
76-
for _ in range(timeout):
77-
if supervisor.runtime.usb_connected:
78-
return device
72+
# Wait for USB to be connected only if this is a usb_hid.Device.
73+
if Device and isinstance(device, Device):
74+
if supervisor is None:
75+
# Blinka doesn't have supervisor (see issue Adafruit_Blinka#711), so wait
76+
# one second for USB to become ready
7977
time.sleep(1.0)
80-
raise OSError("Failed to initialize HID device. Is USB connected?")
78+
elif timeout is None:
79+
# default behavior: wait indefinitely for USB to become ready
80+
while not supervisor.runtime.usb_connected:
81+
time.sleep(1.0)
82+
else:
83+
# wait up to timeout seconds for USB to become ready
84+
for _ in range(timeout):
85+
if supervisor.runtime.usb_connected:
86+
return device
87+
time.sleep(1.0)
88+
raise OSError("Failed to initialize HID device. Is USB connected?")
8189

8290
return device

0 commit comments

Comments
 (0)