labnode-async 1.0.0__tar.gz → 1.1.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.
Files changed (63) hide show
  1. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/pylint.yml +1 -1
  2. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/tests.yml +1 -1
  3. {labnode_async-1.0.0 → labnode_async-1.1.0}/PKG-INFO +13 -13
  4. {labnode_async-1.0.0 → labnode_async-1.1.0}/README.md +6 -4
  5. {labnode_async-1.0.0 → labnode_async-1.1.0}/examples/pid.py +3 -1
  6. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/_version.py +3 -3
  7. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/connection.py +80 -58
  8. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/device_factory.py +11 -6
  9. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/ip_connection.py +8 -8
  10. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/labnode.py +17 -1
  11. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/pid_controller.py +9 -1
  12. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/serial_connection.py +2 -4
  13. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async.egg-info/PKG-INFO +13 -13
  14. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async.egg-info/requires.txt +1 -4
  15. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async.egg-info/scm_version.json +2 -2
  16. {labnode_async-1.0.0 → labnode_async-1.1.0}/pyproject.toml +6 -8
  17. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/fake_labnode.py +18 -3
  18. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_closing_the_transport.py +22 -2
  19. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_connecting.py +2 -3
  20. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_connection.py +2 -4
  21. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_context_manager.py +1 -3
  22. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_device_factory.py +13 -2
  23. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_invalid_replies.py +0 -2
  24. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_ip_connection.py +55 -15
  25. labnode_async-1.1.0/tests/test_lost_connection.py +149 -0
  26. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_oversized_packet.py +0 -2
  27. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_pid_controller.py +0 -2
  28. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_pid_invalid_format.py +0 -2
  29. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_request_data.py +0 -2
  30. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_request_ids.py +2 -3
  31. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/test_serial_connection.py +2 -4
  32. labnode_async-1.0.0/tests/test_lost_connection.py +0 -69
  33. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/dependabot.yml +0 -0
  34. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/code-coverage-comment.yml +0 -0
  35. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/code-coverage.yml +0 -0
  36. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/documentation.yml +0 -0
  37. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/pre-commit.yml +0 -0
  38. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/publish-pypi.yml +0 -0
  39. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/publish-test-pypi.yml +0 -0
  40. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/workflows/zizmor.yml +0 -0
  41. {labnode_async-1.0.0 → labnode_async-1.1.0}/.github/zizmor.yml +0 -0
  42. {labnode_async-1.0.0 → labnode_async-1.1.0}/.gitignore +0 -0
  43. {labnode_async-1.0.0 → labnode_async-1.1.0}/.pre-commit-config.yaml +0 -0
  44. {labnode_async-1.0.0 → labnode_async-1.1.0}/LICENSE +0 -0
  45. {labnode_async-1.0.0 → labnode_async-1.1.0}/doc/Makefile +0 -0
  46. {labnode_async-1.0.0 → labnode_async-1.1.0}/doc/source/conf.py +0 -0
  47. {labnode_async-1.0.0 → labnode_async-1.1.0}/doc/source/examples.rst +0 -0
  48. {labnode_async-1.0.0 → labnode_async-1.1.0}/doc/source/index.rst +0 -0
  49. {labnode_async-1.0.0 → labnode_async-1.1.0}/doc/source/modules.rst +0 -0
  50. {labnode_async-1.0.0 → labnode_async-1.1.0}/doc/source/readme.rst +0 -0
  51. {labnode_async-1.0.0 → labnode_async-1.1.0}/examples/simple.py +0 -0
  52. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/__init__.py +0 -0
  53. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/devices.py +0 -0
  54. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/errors.py +0 -0
  55. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async/py.typed +0 -0
  56. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async.egg-info/SOURCES.txt +0 -0
  57. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async.egg-info/dependency_links.txt +0 -0
  58. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async.egg-info/scm_file_list.json +0 -0
  59. {labnode_async-1.0.0 → labnode_async-1.1.0}/labnode_async.egg-info/top_level.txt +0 -0
  60. {labnode_async-1.0.0 → labnode_async-1.1.0}/requirements-workflows.txt +0 -0
  61. {labnode_async-1.0.0 → labnode_async-1.1.0}/setup.cfg +0 -0
  62. {labnode_async-1.0.0 → labnode_async-1.1.0}/setup.py +0 -0
  63. {labnode_async-1.0.0 → labnode_async-1.1.0}/tests/__init__.py +0 -0
@@ -21,7 +21,7 @@ jobs:
21
21
  strategy:
22
22
  fail-fast: false
23
23
  matrix:
24
- python-version: [ "3.10", "3.11", "3.12", "3.13", "3.14", "3.15" ]
24
+ python-version: [ "3.12", "3.13", "3.14", "3.15" ]
25
25
 
26
26
  steps:
27
27
  - name: Checkout source repository
@@ -23,7 +23,7 @@ jobs:
23
23
  strategy:
24
24
  fail-fast: false
25
25
  matrix:
26
- python-version: [ "3.10", "3.11", "3.12", "3.13", "3.14", "3.15" ]
26
+ python-version: [ "3.12", "3.13", "3.14", "3.15" ]
27
27
 
28
28
  steps:
29
29
  - name: Checkout source repository
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: labnode-async
3
- Version: 1.0.0
3
+ Version: 1.1.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.7
14
- Classifier: Programming Language :: Python :: 3.8
15
- Classifier: Programming Language :: Python :: 3.9
16
- Classifier: Programming Language :: Python :: 3.10
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.7
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,12 +83,14 @@ 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.1680.0.2") as device:
92
- # Add your code here
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
96
  See [examples/](/examples/) for more working examples.
@@ -31,12 +31,14 @@ 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.1680.0.2") as device:
38
- # Add your code here
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
 
42
44
  See [examples/](/examples/) for more working examples.
@@ -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
@@ -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.0.0'
22
- __version_tuple__ = version_tuple = (1, 0, 0)
21
+ __version__ = version = '1.1.0'
22
+ __version_tuple__ = version_tuple = (1, 1, 0)
23
23
 
24
- __commit_id__ = commit_id = 'g652397f07'
24
+ __commit_id__ = commit_id = 'g75a8a704b'
@@ -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, AsyncIterator, Coroutine, Type, cast
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
- self.__running_tasks: set[asyncio.Task] = set()
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: Type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
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(self, reader: StreamReader, writer: StreamWriter) -> None:
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
- self.__start_task(self.__main_loop())
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 __start_task(self, coro: Coroutine[Any, Any, None]) -> None:
214
- task = asyncio.create_task(coro)
215
- self.__running_tasks.add(task)
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 _wait_for_teardown(self) -> None:
228
+ async def __run(self, probe: tuple[float, float] | None) -> None:
220
229
  """
221
- Wait until a connection, that is being closed, is gone. A connection, that was lost, is no longer connected, but
222
- its main loop is still closing the transport. A new connection must not be established before that is done,
223
- because the main loop would close the new connection instead.
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
- idle: float
239
- The time in seconds without data from the Labnode, before it is probed
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
- self.__start_task(self.__probe_loop(idle, timeout))
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 asyncio.TimeoutError:
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
- # wait_for() blocks until the request is done if timeout is None
311
- response = await asyncio.wait_for(self.__pending_requests[request_id], timeout)
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
- try:
403
- async for packet in self.__read_packets():
404
- # Read packets from the socket and process them.
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, which will shut down the transport via __close_transport()
422
- tasks = list(self.__running_tasks)
423
- for task in tasks:
424
- task.cancel()
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
- # Wait for all tasks. The main loop needs longer than the probe, because it closes the transport.
427
- results = await asyncio.gather(*tasks, return_exceptions=True)
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 loop was cancelled before it started, so it could not close the transport
453
+ # The main task was cancelled before it started, so it could not close the transport
431
454
  await self.__close_transport()
432
- for result in results:
433
- if isinstance(result, Exception):
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 __main_loop(), which is started
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, Type, cast
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, Type[Labnode]] = {}
42
+ self.__available_devices: dict[DeviceIdentifier, type[Labnode]] = {}
43
43
 
44
- def register(self, device: Type[Labnode]) -> None:
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: Type[Labnode]
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
- # We cast device.device_identifier because mypy has problems class properties
54
- self.__available_devices[cast(DeviceIdentifier, device.device_identifier())] = device
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, Tuple
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: Tuple[str, int] = hostname, port
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
- # wait_for() blocks until the request is done if timeout is None
200
- reader, writer = await asyncio.wait_for(asyncio.open_connection(*self.__host), self.timeout)
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
- self._start_probe(idle, interval * count)
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:
@@ -107,6 +107,22 @@ class Labnode(ABC):
107
107
  The universally unique identifier of the node
108
108
  """
109
109
 
110
+ @abstractmethod
111
+ async def get_by_function_id(self, function_id: int) -> Any:
112
+ """
113
+ Query a value by function id, instead of calling the named function.
114
+
115
+ Parameters
116
+ ----------
117
+ function_id: int
118
+ The function to query
119
+
120
+ Returns
121
+ -------
122
+ Any
123
+ The result of the query.
124
+ """
125
+
110
126
  async def set_uuid(self, uuid: UUID) -> None:
111
127
  """
112
128
  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, Callable
28
+ from typing import TYPE_CHECKING, Any, override
28
29
  from uuid import UUID
29
30
 
30
31
  from .devices import DeviceIdentifier, ErrorCode, PidFunctionID
@@ -62,6 +63,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
62
63
  __DEVICE_IDENTIFIER = DeviceIdentifier.PID
63
64
 
64
65
  @classmethod
66
+ @override
65
67
  def device_identifier(cls) -> DeviceIdentifier:
66
68
  """The device identifier used to identify the device type"""
67
69
  return cls.__DEVICE_IDENTIFIER
@@ -218,6 +220,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
218
220
  return result
219
221
  return result
220
222
 
223
+ @override
221
224
  async def get_software_version(self) -> tuple[int, int, int]:
222
225
  """
223
226
  Get the firmware version running on the device. The response is a tuple of ints, that represents the version
@@ -230,6 +233,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
230
233
  """
231
234
  return await self.get_by_function_id(PidFunctionID.GET_SOFTWARE_VERSION)
232
235
 
236
+ @override
233
237
  async def get_hardware_version(self) -> tuple[int, int, int]:
234
238
  """
235
239
  Get the hardware revision of the device. The response is a tuple of ints, that represents the version number.
@@ -241,6 +245,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
241
245
  """
242
246
  return await self.get_by_function_id(PidFunctionID.GET_HARDWARE_VERSION)
243
247
 
248
+ @override
244
249
  async def get_serial(self) -> int:
245
250
  """
246
251
  Get the serial number of the device.
@@ -298,6 +303,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
298
303
  mac = bytearray(mac) # convert to bytearray, this also makes sure, that all values are in range(0, 256)
299
304
  await self.__send_single_request(PidFunctionID.SET_MAC_ADDRESS, mac)
300
305
 
306
+ @override
301
307
  async def get_uuid(self) -> UUID:
302
308
  """
303
309
  Get the universally unique identifier of the node.
@@ -319,6 +325,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
319
325
  result = await self.get_by_function_id(PidFunctionID.GET_UUID)
320
326
  return UUID(bytes=bytes(result))
321
327
 
328
+ @override
322
329
  async def set_uuid(self, uuid: UUID) -> None:
323
330
  """
324
331
  Set the universally unique identifier of the node.
@@ -901,6 +908,7 @@ class PidController(Labnode): # pylint: disable=too-many-public-methods
901
908
  )
902
909
  return await self.get_by_function_id(PidFunctionID.GET_ACTIVE_CONNECTION_COUNT)
903
910
 
911
+ @override
904
912
  async def get_by_function_id(self, function_id: PidFunctionID | int) -> Any:
905
913
  """
906
914
  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 serial_asyncio
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 serial_asyncio.open_serial_connection(**self.__tty_kwargs)
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)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: labnode-async
3
- Version: 1.0.0
3
+ Version: 1.1.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.7
14
- Classifier: Programming Language :: Python :: 3.8
15
- Classifier: Programming Language :: Python :: 3.9
16
- Classifier: Programming Language :: Python :: 3.10
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.7
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,12 +83,14 @@ 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.1680.0.2") as device:
92
- # Add your code here
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
96
  See [examples/](/examples/) for more working examples.
@@ -1,9 +1,6 @@
1
1
  cbor2>=5.6.2
2
2
  cobs
3
- pyserial-asyncio
4
-
5
- [:python_version < "3.11"]
6
- typing-extensions
3
+ pyserial-asyncio-fast>=0.16
7
4
 
8
5
  [build]
9
6
  build
@@ -1,7 +1,7 @@
1
1
  {
2
- "tag": "1.0.0",
2
+ "tag": "1.1.0",
3
3
  "distance": 0,
4
- "node": "g652397f073ffb4b957daf375c91ac5fea6e8d012",
4
+ "node": "g75a8a704bb432afebb26a040e7b6a45183c3a6a8",
5
5
  "dirty": false,
6
6
  "branch": "HEAD",
7
7
  "node_date": "2026-12-05"