labnode-async 1.0.0__tar.gz → 1.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/pylint.yml +1 -1
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/tests.yml +1 -1
- {labnode_async-1.0.0 → labnode_async-1.2.0}/PKG-INFO +17 -13
- {labnode_async-1.0.0 → labnode_async-1.2.0}/README.md +10 -4
- {labnode_async-1.0.0 → labnode_async-1.2.0}/examples/pid.py +4 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/_version.py +3 -3
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/connection.py +80 -58
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/device_factory.py +11 -6
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/ip_connection.py +8 -8
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/labnode.py +27 -1
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/pid_controller.py +16 -1
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/serial_connection.py +2 -4
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async.egg-info/PKG-INFO +17 -13
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async.egg-info/requires.txt +1 -4
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async.egg-info/scm_version.json +2 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/pyproject.toml +6 -8
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/fake_labnode.py +18 -3
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_closing_the_transport.py +22 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_connecting.py +2 -3
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_connection.py +2 -4
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_context_manager.py +1 -3
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_device_factory.py +13 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_invalid_replies.py +0 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_ip_connection.py +55 -15
- labnode_async-1.2.0/tests/test_lost_connection.py +149 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_oversized_packet.py +0 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_pid_controller.py +2 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_pid_invalid_format.py +0 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_request_data.py +0 -2
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_request_ids.py +2 -3
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/test_serial_connection.py +2 -4
- labnode_async-1.0.0/tests/test_lost_connection.py +0 -69
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/dependabot.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/code-coverage-comment.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/code-coverage.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/documentation.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/pre-commit.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/publish-pypi.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/publish-test-pypi.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/workflows/zizmor.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.github/zizmor.yml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.gitignore +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/.pre-commit-config.yaml +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/LICENSE +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/doc/Makefile +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/doc/source/conf.py +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/doc/source/examples.rst +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/doc/source/index.rst +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/doc/source/modules.rst +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/doc/source/readme.rst +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/examples/simple.py +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/__init__.py +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/devices.py +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/errors.py +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async/py.typed +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async.egg-info/SOURCES.txt +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async.egg-info/dependency_links.txt +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async.egg-info/scm_file_list.json +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/labnode_async.egg-info/top_level.txt +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/requirements-workflows.txt +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/setup.cfg +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/setup.py +0 -0
- {labnode_async-1.0.0 → labnode_async-1.2.0}/tests/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: labnode-async
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.2.0
|
|
4
4
|
Summary: Python3 AsyncIO Labnode driver
|
|
5
5
|
Author-email: Patrick Baus <patrick.baus@physik.tu-darmstadt.de>
|
|
6
6
|
License: GNU General Public License v3 (GPLv3)
|
|
@@ -10,11 +10,10 @@ Project-URL: Download, https://github.com/PatrickBaus/labnode_async/releases
|
|
|
10
10
|
Project-URL: Documentation, https://patrickbaus.github.io/labnode_async/
|
|
11
11
|
Keywords: IoT,PID,PID controller,API
|
|
12
12
|
Classifier: Programming Language :: Python :: 3
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.
|
|
14
|
-
Classifier: Programming Language :: Python :: 3.
|
|
15
|
-
Classifier: Programming Language :: Python :: 3.
|
|
16
|
-
Classifier: Programming Language :: Python :: 3.
|
|
17
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
17
|
Classifier: Development Status :: 5 - Production/Stable
|
|
19
18
|
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
20
19
|
Classifier: Operating System :: OS Independent
|
|
@@ -24,13 +23,12 @@ Classifier: Natural Language :: English
|
|
|
24
23
|
Classifier: Topic :: Home Automation
|
|
25
24
|
Classifier: Topic :: Scientific/Engineering
|
|
26
25
|
Classifier: Typing :: Typed
|
|
27
|
-
Requires-Python: >=3.
|
|
26
|
+
Requires-Python: >=3.12
|
|
28
27
|
Description-Content-Type: text/markdown
|
|
29
28
|
License-File: LICENSE
|
|
30
|
-
Requires-Dist: typing-extensions; python_version < "3.11"
|
|
31
29
|
Requires-Dist: cbor2>=5.6.2
|
|
32
30
|
Requires-Dist: cobs
|
|
33
|
-
Requires-Dist: pyserial-asyncio
|
|
31
|
+
Requires-Dist: pyserial-asyncio-fast>=0.16
|
|
34
32
|
Provides-Extra: test
|
|
35
33
|
Requires-Dist: pytest; extra == "test"
|
|
36
34
|
Requires-Dist: pytest-cov; extra == "test"
|
|
@@ -85,14 +83,20 @@ also handle cleanup. By the way: Context managers are great!
|
|
|
85
83
|
|
|
86
84
|
Connect to the remote endpoint, and it will automatically enumerate the Labnode and create the correct device.
|
|
87
85
|
```python
|
|
88
|
-
from labnode_async import IPConnection
|
|
86
|
+
from labnode_async import IPConnection, PidController
|
|
89
87
|
|
|
90
88
|
# Create a device and start coding
|
|
91
|
-
async with IPConnection("192.
|
|
92
|
-
#
|
|
93
|
-
|
|
89
|
+
async with IPConnection("192.168.0.2") as device:
|
|
90
|
+
# The device class matches the id reported by the Labnode. Check it to use its specific functions.
|
|
91
|
+
if isinstance(device, PidController):
|
|
92
|
+
# Add your code here
|
|
93
|
+
...
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
+
Every device class names its type: `device_identifier()` returns the `DeviceIdentifier` reported by the Labnode, e.g.
|
|
97
|
+
`DeviceIdentifier.PID`, and `device_name()` a human-readable name, e.g. `"PID Controller"`. Both are class methods, so
|
|
98
|
+
they can be called on the class as well as on a device.
|
|
99
|
+
|
|
96
100
|
See [examples/](/examples/) for more working examples.
|
|
97
101
|
|
|
98
102
|
## Versioning
|
|
@@ -31,14 +31,20 @@ also handle cleanup. By the way: Context managers are great!
|
|
|
31
31
|
|
|
32
32
|
Connect to the remote endpoint, and it will automatically enumerate the Labnode and create the correct device.
|
|
33
33
|
```python
|
|
34
|
-
from labnode_async import IPConnection
|
|
34
|
+
from labnode_async import IPConnection, PidController
|
|
35
35
|
|
|
36
36
|
# Create a device and start coding
|
|
37
|
-
async with IPConnection("192.
|
|
38
|
-
#
|
|
39
|
-
|
|
37
|
+
async with IPConnection("192.168.0.2") as device:
|
|
38
|
+
# The device class matches the id reported by the Labnode. Check it to use its specific functions.
|
|
39
|
+
if isinstance(device, PidController):
|
|
40
|
+
# Add your code here
|
|
41
|
+
...
|
|
40
42
|
```
|
|
41
43
|
|
|
44
|
+
Every device class names its type: `device_identifier()` returns the `DeviceIdentifier` reported by the Labnode, e.g.
|
|
45
|
+
`DeviceIdentifier.PID`, and `device_name()` a human-readable name, e.g. `"PID Controller"`. Both are class methods, so
|
|
46
|
+
they can be called on the class as well as on a device.
|
|
47
|
+
|
|
42
48
|
See [examples/](/examples/) for more working examples.
|
|
43
49
|
|
|
44
50
|
## Versioning
|
|
@@ -39,8 +39,10 @@ async def main():
|
|
|
39
39
|
try:
|
|
40
40
|
connection = IPConnection(hostname="localhost", port=4223)
|
|
41
41
|
# connection = SerialConnection(url="/dev/ttyACM0") # Alternative serial connection
|
|
42
|
-
device: PidController
|
|
43
42
|
async with connection as device:
|
|
43
|
+
# The connection creates the device class, that matches the id reported by the Labnode
|
|
44
|
+
if not isinstance(device, PidController):
|
|
45
|
+
raise TypeError(f"Expected a PID controller, but found {device}.")
|
|
44
46
|
# Test setters
|
|
45
47
|
# await device.set_serial(1)
|
|
46
48
|
# await device.set_uuid(uuid.uuid4()) # Generate and set a random UUID
|
|
@@ -76,7 +78,7 @@ async def main():
|
|
|
76
78
|
# await device.set_secondary_config(1)
|
|
77
79
|
|
|
78
80
|
# Test getters
|
|
79
|
-
print(f"Device Type: {device.device_identifier.name}")
|
|
81
|
+
print(f"Device Type: {device.device_name()} ({device.device_identifier().name})")
|
|
80
82
|
print(f"Controller API version: {'.'.join(map(str, device.api_version))}")
|
|
81
83
|
print(f"Controller hardware version: {'.'.join(map(str, await device.get_hardware_version()))}")
|
|
82
84
|
print(f"Controller software version: {'.'.join(map(str, await device.get_software_version()))}")
|
|
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
|
|
|
18
18
|
commit_id: str | None
|
|
19
19
|
__commit_id__: str | None
|
|
20
20
|
|
|
21
|
-
__version__ = version = '1.
|
|
22
|
-
__version_tuple__ = version_tuple = (1,
|
|
21
|
+
__version__ = version = '1.2.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (1, 2, 0)
|
|
23
23
|
|
|
24
|
-
__commit_id__ = commit_id = '
|
|
24
|
+
__commit_id__ = commit_id = 'g39d32f6e4'
|
|
@@ -18,14 +18,13 @@
|
|
|
18
18
|
# ##### END GPL LICENSE BLOCK #####
|
|
19
19
|
"""All basic classes for connection can be found here"""
|
|
20
20
|
|
|
21
|
-
from __future__ import annotations
|
|
22
|
-
|
|
23
21
|
import asyncio
|
|
24
22
|
import errno
|
|
25
23
|
import logging
|
|
26
24
|
from asyncio import StreamReader, StreamWriter
|
|
25
|
+
from collections.abc import AsyncIterator
|
|
27
26
|
from types import TracebackType
|
|
28
|
-
from typing import Any,
|
|
27
|
+
from typing import Any, cast
|
|
29
28
|
|
|
30
29
|
import cbor2 as cbor
|
|
31
30
|
|
|
@@ -74,7 +73,8 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
74
73
|
timeout: float
|
|
75
74
|
the timeout in seconds used when making queries or connection attempts
|
|
76
75
|
"""
|
|
77
|
-
|
|
76
|
+
# The task, that runs the main loop and owns the task group of the probe
|
|
77
|
+
self.__main_task: asyncio.Task | None = None
|
|
78
78
|
self.__last_received = 0.0 # The time of the event loop, when the last packet was received
|
|
79
79
|
self.__reader: asyncio.StreamReader | None = None
|
|
80
80
|
self.__writer: asyncio.StreamWriter | None = None
|
|
@@ -114,7 +114,7 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
114
114
|
raise
|
|
115
115
|
|
|
116
116
|
async def __aexit__(
|
|
117
|
-
self, exc_type:
|
|
117
|
+
self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
|
|
118
118
|
) -> None:
|
|
119
119
|
await self.disconnect()
|
|
120
120
|
|
|
@@ -194,7 +194,9 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
194
194
|
"""
|
|
195
195
|
raise NotImplementedError
|
|
196
196
|
|
|
197
|
-
async def _connect(
|
|
197
|
+
async def _connect(
|
|
198
|
+
self, reader: StreamReader, writer: StreamWriter, probe: tuple[float, float] | None = None
|
|
199
|
+
) -> None:
|
|
198
200
|
"""
|
|
199
201
|
Starts the data producer tasks when given the StreamReader/Writer.
|
|
200
202
|
|
|
@@ -204,43 +206,67 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
204
206
|
The reader interface of the connection
|
|
205
207
|
writer: StreamWriter
|
|
206
208
|
The writer interface of the connection
|
|
209
|
+
probe: tuple of float, optional
|
|
210
|
+
If given, probe the Labnode, if it was idle for `probe[0]` seconds. This is the fallback for operating
|
|
211
|
+
systems, that do not support TCP keepalive with custom timings or TCP_USER_TIMEOUT. If the probe is not
|
|
212
|
+
answered within `probe[1]` seconds, the Labnode is gone and the connection is closed, as if the remote
|
|
213
|
+
endpoint had closed it. The Labnode is idle, if nothing was received, so this also detects a Labnode, that
|
|
214
|
+
vanished while a request was waiting for its answer.
|
|
207
215
|
"""
|
|
208
216
|
self.__reader, self.__writer = reader, writer
|
|
209
217
|
|
|
210
218
|
self.__last_received = asyncio.get_running_loop().time()
|
|
211
|
-
|
|
219
|
+
main_task = asyncio.create_task(self.__run(probe), name=f"{self} main loop")
|
|
220
|
+
self.__main_task = main_task
|
|
221
|
+
# Do not keep the task of a connection, that was closed by the remote endpoint
|
|
222
|
+
main_task.add_done_callback(self.__forget_main_task)
|
|
212
223
|
|
|
213
|
-
def
|
|
214
|
-
task
|
|
215
|
-
|
|
216
|
-
# Do not keep the tasks of connections, that were closed by the remote endpoint
|
|
217
|
-
task.add_done_callback(self.__running_tasks.discard)
|
|
224
|
+
def __forget_main_task(self, task: asyncio.Task) -> None:
|
|
225
|
+
if self.__main_task is task: # It is not the task of a new connection
|
|
226
|
+
self.__main_task = None
|
|
218
227
|
|
|
219
|
-
async def
|
|
228
|
+
async def __run(self, probe: tuple[float, float] | None) -> None:
|
|
220
229
|
"""
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
if self.__running_tasks:
|
|
226
|
-
await asyncio.wait(self.__running_tasks)
|
|
227
|
-
|
|
228
|
-
def _start_probe(self, idle: float, timeout: float) -> None:
|
|
229
|
-
"""
|
|
230
|
-
Probe the Labnode, if it was idle for `idle` seconds. This is the fallback for operating systems, that do not
|
|
231
|
-
support TCP keepalive with custom timings or TCP_USER_TIMEOUT. If the probe is not answered within `timeout`
|
|
232
|
-
seconds, the Labnode is gone and the connection is closed, as if the remote endpoint had closed it. The
|
|
233
|
-
Labnode is idle, if nothing was received, so this also detects a Labnode, that vanished while a request was
|
|
234
|
-
waiting for its answer.
|
|
230
|
+
The main task of the connection. It runs the main loop and owns the task group, that runs the probe. The main
|
|
231
|
+
loop ends, if the remote endpoint closes the connection, or if the probe finds the Labnode gone, then the probe
|
|
232
|
+
is cancelled. Both are cancelled, if this task is cancelled by disconnect(). If either fails, the task group
|
|
233
|
+
cancels the other one. In all cases, the connection is closed, once both are done.
|
|
235
234
|
|
|
236
235
|
Parameters
|
|
237
236
|
----------
|
|
238
|
-
|
|
239
|
-
The time
|
|
240
|
-
timeout: float
|
|
241
|
-
The time in seconds, after which an unanswered probe closes the connection
|
|
237
|
+
probe: tuple of float or None
|
|
238
|
+
The idle time and the timeout of the probe, if the Labnode is probed. See _connect().
|
|
242
239
|
"""
|
|
243
|
-
|
|
240
|
+
try:
|
|
241
|
+
async with asyncio.TaskGroup() as task_group:
|
|
242
|
+
probe_task = None
|
|
243
|
+
if probe is not None:
|
|
244
|
+
probe_task = task_group.create_task(self.__probe_loop(*probe), name=f"{self} probe")
|
|
245
|
+
try:
|
|
246
|
+
await self.__main_loop()
|
|
247
|
+
finally:
|
|
248
|
+
if probe_task is not None:
|
|
249
|
+
probe_task.cancel() # The probe is useless, once the connection is gone
|
|
250
|
+
except* Exception: # pylint: disable=broad-exception-caught # Nobody else would see the error
|
|
251
|
+
self.__logger.exception("Unexpected error in the connection to '%s'. Closing it.", self.endpoint)
|
|
252
|
+
finally:
|
|
253
|
+
try:
|
|
254
|
+
await self.__close_transport()
|
|
255
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
256
|
+
if cast(asyncio.Task, asyncio.current_task()).cancelling():
|
|
257
|
+
raise # disconnect() is waiting for the result and raises the error
|
|
258
|
+
# The connection was lost and nobody waits for the result
|
|
259
|
+
self.__logger.exception("Error while closing the connection to '%s'.", self.endpoint)
|
|
260
|
+
|
|
261
|
+
async def _wait_for_teardown(self) -> None:
|
|
262
|
+
"""
|
|
263
|
+
Wait until a connection, that is being closed, is gone. A connection, that was lost, is no longer connected, but
|
|
264
|
+
its main task is still closing the transport. A new connection must not be established before that is done,
|
|
265
|
+
because the main task would close the new connection instead.
|
|
266
|
+
"""
|
|
267
|
+
main_task = self.__main_task
|
|
268
|
+
if main_task is not None:
|
|
269
|
+
await asyncio.wait([main_task])
|
|
244
270
|
|
|
245
271
|
async def __probe_loop(self, idle: float, timeout: float) -> None:
|
|
246
272
|
loop = asyncio.get_running_loop()
|
|
@@ -253,7 +279,7 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
253
279
|
try:
|
|
254
280
|
# A harmless query. A single request suffices, because TCP retransmits it, if it is lost.
|
|
255
281
|
await self.__send_request({FunctionID.GET_API_VERSION: None}, True, timeout)
|
|
256
|
-
except
|
|
282
|
+
except TimeoutError:
|
|
257
283
|
self.__logger.error(
|
|
258
284
|
"The Labnode at '%s' did not answer the probe. Closing the connection.", self.endpoint
|
|
259
285
|
)
|
|
@@ -307,8 +333,9 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
307
333
|
# The future will be resolved by the main_loop() and __process_packet()
|
|
308
334
|
self.__pending_requests[request_id] = asyncio.Future()
|
|
309
335
|
try:
|
|
310
|
-
#
|
|
311
|
-
|
|
336
|
+
# A timeout of None waits until the request is done
|
|
337
|
+
async with asyncio.timeout(timeout):
|
|
338
|
+
response = await self.__pending_requests[request_id]
|
|
312
339
|
finally:
|
|
313
340
|
# Cleanup. Note: The request_id, might not be in the dict anymore, because
|
|
314
341
|
# if the remote endpoint shuts down the connection, __close_transport() is called,
|
|
@@ -397,18 +424,12 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
397
424
|
|
|
398
425
|
async def __main_loop(self) -> None:
|
|
399
426
|
"""
|
|
400
|
-
This loops reads data from the connection and forwards it to the waiters (Futures).
|
|
427
|
+
This loops reads data from the connection and forwards it to the waiters (Futures). It ends, when the remote
|
|
428
|
+
endpoint closes the connection.
|
|
401
429
|
"""
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
await self.__process_packet(packet)
|
|
406
|
-
finally:
|
|
407
|
-
# Stop the probe, if there is one
|
|
408
|
-
for task in self.__running_tasks:
|
|
409
|
-
if task is not asyncio.current_task():
|
|
410
|
-
task.cancel()
|
|
411
|
-
await self.__close_transport()
|
|
430
|
+
async for packet in self.__read_packets():
|
|
431
|
+
# Read packets from the socket and process them.
|
|
432
|
+
await self.__process_packet(packet)
|
|
412
433
|
|
|
413
434
|
async def disconnect(self) -> None:
|
|
414
435
|
"""
|
|
@@ -418,26 +439,27 @@ class Connection: # pylint: disable=too-many-instance-attributes
|
|
|
418
439
|
# The connection might have been lost and is still being closed
|
|
419
440
|
await self._wait_for_teardown()
|
|
420
441
|
return
|
|
421
|
-
# Cancel the main task,
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
442
|
+
# Cancel the main task. Its task group cancels the probe, then it shuts down the transport via
|
|
443
|
+
# __close_transport().
|
|
444
|
+
main_task = self.__main_task
|
|
445
|
+
assert main_task is not None # The main task is started, when the connection is established
|
|
446
|
+
main_task.cancel()
|
|
425
447
|
try:
|
|
426
|
-
#
|
|
427
|
-
|
|
448
|
+
# gather() returns the error, instead of raising it, so the transport is closed below in any case. If this
|
|
449
|
+
# coroutine is cancelled, it still waits until the main task is done.
|
|
450
|
+
result = (await asyncio.gather(main_task, return_exceptions=True))[0]
|
|
428
451
|
finally:
|
|
429
452
|
if self.__writer is not None:
|
|
430
|
-
# The main
|
|
453
|
+
# The main task was cancelled before it started, so it could not close the transport
|
|
431
454
|
await self.__close_transport()
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
raise result # The transport could not be closed
|
|
455
|
+
if isinstance(result, Exception):
|
|
456
|
+
raise result # The transport could not be closed
|
|
435
457
|
|
|
436
458
|
async def __close_transport(self) -> None:
|
|
437
459
|
# Flush data
|
|
438
460
|
try:
|
|
439
|
-
# This assertion is always true, because the function is only called by
|
|
440
|
-
# after self.__writer is assigned.
|
|
461
|
+
# This assertion is always true, because the function is only called by the main task, which is started
|
|
462
|
+
# after self.__writer is assigned, or by disconnect(), if the connection is up.
|
|
441
463
|
writer = self.__writer
|
|
442
464
|
assert writer is not None
|
|
443
465
|
try:
|
|
@@ -22,7 +22,7 @@ The device factory which allows creating instances of Labnodes from their device
|
|
|
22
22
|
|
|
23
23
|
from __future__ import annotations
|
|
24
24
|
|
|
25
|
-
from typing import TYPE_CHECKING, Any
|
|
25
|
+
from typing import TYPE_CHECKING, Any
|
|
26
26
|
|
|
27
27
|
from .devices import DeviceIdentifier
|
|
28
28
|
from .labnode import Labnode
|
|
@@ -39,19 +39,24 @@ class DeviceFactory:
|
|
|
39
39
|
"""
|
|
40
40
|
|
|
41
41
|
def __init__(self) -> None:
|
|
42
|
-
self.__available_devices: dict[DeviceIdentifier,
|
|
42
|
+
self.__available_devices: dict[DeviceIdentifier, type[Labnode]] = {}
|
|
43
43
|
|
|
44
|
-
def register(self, device:
|
|
44
|
+
def register[T: Labnode](self, device: type[T]) -> type[T]:
|
|
45
45
|
"""
|
|
46
46
|
Register a driver with the factory. Should only be called in this file.
|
|
47
47
|
|
|
48
48
|
Parameters
|
|
49
49
|
----------
|
|
50
|
-
device:
|
|
50
|
+
device: type[Labnode]
|
|
51
51
|
A Labnode device class to be registered with the factory.
|
|
52
|
+
|
|
53
|
+
Returns
|
|
54
|
+
-------
|
|
55
|
+
type[Labnode]
|
|
56
|
+
The device class, unchanged, so that it can be used as a class decorator.
|
|
52
57
|
"""
|
|
53
|
-
|
|
54
|
-
|
|
58
|
+
self.__available_devices[device.device_identifier()] = device
|
|
59
|
+
return device
|
|
55
60
|
|
|
56
61
|
def get(self, device_id: DeviceIdentifier, connection: Connection, *args: Any, **kwargs: Any) -> Labnode:
|
|
57
62
|
"""
|
|
@@ -18,12 +18,10 @@
|
|
|
18
18
|
# ##### END GPL LICENSE BLOCK #####
|
|
19
19
|
"""The ip connection module for all Labnodes"""
|
|
20
20
|
|
|
21
|
-
from __future__ import annotations
|
|
22
|
-
|
|
23
21
|
import asyncio
|
|
24
22
|
import logging
|
|
25
23
|
import socket
|
|
26
|
-
from typing import Any
|
|
24
|
+
from typing import Any
|
|
27
25
|
|
|
28
26
|
from .connection import Connection, NotConnectedError
|
|
29
27
|
from .devices import FunctionID
|
|
@@ -153,7 +151,7 @@ class IPConnection(Connection):
|
|
|
153
151
|
The number of unanswered probes, after which the Labnode is considered dead
|
|
154
152
|
"""
|
|
155
153
|
super().__init__(timeout)
|
|
156
|
-
self.__host:
|
|
154
|
+
self.__host: tuple[str, int] = hostname, port
|
|
157
155
|
self.__keepalive = keepalive_idle, keepalive_interval, keepalive_count
|
|
158
156
|
self.__logger = logging.getLogger(__name__)
|
|
159
157
|
self.__logger.setLevel(logging.ERROR) # Only log really important messages
|
|
@@ -196,16 +194,18 @@ class IPConnection(Connection):
|
|
|
196
194
|
return
|
|
197
195
|
await self._wait_for_teardown() # of a connection, that was lost
|
|
198
196
|
|
|
199
|
-
#
|
|
200
|
-
|
|
197
|
+
# A timeout of None waits until the connection is established
|
|
198
|
+
async with asyncio.timeout(self.timeout):
|
|
199
|
+
reader, writer = await asyncio.open_connection(*self.__host)
|
|
201
200
|
self.__logger.info("Labnode IP connection established to host '%s:%i'", *self.__host)
|
|
202
|
-
await super()._connect(reader, writer)
|
|
203
201
|
|
|
204
202
|
# Detect a Labnode, that vanished without closing the connection. Let the operating system do it, if it can.
|
|
203
|
+
probe = None
|
|
205
204
|
sock = writer.get_extra_info("socket")
|
|
206
205
|
if sock is None or not enable_tcp_keepalive(sock, *self.__keepalive):
|
|
207
206
|
self.__logger.info(
|
|
208
207
|
"TCP keepalive cannot be fully configured for host '%s:%i', probing the host instead.", *self.__host
|
|
209
208
|
)
|
|
210
209
|
idle, interval, count = self.__keepalive
|
|
211
|
-
|
|
210
|
+
probe = idle, interval * count
|
|
211
|
+
await super()._connect(reader, writer, probe)
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
from __future__ import annotations
|
|
22
22
|
|
|
23
23
|
from abc import ABC, abstractmethod
|
|
24
|
-
from typing import TYPE_CHECKING
|
|
24
|
+
from typing import TYPE_CHECKING, Any
|
|
25
25
|
from uuid import UUID
|
|
26
26
|
|
|
27
27
|
if TYPE_CHECKING:
|
|
@@ -44,6 +44,16 @@ class Labnode(ABC):
|
|
|
44
44
|
The device identifier version of the device
|
|
45
45
|
"""
|
|
46
46
|
|
|
47
|
+
@classmethod
|
|
48
|
+
@abstractmethod
|
|
49
|
+
def device_name(cls) -> str:
|
|
50
|
+
"""
|
|
51
|
+
Returns
|
|
52
|
+
-------
|
|
53
|
+
str
|
|
54
|
+
The human-readable name of the device type, e.g. "PID Controller"
|
|
55
|
+
"""
|
|
56
|
+
|
|
47
57
|
@property
|
|
48
58
|
def api_version(self) -> tuple[int, int, int]:
|
|
49
59
|
"""
|
|
@@ -107,6 +117,22 @@ class Labnode(ABC):
|
|
|
107
117
|
The universally unique identifier of the node
|
|
108
118
|
"""
|
|
109
119
|
|
|
120
|
+
@abstractmethod
|
|
121
|
+
async def get_by_function_id(self, function_id: int) -> Any:
|
|
122
|
+
"""
|
|
123
|
+
Query a value by function id, instead of calling the named function.
|
|
124
|
+
|
|
125
|
+
Parameters
|
|
126
|
+
----------
|
|
127
|
+
function_id: int
|
|
128
|
+
The function to query
|
|
129
|
+
|
|
130
|
+
Returns
|
|
131
|
+
-------
|
|
132
|
+
Any
|
|
133
|
+
The result of the query.
|
|
134
|
+
"""
|
|
135
|
+
|
|
110
136
|
async def set_uuid(self, uuid: UUID) -> None:
|
|
111
137
|
"""
|
|
112
138
|
Set the universally unique identifier of the node
|
|
@@ -22,9 +22,10 @@ from __future__ import annotations
|
|
|
22
22
|
|
|
23
23
|
import logging
|
|
24
24
|
import warnings
|
|
25
|
+
from collections.abc import Callable
|
|
25
26
|
from decimal import Decimal
|
|
26
27
|
from enum import Enum, unique
|
|
27
|
-
from typing import TYPE_CHECKING, Any,
|
|
28
|
+
from typing import TYPE_CHECKING, Any, override
|
|
28
29
|
from uuid import UUID
|
|
29
30
|
|
|
30
31
|
from .devices import DeviceIdentifier, ErrorCode, PidFunctionID
|
|
@@ -60,12 +61,20 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
|
|
|
60
61
|
"""
|
|
61
62
|
|
|
62
63
|
__DEVICE_IDENTIFIER = DeviceIdentifier.PID
|
|
64
|
+
__DEVICE_NAME = "PID Controller"
|
|
63
65
|
|
|
64
66
|
@classmethod
|
|
67
|
+
@override
|
|
65
68
|
def device_identifier(cls) -> DeviceIdentifier:
|
|
66
69
|
"""The device identifier used to identify the device type"""
|
|
67
70
|
return cls.__DEVICE_IDENTIFIER
|
|
68
71
|
|
|
72
|
+
@classmethod
|
|
73
|
+
@override
|
|
74
|
+
def device_name(cls) -> str:
|
|
75
|
+
"""The human-readable name of the device type"""
|
|
76
|
+
return cls.__DEVICE_NAME
|
|
77
|
+
|
|
69
78
|
_RAW_TO_UNIT: dict[PidFunctionID, Callable] = {
|
|
70
79
|
# We need to truncate to 100 %rH according to the datasheet.
|
|
71
80
|
# The datasheet is *wrong* about the conversion formula. Slightly wrong, but wrong nonetheless.
|
|
@@ -218,6 +227,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
|
|
|
218
227
|
return result
|
|
219
228
|
return result
|
|
220
229
|
|
|
230
|
+
@override
|
|
221
231
|
async def get_software_version(self) -> tuple[int, int, int]:
|
|
222
232
|
"""
|
|
223
233
|
Get the firmware version running on the device. The response is a tuple of ints, that represents the version
|
|
@@ -230,6 +240,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
|
|
|
230
240
|
"""
|
|
231
241
|
return await self.get_by_function_id(PidFunctionID.GET_SOFTWARE_VERSION)
|
|
232
242
|
|
|
243
|
+
@override
|
|
233
244
|
async def get_hardware_version(self) -> tuple[int, int, int]:
|
|
234
245
|
"""
|
|
235
246
|
Get the hardware revision of the device. The response is a tuple of ints, that represents the version number.
|
|
@@ -241,6 +252,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
|
|
|
241
252
|
"""
|
|
242
253
|
return await self.get_by_function_id(PidFunctionID.GET_HARDWARE_VERSION)
|
|
243
254
|
|
|
255
|
+
@override
|
|
244
256
|
async def get_serial(self) -> int:
|
|
245
257
|
"""
|
|
246
258
|
Get the serial number of the device.
|
|
@@ -298,6 +310,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
|
|
|
298
310
|
mac = bytearray(mac) # convert to bytearray, this also makes sure, that all values are in range(0, 256)
|
|
299
311
|
await self.__send_single_request(PidFunctionID.SET_MAC_ADDRESS, mac)
|
|
300
312
|
|
|
313
|
+
@override
|
|
301
314
|
async def get_uuid(self) -> UUID:
|
|
302
315
|
"""
|
|
303
316
|
Get the universally unique identifier of the node.
|
|
@@ -319,6 +332,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
|
|
|
319
332
|
result = await self.get_by_function_id(PidFunctionID.GET_UUID)
|
|
320
333
|
return UUID(bytes=bytes(result))
|
|
321
334
|
|
|
335
|
+
@override
|
|
322
336
|
async def set_uuid(self, uuid: UUID) -> None:
|
|
323
337
|
"""
|
|
324
338
|
Set the universally unique identifier of the node.
|
|
@@ -901,6 +915,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
|
|
|
901
915
|
)
|
|
902
916
|
return await self.get_by_function_id(PidFunctionID.GET_ACTIVE_CONNECTION_COUNT)
|
|
903
917
|
|
|
918
|
+
@override
|
|
904
919
|
async def get_by_function_id(self, function_id: PidFunctionID | int) -> Any:
|
|
905
920
|
"""
|
|
906
921
|
Query a value by function id, instead of calling the named function.
|
|
@@ -18,12 +18,10 @@
|
|
|
18
18
|
# ##### END GPL LICENSE BLOCK #####
|
|
19
19
|
"""The serial connection module for all Labnodes"""
|
|
20
20
|
|
|
21
|
-
from __future__ import annotations
|
|
22
|
-
|
|
23
21
|
import logging
|
|
24
22
|
from typing import Any
|
|
25
23
|
|
|
26
|
-
import
|
|
24
|
+
import serial_asyncio_fast
|
|
27
25
|
|
|
28
26
|
from .connection import Connection, NotConnectedError
|
|
29
27
|
from .devices import FunctionID
|
|
@@ -115,6 +113,6 @@ class SerialConnection(Connection):
|
|
|
115
113
|
return
|
|
116
114
|
await self._wait_for_teardown() # of a connection, that was lost
|
|
117
115
|
|
|
118
|
-
reader, writer = await
|
|
116
|
+
reader, writer = await serial_asyncio_fast.open_serial_connection(**self.__tty_kwargs)
|
|
119
117
|
self.__logger.info("Labnode serial connection established to port '%s'", self.tty)
|
|
120
118
|
await super()._connect(reader, writer)
|