GUI: add logging infra, switch to argparse

First part for #4662

Change-Id: I75877337e8ea35d4c4555471ee4518c942dac88a
This commit is contained in:
Alexander Zaft
2022-12-07 17:42:08 +01:00
parent 929e41ffff
commit c522c41654
2 changed files with 38 additions and 24 deletions

View File

@ -26,42 +26,49 @@
from __future__ import print_function from __future__ import print_function
import sys import sys
import argparse
from os import path from os import path
# Add import path for inplace usage # Add import path for inplace usage
sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..'))) sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..')))
import mlzlog import logging
from mlzlog import ColoredConsoleHandler
from frappy.gui.qt import QApplication from frappy.gui.qt import QApplication
from frappy.gui.mainwindow import MainWindow from frappy.gui.mainwindow import MainWindow
def parseArgv(argv):
parser = argparse.ArgumentParser()
loggroup = parser.add_mutually_exclusive_group()
loggroup.add_argument('-d', '--debug',
help='Enable debug output',
action='store_true', default=False)
loggroup.add_argument('-q', '--quiet',
help='Supress everything but errors',
action='store_true', default=False)
parser.add_argument('node',
help='Nodes the Gui should connect to.\n', metavar='host[:port]',
nargs='*', type=str, default=['localhost:10767'])
return parser.parse_args(argv)
def main(argv=None): def main(argv=None):
if argv is None: if argv is None:
argv = sys.argv argv = sys.argv
if '-h' in argv or '--help' in argv: args = parseArgv(argv[1:])
print("Usage: frappy-gui [-d] [-h] [host:[port]]")
print()
print("Option GNU long option Meaning")
print("-h --help Show this message")
print("-d --debug Enable debug output")
print()
print("if not given, host defaults to 'localhost' and port to 10767")
sys.exit(0)
if '-d' in argv or '--debug' in argv: loglevel = logging.DEBUG if args.debug else (logging.ERROR if args.quiet else logging.INFO)
mlzlog.initLogging('gui', 'debug') logger = logging.getLogger('gui')
else: logger.setLevel(logging.DEBUG)
mlzlog.initLogging('gui', 'info') console = ColoredConsoleHandler()
console.setLevel(loglevel)
logger.addHandler(console)
app = QApplication(argv) app = QApplication(argv)
hosts = [host for host in argv[1:] if not host.startswith('-')] win = MainWindow(args.node, logger)
if not hosts:
hosts = ['localhost:10767']
win = MainWindow(hosts)
win.show() win.show()
return app.exec_() return app.exec_()

View File

@ -43,18 +43,21 @@ class QSECNode(QObject):
unhandledMsg = pyqtSignal(str) # message unhandledMsg = pyqtSignal(str) # message
logEntry = pyqtSignal(str) logEntry = pyqtSignal(str)
def __init__(self, uri, parent=None): def __init__(self, uri, parent_logger, parent=None):
super().__init__(parent) super().__init__(parent)
self.conn = conn = frappy.client.SecopClient(uri) self.log = parent_logger.getChild(uri)
self.conn = conn = frappy.client.SecopClient(uri, self.log)
conn.validate_data = True conn.validate_data = True
self.log = conn.log
self.contactPoint = conn.uri self.contactPoint = conn.uri
conn.connect() conn.connect()
self.equipmentId = conn.properties['equipment_id'] self.equipmentId = conn.properties['equipment_id']
self.log.info('Switching to logger %s', self.equipmentId)
self.log.name = '.'.join((parent_logger.name, self.equipmentId))
self.nodename = '%s (%s)' % (self.equipmentId, conn.uri) self.nodename = '%s (%s)' % (self.equipmentId, conn.uri)
self.modules = conn.modules self.modules = conn.modules
self.properties = self.conn.properties self.properties = self.conn.properties
self.protocolVersion = conn.secop_version self.protocolVersion = conn.secop_version
self.log.debug('SECoP Version: %s', conn.secop_version)
conn.register_callback(None, self.updateEvent, self.nodeStateChange, self.unhandledMessage) conn.register_callback(None, self.updateEvent, self.nodeStateChange, self.unhandledMessage)
# provide methods from old baseclient for making other gui code work # provide methods from old baseclient for making other gui code work
@ -112,7 +115,7 @@ class QSECNode(QObject):
class MainWindow(QMainWindow): class MainWindow(QMainWindow):
def __init__(self, hosts, parent=None): def __init__(self, hosts, logger, parent=None):
super().__init__(parent) super().__init__(parent)
loadUi(self, 'mainwindow.ui') loadUi(self, 'mainwindow.ui')
@ -130,13 +133,17 @@ class MainWindow(QMainWindow):
self._topItems = {} self._topItems = {}
self._currentWidget = self.splitter.widget(1).layout().takeAt(0) self._currentWidget = self.splitter.widget(1).layout().takeAt(0)
self.log = logger
# add localhost (if available) and SEC nodes given as arguments # add localhost (if available) and SEC nodes given as arguments
for host in hosts: for host in hosts:
try: try:
self.log.info('Trying to connect to %s', host)
self._addNode(host) self._addNode(host)
except Exception as e: except Exception as e:
# TODO: make this nicer than dumping to console
print(formatExtendedTraceback()) print(formatExtendedTraceback())
print('error in addNode: %r' % e) self.log.error('error in addNode: %r', e)
@pyqtSlot() @pyqtSlot()
def on_actionAdd_SEC_node_triggered(self): def on_actionAdd_SEC_node_triggered(self):
@ -187,7 +194,7 @@ class MainWindow(QMainWindow):
def _addNode(self, host): def _addNode(self, host):
# create client # create client
node = QSECNode(host, parent=self) node = QSECNode(host, self.log, parent=self)
nodename = node.nodename nodename = node.nodename
self._nodes[nodename] = node self._nodes[nodename] = node