|
16 | 16 | from types import TracebackType |
17 | 17 | from typing import Iterable |
18 | 18 |
|
19 | | -from serial import Serial, SerialException, SerialTimeoutException |
| 19 | +from serial import ( |
| 20 | + Serial, |
| 21 | + SerialException, |
| 22 | + SerialTimeoutException, |
| 23 | + PARITY_NONE |
| 24 | +) |
20 | 25 |
|
21 | 26 |
|
22 | 27 | class Connection: |
@@ -125,6 +130,64 @@ def exchange1(self, cmd: str) -> str: |
125 | 130 | raise NotImplementedError("interface does not implement 'exchange1'") |
126 | 131 |
|
127 | 132 |
|
| 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 | + |
128 | 191 | class SerialConnection(Connection): |
129 | 192 | """ |
130 | 193 | Connection wrapping an open serial port. |
|
0 commit comments