|
22 | 22 |
|
23 | 23 | import logging |
24 | 24 | from types import TracebackType |
25 | | -from typing import Literal |
| 25 | +from typing import Literal, Generator |
| 26 | +from contextlib import contextmanager |
26 | 27 |
|
27 | 28 | from serial import ( |
28 | 29 | Serial, |
@@ -412,3 +413,52 @@ def exchange(self, cmd: str) -> str: |
412 | 413 | """ |
413 | 414 | self.send(cmd) |
414 | 415 | return self.receive() |
| 416 | + |
| 417 | + @contextmanager |
| 418 | + def timeout_override( |
| 419 | + self, |
| 420 | + timeout: int | None |
| 421 | + ) -> Generator[None, None, None]: |
| 422 | + """ |
| 423 | + Context manager that temporarily overrides connection parameters. |
| 424 | +
|
| 425 | + Parameters |
| 426 | + ---------- |
| 427 | + timeout : int | None |
| 428 | + Temporary timeout in seconds. Set to None to wait indefinitely. |
| 429 | +
|
| 430 | + Returns |
| 431 | + ------- |
| 432 | + Generator |
| 433 | + Context manager generator object. |
| 434 | +
|
| 435 | + Warning |
| 436 | + ------- |
| 437 | + An indefinite timeout might leave the connection in a perpetual |
| 438 | + waiting state, if the instrument became unresponsive in the |
| 439 | + mean time (e.g. it powered off due to low battery charge). |
| 440 | +
|
| 441 | + Example |
| 442 | + ------- |
| 443 | +
|
| 444 | + >>> from serial import Serial |
| 445 | + >>> from geocompy.communication import SerialConnection |
| 446 | + >>> |
| 447 | + >>> port = Serial("COM1", timeout=5) |
| 448 | + >>> with SerialConnection(port) as com: |
| 449 | + ... # normal operation |
| 450 | + ... |
| 451 | + ... # potentially long operation |
| 452 | + ... with com.timeout_override(20): |
| 453 | + ... answer = com.exchange("message") |
| 454 | + ... |
| 455 | + ... # continue normal operation |
| 456 | + ... |
| 457 | + """ |
| 458 | + saved_timeout = self._port.timeout |
| 459 | + |
| 460 | + try: |
| 461 | + self._port.timeout = timeout |
| 462 | + yield |
| 463 | + finally: |
| 464 | + self._port.timeout = saved_timeout |
0 commit comments