From 02d676bda89c2fb8469ea81f7429c19c1e29df7c Mon Sep 17 00:00:00 2001 From: Sébastien Dailly Date: Sat, 15 Jul 2023 14:44:41 +0200 Subject: Initial commit --- serial_conn.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100755 serial_conn.py (limited to 'serial_conn.py') diff --git a/serial_conn.py b/serial_conn.py new file mode 100755 index 0000000..a08543a --- /dev/null +++ b/serial_conn.py @@ -0,0 +1,46 @@ +from zope import interface +from interfaces.message import ISocketMessage + +@interface.implementer(ISocketMessage) +class Layout(object): + + def __init__(self, message): + self.content = message + +from zope import component +from interfaces.endpoint import IConnection +import serial +from queue import Queue + +@interface.implementer(IConnection) +class SerialConnection(object): + """ Define a connected element (serial, network…) + """ + + def __init__(self, configuration): + self.serial_port = configuration["port"] + + def connect(self) -> None: + """ Connect """ + self.s = serial.Serial(port=self.serial_port, timeout=0) + + def read(self) -> str: + """ Read from the connection and return the bytes. + Return None if there is nothing to read (non-blocking) + Raise an exception if disconnected """ + + + in_waiting = self.s.in_waiting != 0 + if in_waiting == 0: + # If we do not have any entry from the macropad, just return + return None + + line = self.s.readline() + layout = str(line, "utf-8").strip() + component.handle(Layout(layout)) + return line + + def write(self, content:str) -> None: + """ Write into the connection. + Raise an exception if disconnected """ + self.s.write(content) -- cgit v1.2.3