From ad7cfe4ea022203f0e180bead711f855b37be757 Mon Sep 17 00:00:00 2001 From: Markus Zolliker Date: Wed, 10 Nov 2021 13:21:44 +0100 Subject: [PATCH] automatically register subclasses of AsynConn using __init_subclass__ method. + correct typo Change-Id: I9a57c467efcd138651248f92fbf84195624e0b9a Reviewed-on: https://forge.frm2.tum.de/review/c/sine2020/secop/playground/+/27093 Tested-by: Jenkins Automated Tests Reviewed-by: Enrico Faulhaber Reviewed-by: Markus Zolliker --- secop/lib/__init__.py | 2 +- secop/lib/asynconn.py | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/secop/lib/__init__.py b/secop/lib/__init__.py index d29df77..96fb073 100644 --- a/secop/lib/__init__.py +++ b/secop/lib/__init__.py @@ -98,7 +98,7 @@ def clamp(_min, value, _max): def get_class(spec): - """loads a class given by string in dotted notaion (as python would do)""" + """loads a class given by string in dotted notation (as python would do)""" modname, classname = spec.rsplit('.', 1) if modname.startswith('secop'): module = importlib.import_module(modname) diff --git a/secop/lib/asynconn.py b/secop/lib/asynconn.py index 6d9fc5c..9d5df16 100644 --- a/secop/lib/asynconn.py +++ b/secop/lib/asynconn.py @@ -48,6 +48,7 @@ class ConnectionClosed(ConnectionError): class AsynConn: timeout = 1 # inter byte timeout + scheme = None SCHEME_MAP = {} connection = None # is not None, if connected defaultport = None @@ -79,8 +80,10 @@ class AsynConn: self.disconnect() @classmethod - def register_scheme(cls, scheme): - cls.SCHEME_MAP[scheme] = cls + def __init_subclass__(cls): + """register subclass to scheme, if available""" + if cls.scheme: + cls.SCHEME_MAP[cls.scheme] = cls def disconnect(self): raise NotImplementedError @@ -154,6 +157,8 @@ class AsynConn: class AsynTcp(AsynConn): + scheme = 'tcp' + def __init__(self, uri, *args, **kwargs): super().__init__(uri, *args, **kwargs) self.uri = uri @@ -202,9 +207,6 @@ class AsynTcp(AsynConn): raise ConnectionClosed() # marks end of connection -AsynTcp.register_scheme('tcp') - - class AsynSerial(AsynConn): """a serial connection using pyserial @@ -221,6 +223,7 @@ class AsynSerial(AsynConn): and others (see documentation of serial.Serial) """ + scheme = 'serial' PARITY_NAMES = {name[0]: name for name in ['NONE', 'ODD', 'EVEN', 'MASK', 'SPACE']} def __init__(self, uri, *args, **kwargs): @@ -282,6 +285,3 @@ class AsynSerial(AsynConn): return self.connection.read(n) data = self.connection.read(1) return data + self.connection.read(self.connection.in_waiting) - - -AsynSerial.register_scheme('serial')