diff options
author | Sébastien Dailly <sebastien@dailly.me> | 2023-07-15 14:44:41 +0200 |
---|---|---|
committer | Sébastien Dailly <sebastien@dailly.me> | 2023-07-15 14:59:43 +0200 |
commit | 02d676bda89c2fb8469ea81f7429c19c1e29df7c (patch) | |
tree | 11dae86a561a4800661e6c174b47611a704f857e /serial_conn.py |
Initial commit
Diffstat (limited to 'serial_conn.py')
-rwxr-xr-x | serial_conn.py | 46 |
1 files changed, 46 insertions, 0 deletions
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)
|