|
| 1 | +# SPDX-FileCopyrightText: 2026 Melissa LeBlanc-Williams for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +"""Generic Linux UART class wrapping PySerial""" |
| 5 | + |
| 6 | +import os |
| 7 | + |
| 8 | +import serial |
| 9 | + |
| 10 | + |
| 11 | +class UART: |
| 12 | + """UART class for generic Linux using PySerial. |
| 13 | +
|
| 14 | + Wraps a ``serial.Serial`` instance so that CircuitPython UART code |
| 15 | + runs unchanged on Linux / SBC boards. |
| 16 | + """ |
| 17 | + |
| 18 | + # Map of known port IDs to device paths, by platform. |
| 19 | + # If the port entry in uartPorts is a string it is used directly; |
| 20 | + # otherwise we try common symlink / device conventions. |
| 21 | + _PORT_SEARCH_PATTERNS = ( |
| 22 | + "/dev/serial{}", |
| 23 | + "/dev/ttyS{}", |
| 24 | + "/dev/ttyAMA{}", |
| 25 | + ) |
| 26 | + |
| 27 | + # pylint: disable=too-many-arguments |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + port_id, |
| 31 | + baudrate=9600, |
| 32 | + bits=8, |
| 33 | + parity=None, |
| 34 | + stop=1, |
| 35 | + timeout=1, |
| 36 | + receiver_buffer_size=64, # pylint: disable=unused-argument |
| 37 | + ): |
| 38 | + device = self._resolve_device(port_id) |
| 39 | + |
| 40 | + # Translate CircuitPython parity values to pyserial constants. |
| 41 | + if parity is None: |
| 42 | + ser_parity = serial.PARITY_NONE |
| 43 | + elif parity == 0: |
| 44 | + ser_parity = serial.PARITY_EVEN |
| 45 | + elif parity == 1: |
| 46 | + ser_parity = serial.PARITY_ODD |
| 47 | + else: |
| 48 | + raise ValueError("Invalid parity: {}".format(parity)) |
| 49 | + |
| 50 | + stop_map = {1: serial.STOPBITS_ONE, 2: serial.STOPBITS_TWO} |
| 51 | + ser_stop = stop_map.get(stop) |
| 52 | + if ser_stop is None: |
| 53 | + raise ValueError("Invalid stop bits: {}".format(stop)) |
| 54 | + |
| 55 | + byte_size_map = { |
| 56 | + 5: serial.FIVEBITS, |
| 57 | + 6: serial.SIXBITS, |
| 58 | + 7: serial.SEVENBITS, |
| 59 | + 8: serial.EIGHTBITS, |
| 60 | + } |
| 61 | + ser_bytesize = byte_size_map.get(bits) |
| 62 | + if ser_bytesize is None: |
| 63 | + raise ValueError("Invalid bits: {}".format(bits)) |
| 64 | + |
| 65 | + # PySerial timeout is in seconds (float); CircuitPython also uses |
| 66 | + # seconds as of CP 4.0+. Blinka's older MicroPython path passed |
| 67 | + # timeout in *milliseconds* to machine.UART; we accept seconds here. |
| 68 | + self._serial = serial.Serial( |
| 69 | + device, |
| 70 | + baudrate=baudrate, |
| 71 | + bytesize=ser_bytesize, |
| 72 | + parity=ser_parity, |
| 73 | + stopbits=ser_stop, |
| 74 | + timeout=timeout, |
| 75 | + write_timeout=timeout, |
| 76 | + ) |
| 77 | + |
| 78 | + # ----- helpers ----- |
| 79 | + |
| 80 | + @classmethod |
| 81 | + def _resolve_device(cls, port_id): |
| 82 | + """Turn a port identifier into a ``/dev/`` path. |
| 83 | +
|
| 84 | + *port_id* may be: |
| 85 | + - A string that is already a device path (e.g. ``"/dev/serial0"``). |
| 86 | + - An integer that will be resolved via common naming conventions. |
| 87 | + """ |
| 88 | + if isinstance(port_id, str) and os.path.exists(port_id): |
| 89 | + return port_id |
| 90 | + |
| 91 | + if isinstance(port_id, int): |
| 92 | + for pattern in cls._PORT_SEARCH_PATTERNS: |
| 93 | + path = pattern.format(port_id) |
| 94 | + if os.path.exists(path): |
| 95 | + return path |
| 96 | + |
| 97 | + raise RuntimeError( |
| 98 | + "Could not find UART device for port {!r}. " |
| 99 | + "Make sure the serial port is enabled.".format(port_id) |
| 100 | + ) |
| 101 | + |
| 102 | + # ----- CircuitPython-compatible API ----- |
| 103 | + |
| 104 | + def deinit(self): |
| 105 | + """Close the serial port.""" |
| 106 | + if self._serial is not None: |
| 107 | + self._serial.close() |
| 108 | + self._serial = None |
| 109 | + |
| 110 | + def read(self, nbytes=None): |
| 111 | + """Read up to *nbytes* bytes. Returns ``None`` when no data is |
| 112 | + available (matching CircuitPython behaviour, not pyserial's ``b""``). |
| 113 | + """ |
| 114 | + if nbytes is None: |
| 115 | + # Read whatever is available; if nothing, wait up to timeout. |
| 116 | + data = self._serial.read(self._serial.in_waiting or 1) |
| 117 | + else: |
| 118 | + data = self._serial.read(nbytes) |
| 119 | + return data if data else None |
| 120 | + |
| 121 | + def readinto(self, buf, nbytes=None): |
| 122 | + """Read bytes into *buf*. Returns number of bytes read or ``None``.""" |
| 123 | + if nbytes is None: |
| 124 | + nbytes = len(buf) |
| 125 | + data = self._serial.read(nbytes) |
| 126 | + if not data: |
| 127 | + return None |
| 128 | + n = len(data) |
| 129 | + buf[:n] = data |
| 130 | + return n |
| 131 | + |
| 132 | + def readline(self): |
| 133 | + """Read a line (up to ``\\n``). Returns ``None`` on timeout with no data.""" |
| 134 | + data = self._serial.readline() |
| 135 | + return data if data else None |
| 136 | + |
| 137 | + def write(self, buf): |
| 138 | + """Write bytes from *buf*. Returns the number of bytes written.""" |
| 139 | + return self._serial.write(buf) |
| 140 | + |
| 141 | + @property |
| 142 | + def baudrate(self): |
| 143 | + """The current baudrate.""" |
| 144 | + return self._serial.baudrate |
| 145 | + |
| 146 | + @baudrate.setter |
| 147 | + def baudrate(self, value): |
| 148 | + self._serial.baudrate = value |
| 149 | + |
| 150 | + @property |
| 151 | + def in_waiting(self): |
| 152 | + """The number of bytes in the input buffer, available to be read.""" |
| 153 | + return self._serial.in_waiting |
| 154 | + |
| 155 | + @property |
| 156 | + def timeout(self): |
| 157 | + """Read timeout in seconds (float).""" |
| 158 | + return self._serial.timeout |
| 159 | + |
| 160 | + @timeout.setter |
| 161 | + def timeout(self, value): |
| 162 | + self._serial.timeout = value |
| 163 | + self._serial.write_timeout = value |
| 164 | + |
| 165 | + def reset_input_buffer(self): |
| 166 | + """Discard any unread data in the input buffer.""" |
| 167 | + self._serial.reset_input_buffer() |
0 commit comments