Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions pslab/bus/busio.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,12 +493,12 @@ def _read_with_timeout(self, nbytes: int = None, *, line=False):
char = self._read_byte()
start_time = time.time()

if line and char == 0xA:
break

data.append(char)
total_read += 1

if line and char == 0xA:
break

if nbytes and total_read == nbytes:
break

Expand Down
73 changes: 73 additions & 0 deletions tests/test_uart.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

import pytest

from pslab import protocol as CP
from pslab.bus import busio
from pslab.bus.uart import UART
from pslab.instrument.logic_analyzer import LogicAnalyzer
from pslab.instrument.waveform_generator import PWMGenerator
Expand Down Expand Up @@ -82,3 +84,74 @@ def test_read_int(pwm: PWMGenerator, uart: UART):
value = uart.read_int()

assert value in (0x5555, 0x55AA, 0xAA55, 0xAAAA)


class _FakeUARTDevice:
"""Mock connection handler providing scripted byte streams for UART tests."""

def __init__(self, stream: bytes = b""):
self.stream = list(stream)
self.version = "PSLab V5"
self._last_cmd = None

def send_byte(self, val):
self._last_cmd = val

def send_int(self, val):
pass

def get_ack(self):
return b"\x00"

def get_byte(self) -> int:
if self._last_cmd == CP.READ_UART2_STATUS:
return 1 if self.stream else 0
if self._last_cmd == CP.READ_BYTE and self.stream:
return self.stream.pop(0)
return 0


def _make_uart(device: _FakeUARTDevice, timeout: float = 0.1) -> busio.UART:
"""Helper to initialize a UART instance for read testing without hardware setup."""
uart = busio.UART.__new__(busio.UART)
uart._device = device
uart._timeout = timeout
return uart


def test_busio_uart_readline_preserves_newline():
device = _FakeUARTDevice(b"hello\r\n")
uart = _make_uart(device)
assert uart.readline() == b"hello\r\n"


def test_busio_uart_readline_blank_line():
device = _FakeUARTDevice(b"\n")
uart = _make_uart(device)
assert uart.readline() == b"\n"


def test_busio_uart_readline_successive_lines():
device = _FakeUARTDevice(b"first\r\nsecond\n")
uart = _make_uart(device)
assert uart.readline() == b"first\r\n"
assert uart.readline() == b"second\n"


def test_busio_uart_readline_timeout_empty():
device = _FakeUARTDevice(b"")
uart = _make_uart(device, timeout=0.05)
assert uart.readline() is None


def test_busio_uart_readline_timeout_partial():
device = _FakeUARTDevice(b"partial")
uart = _make_uart(device, timeout=0.05)
assert uart.readline() == b"partial"


def test_busio_uart_read_nbytes():
device = _FakeUARTDevice(b"12345678")
uart = _make_uart(device)
assert uart.read(4) == b"1234"