try to follow PEP8

- fixed most important code after checking with flake8
- ignored code which has to be reworked or removed
+ mark unused code with 'TODO: remove ...'

Change-Id: Ic45e541049e391e2853d29cd64bb0963bd9a2125
Reviewed-on: https://forge.frm2.tum.de/review/c/sine2020/secop/playground/+/25053
Tested-by: Jenkins Automated Tests <pedersen+jenkins@frm2.tum.de>
Reviewed-by: Enrico Faulhaber <enrico.faulhaber@frm2.tum.de>
This commit is contained in:
zolliker 2021-02-24 10:51:09 +01:00
parent bb6f692c6b
commit 1464a6bce5
22 changed files with 95 additions and 57 deletions

View File

@ -21,6 +21,8 @@
# *****************************************************************************
"""basic validators (for properties)"""
# TODO: remove, as not used anymore
import re

View File

@ -31,7 +31,7 @@ from threading import Event, RLock, current_thread
import secop.errors
import secop.params
from secop.datatypes import get_datatype
from secop.lib import formatExtendedStack, formatExtendedTraceback, mkthread
from secop.lib import mkthread
from secop.lib.asynconn import AsynConn, ConnectionClosed
from secop.protocol.interface import decode_msg, encode_msg_frame
from secop.protocol.messages import COMMANDREQUEST, \
@ -161,7 +161,6 @@ class ProxyClient:
if not cblist:
self.callbacks[cbname].pop(key)
def callback(self, key, cbname, *args):
"""perform callbacks

View File

@ -21,6 +21,8 @@
# *****************************************************************************
"""Define Client side proxies"""
# TODO: remove, as currently not used
import json
import queue
@ -48,7 +50,6 @@ except ImportError:
pass
class TCPConnection:
# disguise a TCP connection as serial one

View File

@ -21,7 +21,7 @@
# *****************************************************************************
"""console client"""
# this needs to be reworked or removed
# TODO: remove, as currently not used
import code

View File

@ -22,7 +22,6 @@
"""Define (internal) SECoP Errors"""
class SECoPError(RuntimeError):
def __init__(self, *args, **kwds):

View File

@ -58,7 +58,7 @@ def write_config(file_name, tree_widget):
value = value.replace('\n\n', '\n.\n')
value = value.replace('\n', '\n ')
itm_lines[id(itm)] = '[%s %s]\n' % (itm.kind, itm.name) +\
value_str % (SECTIONS[itm.kind], value)
value_str % (SECTIONS[itm.kind], value)
# TODO params and props
elif itm.kind == PARAMETER and value:
itm_lines[id(itm)] = value_str % (itm.name, value)
@ -142,7 +142,7 @@ def read_config(file_path):
else:
param.addChild(TreeWidgetItem(PROPERTY,
separated[1], get_value(config, section,
option)))
option)))
node = get_comments(node, ifs, mods, file_path)
return node, ifs, mods

View File

@ -90,7 +90,7 @@ class QSECNode(QObject):
def queryCache(self, module):
return {k: Value(*self.conn.cache[(module, k)])
for k in self.modules[module]['parameters']}
for k in self.modules[module]['parameters']}
def syncCommunicate(self, action, ident='', data=None):
reply = self.conn.request(action, ident, data)

View File

@ -36,19 +36,19 @@ class CommandDialog(QDialog):
loadUi(self, 'cmddialog.ui')
self.setWindowTitle('Arguments for %s' % cmdname)
#row = 0
# row = 0
self._labels = []
self.widgets = []
# improve! recursive?
dtype = argument
l = QLabel(repr(dtype))
l.setWordWrap(True)
w = get_widget(dtype, readonly=False)
self.gridLayout.addWidget(l, 0, 0)
self.gridLayout.addWidget(w, 0, 1)
self._labels.append(l)
self.widgets.append(w)
label = QLabel(repr(dtype))
label.setWordWrap(True)
widget = get_widget(dtype, readonly=False)
self.gridLayout.addWidget(label, 0, 0)
self.gridLayout.addWidget(widget, 0, 1)
self._labels.append(label)
self.widgets.append(widget)
self.gridLayout.setRowStretch(1, 1)
self.setModal(True)

View File

@ -168,7 +168,6 @@ class NodeCtrl(QWidget):
print(secop.lib.formatExtendedTraceback())
widget = QLabel('Bad configured Module %s! (%s)' % (modname, e))
if unit:
labelstr = '%s (%s):' % (modname, unit)
else:
@ -290,7 +289,7 @@ class DrivableWidget(ReadableWidget):
def update_current(self, value):
self.currentLineEdit.setText(str(value))
#elif self._is_enum:
# elif self._is_enum:
# member = self._map[self._revmap[value.value]]
# self.currentLineEdit.setText('%s.%s (%d)' % (member.enum.name, member.name, member.value))

View File

@ -22,12 +22,9 @@
# *****************************************************************************
from secop.datatypes import EnumType, FloatRange, IntRange
from secop.gui.qt import QCheckBox, QLabel, QLineEdit, QMessageBox
from secop.gui.qt import QPushButton as QButton
from secop.gui.qt import QSizePolicy, Qt, QWidget, pyqtSignal, pyqtSlot
from secop.datatypes import EnumType
from secop.gui.qt import QWidget, pyqtSignal, pyqtSlot
from secop.gui.util import loadUi
from secop.lib import formatExtendedStack
class ParameterWidget(QWidget):

View File

@ -32,6 +32,7 @@ uipath = path.dirname(__file__)
def loadUi(widget, uiname, subdir='ui'):
uic.loadUi(path.join(uipath, subdir, uiname), widget)
class Value:
def __init__(self, value, timestamp=None, readerror=None):
self.value = value

View File

@ -29,6 +29,7 @@ from secop.gui.qt import QCheckBox, QComboBox, QDialog, \
QLabel, QLineEdit, QSpinBox, QTextEdit, QVBoxLayout
from secop.gui.util import loadUi
# XXX: implement live validators !!!!
# XXX: signals upon change of value
# XXX: honor readonly in all cases!
@ -171,12 +172,12 @@ class StructWidget(QGroupBox):
self._labels = []
for idx, name in enumerate(sorted(datatype.members)):
dt = datatype.members[name]
w = get_widget(dt, readonly=readonly, parent=self)
l = QLabel(name)
self.layout.addWidget(l, idx, 0)
self.layout.addWidget(w, idx, 1)
self._labels.append(l)
self.subwidgets[name] = (w, dt)
widget = get_widget(dt, readonly=readonly, parent=self)
label = QLabel(name)
self.layout.addWidget(label, idx, 0)
self.layout.addWidget(widget, idx, 1)
self._labels.append(label)
self.subwidgets[name] = (widget, dt)
self.datatypes.append(dt)
self.setLayout(self.layout)
@ -215,21 +216,22 @@ class ArrayWidget(QGroupBox):
w.set_value(v)
def get_widget(datatype, readonly=False, parent=None):
return {FloatRange: FloatWidget,
IntRange: IntWidget,
StringType: StringWidget,
TextType: TextWidget,
BLOBType: BlobWidget,
EnumType: EnumWidget,
BoolType: BoolWidget,
TupleOf: TupleWidget,
StructOf: StructWidget,
ArrayOf: ArrayWidget,
return {
FloatRange: FloatWidget,
IntRange: IntWidget,
StringType: StringWidget,
TextType: TextWidget,
BLOBType: BlobWidget,
EnumType: EnumWidget,
BoolType: BoolWidget,
TupleOf: TupleWidget,
StructOf: StructWidget,
ArrayOf: ArrayWidget,
}.get(datatype.__class__)(datatype, readonly, parent)
# TODO: handle NoneOr
class msg(QDialog):
def __init__(self, stuff, parent=None):
super(msg, self).__init__(parent)
@ -242,7 +244,7 @@ class msg(QDialog):
dt = StructOf(i=IntRange(0, 10), f=FloatRange(), b=BoolType())
w = StructWidget(dt)
self.gridLayout.addWidget(w, row, 1)
row+=1
row += 1
self.gridLayout.addWidget(QLabel('stuff'), row, 0, 1, 0)
row += 1 # at pos (0,0) span 2 cols, 1 row

View File

@ -58,6 +58,7 @@ CONFIG['basedir'] = repodir
unset_value = object()
class lazy_property:
"""A property that calculates its value only once."""

View File

@ -62,10 +62,10 @@ class AsynConn:
except (ValueError, TypeError, AssertionError):
if 'COM' in uri:
raise ValueError("the correct uri for a COM port is: "
"'serial://COM<i>[?<option>=<value>[+<option>=value ...]]'" )
"'serial://COM<i>[?<option>=<value>[+<option>=value ...]]'")
if '/dev' in uri:
raise ValueError("the correct uri for a serial port is: "
"'serial:///dev/<tty>[?<option>=<value>[+<option>=value ...]]'" )
"'serial:///dev/<tty>[?<option>=<value>[+<option>=value ...]]'")
raise ValueError('invalid uri: %s' % uri)
iocls = cls.SCHEME_MAP['tcp']
uri = 'tcp://%s:%d' % host_port

View File

@ -32,6 +32,7 @@ class EnumMember:
has an int-type value and attributes 'name' and 'value'
"""
__slots__ = ['name', 'value', 'enum']
def __init__(self, enum, name, value):
if not isinstance(enum, Enum):
raise TypeError('1st Argument must be an instance of class Enum()')
@ -49,7 +50,7 @@ class EnumMember:
try:
other = int(other)
except Exception:
#raise TypeError('%r can not be compared to %r!' %(other, self))
# raise TypeError('%r can not be compared to %r!' %(other, self))
return -1 # XXX:!
if self.value < other:
return -1
@ -59,10 +60,12 @@ class EnumMember:
def __lt__(self, other):
return self.__cmp__(other.value if isinstance(other, EnumMember) else other) == -1
def __le__(self, other):
return self.__cmp__(other.value if isinstance(other, EnumMember) else other) < 1
def __eq__(self, other):
if isinstance(other, (EnumMember)):
if isinstance(other, EnumMember):
return other.value == self.value
if isinstance(other, int):
return other == self.value
@ -72,10 +75,13 @@ class EnumMember:
return self.name == other
return False
return self.__cmp__(other.value if isinstance(other, EnumMember) else other) == 0
def __ne__(self, other):
return not self.__eq__(other)
def __ge__(self, other):
return self.__cmp__(other.value if isinstance(other, EnumMember) else other) > -1
def __gt__(self, other):
return self.__cmp__(other.value if isinstance(other, EnumMember) else other) == 1
@ -100,77 +106,105 @@ class EnumMember:
def __repr__(self):
return '<%s%s (%d)>' % (self.enum.name + '.' if self.enum.name else '', self.name, self.value)
# numeric operations: delegate to int. Do we really need any of those?
def __add__(self, other):
return self.value.__add__(other.value if isinstance(other, EnumMember) else other)
def __sub__(self, other):
return self.value.__sub__(other.value if isinstance(other, EnumMember) else other)
def __mul__(self, other):
return self.value.__mul__(other.value if isinstance(other, EnumMember) else other)
def __truediv__(self, other):
return self.value.__truediv__(other.value if isinstance(other, EnumMember) else other)
def __floordiv__(self, other):
return self.value.__floordiv__(other.value if isinstance(other, EnumMember) else other)
def __mod__(self, other):
return self.value.__mod__(other.value if isinstance(other, EnumMember) else other)
def __divmod__(self, other):
return self.value.__divmod__(other.value if isinstance(other, EnumMember) else other)
def __pow__(self, other, *args):
return self.value.__pow__(other, *args)
def __lshift__(self, other):
return self.value.__lshift__(other.value if isinstance(other, EnumMember) else other)
def __rshift__(self, other):
return self.value.__rshift__(other.value if isinstance(other, EnumMember) else other)
def __radd__(self, other):
return self.value.__radd__(other.value if isinstance(other, EnumMember) else other)
def __rsub__(self, other):
return self.value.__rsub__(other.value if isinstance(other, EnumMember) else other)
def __rmul__(self, other):
return self.value.__rmul__(other.value if isinstance(other, EnumMember) else other)
def __rtruediv__(self, other):
return self.value.__rtruediv__(other.value if isinstance(other, EnumMember) else other)
def __rfloordiv__(self, other):
return self.value.__rfloordiv__(other.value if isinstance(other, EnumMember) else other)
def __rmod__(self, other):
return self.value.__rmod__(other.value if isinstance(other, EnumMember) else other)
def __rdivmod__(self, other):
return self.value.__rdivmod__(other.value if isinstance(other, EnumMember) else other)
def __rpow__(self, other, *args):
return self.value.__rpow__(other, *args)
def __rlshift__(self, other):
return self.value.__rlshift__(other.value if isinstance(other, EnumMember) else other)
def __rrshift__(self, other):
return self.value.__rrshift__(other.value if isinstance(other, EnumMember) else other)
# logical operations
def __and__(self, other):
return self.value.__and__(other.value if isinstance(other, EnumMember) else other)
def __xor__(self, other):
return self.value.__xor__(other.value if isinstance(other, EnumMember) else other)
def __or__(self, other):
return self.value.__or__(other.value if isinstance(other, EnumMember) else other)
def __rand__(self, other):
return self.value.__rand__(other.value if isinstance(other, EnumMember) else other)
def __rxor__(self, other):
return self.value.__rxor__(other.value if isinstance(other, EnumMember) else other)
def __ror__(self, other):
return self.value.__ror__(other.value if isinstance(other, EnumMember) else other)
# other stuff
def __neg__(self):
return self.value.__neg__()
def __pos__(self):
return self.value.__pos__()
def __abs__(self):
return self.value.__abs__()
def __invert__(self):
return self.value.__invert__()
def __int__(self):
return self.value.__int__()
def __float__(self):
return self.value.__float__()
#return NotImplemented # makes no sense
def __index__(self):
return self.value.__index__()
@ -206,6 +240,7 @@ class Enum(dict):
You only can create an extended Enum.
"""
name = ''
def __init__(self, name='', parent=None, **kwds):
super(Enum, self).__init__()
if isinstance(name, (dict, Enum)) and parent is None:
@ -217,7 +252,7 @@ class Enum(dict):
# if name was not given, use that of the parent
# this means, an extended Enum behaves like the parent
# THIS MAY BE CONFUSING SOMETIMES!
name=parent.name
name = parent.name
# else:
# raise TypeError('Enum instances need a name or an Enum parent!')
if not isinstance(name, str):
@ -225,8 +260,9 @@ class Enum(dict):
names = set()
values = set()
# pylint: disable=dangerous-default-value
def add(self, k, v, names = names, value = values):
def add(self, k, v, names=names, value=values):
"""helper for creating the enum members"""
if v is None:
# sugar: take the next free number if value was None
@ -237,7 +273,7 @@ class Enum(dict):
if v in names:
v = self[v].value
while v in values:
v +=1
v += 1
# check that the value is an int
_v = int(v)

View File

@ -21,6 +21,7 @@
# *****************************************************************************
"""Define parsing helpers"""
# TODO: remove, as currently not used
import re
import time

View File

@ -440,7 +440,7 @@ class Module(HasAccessibles):
for cb in cblist:
try:
cb(arg)
except Exception as e:
except Exception:
# print(formatExtendedTraceback())
pass

View File

@ -167,8 +167,8 @@ class Poller(PollerBase):
continue # only one poller per handler
handlers.add(pobj.handler)
# placeholders 0 are used for due, lastdue and idx
self.queues[polltype].append((0, 0,
(0, module, pobj, pname, factors[polltype])))
self.queues[polltype].append(
(0, 0, (0, module, pobj, pname, factors[polltype])))
def poll_next(self, polltype):
"""try to poll next item

View File

@ -25,6 +25,7 @@ import json
EOL = b'\n'
def encode_msg_frame(action, specifier=None, data=None):
""" encode a msg_triple into an msg_frame, ready to be sent

View File

@ -80,7 +80,6 @@ REQUEST2REPLY = {
}
HelpMessage = """Try one of the following:
'%s' to query protocol version
'%s' to read the description

View File

@ -88,10 +88,10 @@ class ProxyModule(HasIodev, Module):
dt.compatible(pobj.datatype)
except Exception:
self.log.warning('remote parameter %s:%s is not fully compatible: %r != %r'
% (self.module, pname, pobj.datatype, dt))
% (self.module, pname, pobj.datatype, dt))
except Exception:
self.log.warning('remote parameter %s:%s has an incompatible datatype: %r != %r'
% (self.module, pname, pobj.datatype, dt))
% (self.module, pname, pobj.datatype, dt))
while cmds:
cname, cobj = cmds.popitem()
props = remotecmds.get(cname)

View File

@ -47,7 +47,7 @@ def get_git_version(abbrev=4, cwd=None):
# mangle version to comply with pep440
if version.count('-'):
version, patchcount, githash = version.split('-')
version += '.post%s+%s' %(patchcount, githash)
version += '.post%s+%s' % (patchcount, githash)
return version
except Exception:
return None