Skip to content

Commit 27fa558

Browse files
committed
Added open_serial helper function
1 parent ce9b914 commit 27fa558

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

src/geocompy/communication.py

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@
1616
from types import TracebackType
1717
from typing import Iterable
1818

19-
from serial import Serial, SerialException, SerialTimeoutException
19+
from serial import (
20+
Serial,
21+
SerialException,
22+
SerialTimeoutException,
23+
PARITY_NONE
24+
)
2025

2126

2227
class Connection:
@@ -125,6 +130,64 @@ def exchange1(self, cmd: str) -> str:
125130
raise NotImplementedError("interface does not implement 'exchange1'")
126131

127132

133+
def open_serial(
134+
port: str,
135+
*,
136+
speed: int = 9600,
137+
databits: int = 8,
138+
stopbits: int = 1,
139+
parity: str = PARITY_NONE,
140+
timeout: int = 15,
141+
eom: str = "\r\n",
142+
eoa: str = "\r\n"
143+
) -> SerialConnection:
144+
"""
145+
Constructs a SerialConnection with the given communication
146+
parameters.
147+
148+
Parameters
149+
----------
150+
port : str
151+
Name of the port to use (e.g. ``COM1`` or ``/dev/ttyUSB0``).
152+
speed : int, optional
153+
Communication speed (baud), by default 9600
154+
databits : int, optional
155+
Number of data bits, by default 8
156+
stopbits : int, optional
157+
Number of stop bits, by default 1
158+
parity : str, optional
159+
Parity bit behavior, by default PARITY_NONE
160+
timeout : int, optional
161+
Communication timeout threshold, by default 15
162+
eom : str, optional
163+
EndOfMessage sequence, by default "\\r\\n"
164+
eoa : str, optional
165+
EndOfAnswer sequence, by default "\\r\\n"
166+
167+
Returns
168+
-------
169+
SerialConnection
170+
171+
Examples
172+
--------
173+
174+
Opening a serial connection similar to a file:
175+
176+
>>> conn = open_serial("COM1", speed=19200, timeout=5)
177+
>>> # do operations
178+
>>> conn.close()
179+
180+
Using as a context manager:
181+
182+
>>> with open_serial("COM1", timeout=20) as conn:
183+
... conn.send("test")
184+
185+
"""
186+
serialport = Serial(port, speed, databits, parity, stopbits, timeout)
187+
wrapper = SerialConnection(serialport, eom=eom, eoa=eoa)
188+
return wrapper
189+
190+
128191
class SerialConnection(Connection):
129192
"""
130193
Connection wrapping an open serial port.

0 commit comments

Comments
 (0)