Created
October 13, 2020 17:20
-
-
Save dotchetter/cdc63dae0ba6f738024e6cbc1693dca6 to your computer and use it in GitHub Desktop.
Simple script to parse UART on linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import serial | |
import sys | |
import argparse | |
class ConnectionHandle: | |
def __init__(self, *args, **kwargs): | |
self._isactive = False | |
self._connection = None | |
self._bytes_available = 0 | |
for k, v in kwargs.items(): | |
setattr(self, k, v) | |
def __bool__(self): | |
return self._isactive | |
def __repr__(self): | |
return f"ConnectionHandle(active: {self._isactive})" | |
def connect_arduino(self, port, baudrate, | |
parity=serial.PARITY_NONE, | |
stopbits=serial.STOPBITS_ONE, | |
bytesize=serial.EIGHTBITS, | |
timeout=0) -> bool: | |
try: | |
self._connection = serial.Serial(port=port, | |
baudrate=baudrate, | |
parity=parity, | |
stopbits=stopbits, | |
bytesize=bytesize, | |
timeout=timeout) | |
except serial.serialutil.SerialException as e: | |
self._isactive = False | |
raise(e) | |
else: | |
self._isactive = True | |
def readline(self): | |
return self._connection.readline().decode("utf-8") | |
def close(self): | |
self._connection.close() | |
self._isactive = False | |
if __name__ == "__main__": | |
argument_parser = argparse.ArgumentParser() | |
argument_parser.add_argument("-port", help="Serial port for the device, linux: usually /dev/ttylS* (* = some digit), Windows usually COM*") | |
argument_parser.add_argument("-baudrate", help="Baudrate for communications, usually 9600 or 115200") | |
args = argument_parser.parse_args() | |
arduino_connection = ConnectionHandle() | |
arduino_connection.connect_arduino(port=args.port, baudrate=args.baudrate) | |
while arduino_connection: | |
try: | |
reading = arduino_connection.readline() | |
if reading: | |
print(reading) | |
except KeyboardInterrupt: | |
arduino_connection.close() | |
print("connection closed") | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment