Skip to content

Commit 0662b2a

Browse files
committed
Added timeout_override method to SerialConnection
1 parent f77b466 commit 0662b2a

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/geocompy/communication.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222

2323
import logging
2424
from types import TracebackType
25-
from typing import Literal
25+
from typing import Literal, Generator
26+
from contextlib import contextmanager
2627

2728
from serial import (
2829
Serial,
@@ -412,3 +413,45 @@ def exchange(self, cmd: str) -> str:
412413
"""
413414
self.send(cmd)
414415
return self.receive()
416+
417+
@contextmanager
418+
def timeout_override(self, timeout: int) -> Generator[None, None, None]:
419+
"""
420+
Context manager that temporarily overrides connection parameters.
421+
422+
Parameters
423+
----------
424+
timeout : int
425+
Temporary timeout in seconds.
426+
427+
Returns
428+
-------
429+
Generator
430+
Context manager generator object.
431+
432+
Example
433+
-------
434+
435+
>>> from serial import Serial
436+
>>> from geocompy.communication import SerialConnection
437+
>>>
438+
>>> port = Serial("COM1", timeout=5)
439+
>>> with SerialConnection(port) as com:
440+
... # normal operation
441+
...
442+
... # potentially long operation
443+
... with com.timeout_override(20):
444+
... answer = com.exchange("message")
445+
...
446+
... # continue normal operation
447+
...
448+
"""
449+
saved_timeout = self._port.timeout
450+
451+
try:
452+
if timeout is not None:
453+
self._port.timeout = timeout
454+
yield
455+
finally:
456+
if timeout is not None:
457+
self._port.timeout = saved_timeout

0 commit comments

Comments
 (0)