-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy path__init__.py
More file actions
83 lines (65 loc) · 1.98 KB
/
__init__.py
File metadata and controls
83 lines (65 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""Interfaces for communicating with PSLab devices."""
from serial.tools import list_ports
from .connection import ConnectionHandler
from ._serial import SerialHandler
from .wlan import WLANHandler
from .mock import MockHandler
__all__ = [
"ConnectionHandler",
"SerialHandler",
"WLANHandler",
"autoconnect",
"MockHandler",
]
def detect() -> list[ConnectionHandler]:
"""Detect PSLab devices.
Returns
-------
devices : list[ConnectionHandler]
Handlers for all detected PSLabs. The returned handlers are disconnected; call
.connect() before use.
"""
regex = []
for vid, pid in zip(SerialHandler._USB_VID, SerialHandler._USB_PID):
regex.append(f"{vid:04x}:{pid:04x}")
regex = "(" + "|".join(regex) + ")"
port_info_generator = list_ports.grep(regex)
pslab_devices = []
for port_info in port_info_generator:
device = SerialHandler(port=port_info.device, baudrate=1000000, timeout=1)
try:
device.connect()
except Exception:
pass # nosec
else:
pslab_devices.append(device)
finally:
device.disconnect()
try:
device = WLANHandler()
device.connect()
except Exception:
pass # nosec
else:
pslab_devices.append(device)
finally:
device.disconnect()
return pslab_devices
def autoconnect() -> ConnectionHandler:
"""Automatically connect when exactly one device is present.
Returns
-------
device : ConnectionHandler
A handler connected to the detected PSLab device. The handler is connected; it
is not necessary to call .connect before use().
"""
devices = detect()
if not devices:
msg = "device not found"
raise ConnectionError(msg)
if len(devices) > 1:
msg = f"autoconnect failed, multiple devices detected: {devices}"
raise ConnectionError(msg)
device = devices[0]
device.connect()
return device