From c3afdc5e151fc031f36eb98956667aa2aacb1471 Mon Sep 17 00:00:00 2001 From: Karl Palsson Date: Tue, 2 Jul 2024 16:26:39 +0000 Subject: [PATCH] Connect using a URL for maximum flexibility Use serial.serial_for_url instead of serial.Serial() so that all the helpful URL formats can be used, instead of just devices. This is entirely backwards compatible, it simply allows new functionality. See https://pythonhosted.org/pyserial/url_handlers.html#urls Signed-off-by: Karl Palsson --- SerialLibrary.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/SerialLibrary.py b/SerialLibrary.py index 60f67dc..93a46da 100644 --- a/SerialLibrary.py +++ b/SerialLibrary.py @@ -68,25 +68,29 @@ def __init__(self, unicode='utf-8'): self.buffer = BytesIO() @keyword("Connect") - def connect_to_serial(self, device: str, baudrate: int) -> serial.Serial: + def connect_to_serial_url(self, url: str, baudrate: int) -> serial.Serial: """ Connects to a serial device. - ``device`` - The device name or a device number. + ``url`` - The device name or URL. see: https://pythonhosted.org/pyserial/url_handlers.html#urls ``baudrate`` - The baud rate to use for communication. + NOTE: baudrate is kept for backwords compatibility. === Example === - | Connect | | - | Connect | /dev/ttyUSB0 | 115200 + | ConnectUrl | | + | ConnectUrl | /dev/ttyUSB0 | 115200 + | ConnectUrl | spy:///dev/ttyUSB0/file=dump-comms.txt | 115200 === Returns === The connected serial device object. """ try: - self.device = serial.Serial(device, baudrate=baudrate) + self.device = serial.serial_for_url(url, do_not_open=True) + self.device.baudrate = baudrate + self.device.open() except SerialException as exc: - raise PySerialError(f"Failed to connect {device}: {exc}") from exc + raise PySerialError(f"Failed to connect {url}: {exc}") from exc return self.device @keyword("Disconnect")