Configtool: make Settings the "global" container.

Instead of passing myriad variables around in arguments to
classes and functions, put the global settings like "verbose" and
"cmdFolder" in the Settings object and pass that in to the top.
This commit is contained in:
Phil Hord 2016-04-21 13:23:16 -04:00 committed by Markus Hitter
parent eafb8e0bfb
commit 2c5a36b14e
7 changed files with 99 additions and 57 deletions

View File

@ -24,9 +24,23 @@ import getopt
import os.path import os.path
import inspect import inspect
from configtool.settings import Settings
from configtool.gui import StartGui from configtool.gui import StartGui
cmdFolder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(
inspect.currentframe()))[0]))
verbose = 0
settings = None
def getSettings(arg = None):
global settings
if arg or not settings:
settings = Settings(None, cmdFolder, arg)
settings.verbose = verbose
return settings
def cmdLoad(arg): def cmdLoad(arg):
print("Want to load %s, but don't know how.\n" % arg) print("Want to load %s, but don't know how.\n" % arg)
@ -38,6 +52,9 @@ Following options are available for command line automation:
-h, --help Show this help text. -h, --help Show this help text.
-v, --verbose Be more verbose. Can be applied multiple times
to get even more output.
-l <file>, --load=<file> Load a specific printer config, board config -l <file>, --load=<file> Load a specific printer config, board config
or .ini file. or .ini file.
""" % sys.argv[0]) """ % sys.argv[0])
@ -47,8 +64,10 @@ def CommandLine(argv):
result in sys.exit() (i.e. they do not return from this function). Other result in sys.exit() (i.e. they do not return from this function). Other
options like --debug will return to allow the gui to launch. options like --debug will return to allow the gui to launch.
""" """
global settings, verbose
try: try:
opts, args = getopt.getopt(argv, "hl:", ["help", "load="]) opts, args = getopt.getopt(argv, "hvl:", ["help", "verbose", "load="])
except getopt.GetoptError as err: except getopt.GetoptError as err:
print(err) print(err)
print("Use '%s --help' to get help with command line options." % print("Use '%s --help' to get help with command line options." %
@ -63,12 +82,13 @@ def CommandLine(argv):
# Now parse other options. # Now parse other options.
for opt, arg in opts: for opt, arg in opts:
if opt in ("-l", "--load"): if opt in ("-v", "--verbose"):
verbose += 1
getSettings()
elif opt in ("-l", "--load"):
cmdLoad(arg) cmdLoad(arg)
if __name__ == '__main__': if __name__ == '__main__':
CommandLine(sys.argv[1:]) CommandLine(sys.argv[1:])
StartGui(getSettings())
cmdFolder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(
inspect.currentframe()))[0]))
StartGui(cmdFolder)

View File

@ -15,8 +15,10 @@ from configtool.data import (defineValueFormat,
reTempTable4, reTempTable7) reTempTable4, reTempTable7)
class Board: class Board:
def __init__(self): def __init__(self, settings):
self.settings = settings
self.configFile = None self.configFile = None
self.cfgDir = os.path.join(self.settings.folder, "configtool")
self.cfgValues = {} self.cfgValues = {}
self.heaters = [] self.heaters = []
@ -41,8 +43,8 @@ class Board:
def getFileName(self): def getFileName(self):
return self.configFile return self.configFile
def loadConfigFile(self, cfgDir, fn): def loadConfigFile(self, fn):
cfgFn = os.path.join(cfgDir, "board.generic.h") cfgFn = os.path.join(self.cfgDir, "board.generic.h")
try: try:
self.cfgBuffer = list(open(cfgFn)) self.cfgBuffer = list(open(cfgFn))
except: except:
@ -171,17 +173,18 @@ class Board:
continue continue
# Parsing done. All parsed stuff is now in these arrays and dicts. # Parsing done. All parsed stuff is now in these arrays and dicts.
# Uncomment for debugging. if self.settings.verbose >= 2:
#print self.sensors print self.sensors
#print self.heaters print self.heaters
#print self.candHeatPins print self.candHeatPins
#print self.candThermPins print self.candThermPins
#print self.candProcessors print self.candProcessors
#print self.candClocks print self.candClocks
#print self.tempTables print self.tempTables
#print self.cfgValues # #defines with a value and booleans. print self.cfgValues # #defines with a value.
#print self.cfgNames # Names found in the generic file. print self.cfgNames # Names found in the generic file.
#print self.helpText if self.settings.verbose >= 3:
print self.helpText
for k in range(len(self.sensors)): for k in range(len(self.sensors)):
tn = self.sensors[k][0].upper() tn = self.sensors[k][0].upper()
@ -324,6 +327,11 @@ class Board:
return None return None
def saveConfigFile(self, path, values): def saveConfigFile(self, path, values):
if self.settings.verbose >= 1:
print("Saving board: %s." % path)
if self.settings.verbose >= 2:
print values
fp = file(path, 'w') fp = file(path, 'w')
self.configFile = path self.configFile = path

View File

@ -36,10 +36,9 @@ class BoardPanel(wx.Panel):
self.settings = settings self.settings = settings
self.board = Board() self.board = Board(self.settings)
self.dir = os.path.join(self.settings.folder, "config") self.dir = os.path.join(self.settings.folder, "config")
self.cfgDir = os.path.join(self.settings.folder, "configtool")
self.SetBackgroundColour(self.deco.getBackgroundColour()) self.SetBackgroundColour(self.deco.getBackgroundColour())
self.Bind(wx.EVT_PAINT, self.deco.onPaintBackground) self.Bind(wx.EVT_PAINT, self.deco.onPaintBackground)
@ -187,7 +186,7 @@ class BoardPanel(wx.Panel):
return return
def loadConfigFile(self, fn): def loadConfigFile(self, fn):
ok, file = self.board.loadConfigFile(self.cfgDir, fn) ok, file = self.board.loadConfigFile(fn)
if not ok: if not ok:
return ok, file return ok, file

View File

@ -36,10 +36,8 @@ ID_REPORT = 1051
ID_ABOUT = 1052 ID_ABOUT = 1052
cmdFolder = "placeholder"
class ConfigFrame(wx.Frame): class ConfigFrame(wx.Frame):
def __init__(self): def __init__(self, settings):
wx.Frame.__init__(self, None, -1, "Teacup Configtool", size = (880, 550)) wx.Frame.__init__(self, None, -1, "Teacup Configtool", size = (880, 550))
self.Bind(wx.EVT_CLOSE, self.onClose) self.Bind(wx.EVT_CLOSE, self.onClose)
self.Bind(wx.EVT_SIZE, self.onResize) self.Bind(wx.EVT_SIZE, self.onResize)
@ -50,10 +48,10 @@ class ConfigFrame(wx.Frame):
panel.SetBackgroundColour(self.deco.getBackgroundColour()) panel.SetBackgroundColour(self.deco.getBackgroundColour())
panel.Bind(wx.EVT_PAINT, self.deco.onPaintBackground) panel.Bind(wx.EVT_PAINT, self.deco.onPaintBackground)
self.settings = Settings(self, cmdFolder) self.settings = settings
self.settings.app = self
self.settings.font = wx.Font(8, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, self.settings.font = wx.Font(8, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_BOLD) wx.FONTWEIGHT_BOLD)
self.settings.folder = cmdFolder
self.heaters = [] self.heaters = []
self.savePrtEna = False self.savePrtEna = False
@ -257,7 +255,7 @@ class ConfigFrame(wx.Frame):
return rc return rc
def checkEnableLoadConfig(self): def checkEnableLoadConfig(self):
fn = os.path.join(cmdFolder, "config.h") fn = os.path.join(self.settings.folder, "config.h")
if os.path.isfile(fn): if os.path.isfile(fn):
self.fileMenu.Enable(ID_LOAD_CONFIG, True) self.fileMenu.Enable(ID_LOAD_CONFIG, True)
self.buildMenu.Enable(ID_BUILD, True) self.buildMenu.Enable(ID_BUILD, True)
@ -268,7 +266,7 @@ class ConfigFrame(wx.Frame):
return False return False
def checkEnableUpload(self): def checkEnableUpload(self):
fn = os.path.join(cmdFolder, "teacup.hex") fn = os.path.join(self.settings.folder, "teacup.hex")
if os.path.isfile(fn): if os.path.isfile(fn):
self.buildMenu.Enable(ID_UPLOAD, True) self.buildMenu.Enable(ID_UPLOAD, True)
else: else:
@ -334,7 +332,7 @@ class ConfigFrame(wx.Frame):
def getConfigFileNames(self, fn): def getConfigFileNames(self, fn):
pfile = None pfile = None
bfile = None bfile = None
path = os.path.join(cmdFolder, fn) path = os.path.join(self.settings.folder, fn)
try: try:
cfgBuffer = list(open(path)) cfgBuffer = list(open(path))
except: except:
@ -355,14 +353,14 @@ class ConfigFrame(wx.Frame):
"Ignoring %s." % ln, "Config error", "Ignoring %s." % ln, "Config error",
wx.OK + wx.ICON_WARNING) wx.OK + wx.ICON_WARNING)
else: else:
pfile = os.path.join(cmdFolder, t[0]) pfile = os.path.join(self.settings.folder, t[0])
elif "board." in t[0]: elif "board." in t[0]:
if bfile: if bfile:
self.message("Multiple board file include statements.\n" self.message("Multiple board file include statements.\n"
"Ignoring %s." % ln, "Config error", "Ignoring %s." % ln, "Config error",
wx.OK + wx.ICON_WARNING) wx.OK + wx.ICON_WARNING)
else: else:
bfile = os.path.join(cmdFolder, t[0]) bfile = os.path.join(self.settings.folder, t[0])
else: else:
self.message("Unable to parse include statement:\n%s" % ln, self.message("Unable to parse include statement:\n%s" % ln,
"Config error") "Config error")
@ -370,7 +368,7 @@ class ConfigFrame(wx.Frame):
return pfile, bfile return pfile, bfile
def onSaveConfig(self, evt): def onSaveConfig(self, evt):
fn = os.path.join(cmdFolder, "config.h") fn = os.path.join(self.settings.folder, "config.h")
try: try:
fp = open(fn, 'w') fp = open(fn, 'w')
except: except:
@ -389,7 +387,7 @@ class ConfigFrame(wx.Frame):
if not self.pgPrinter.saveConfigFile(pfn): if not self.pgPrinter.saveConfigFile(pfn):
return False return False
prefix = cmdFolder + os.path.sep prefix = self.settings.folder + os.path.sep
lpfx = len(prefix) lpfx = len(prefix)
if bfn.startswith(prefix): if bfn.startswith(prefix):
@ -612,11 +610,8 @@ class ConfigFrame(wx.Frame):
dlg.Destroy() dlg.Destroy()
def StartGui(teacupFolder): def StartGui(settings):
global cmdFolder
cmdFolder = teacupFolder
app = wx.App(False) app = wx.App(False)
frame = ConfigFrame() frame = ConfigFrame(settings)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()

View File

@ -9,10 +9,12 @@ from configtool.data import (defineValueFormat, defineBoolFormat,
reDefQSm2, reDefBool, reDefBoolBL) reDefQSm2, reDefBool, reDefBoolBL)
class Printer: class Printer:
def __init__(self): def __init__(self, settings):
self.configFile = None self.configFile = None
self.cfgValues = {} self.cfgValues = {}
self.settings = settings
self.cfgDir = os.path.join(self.settings.folder, "configtool")
def hasData(self): def hasData(self):
return (self.configFile != None) return (self.configFile != None)
@ -20,8 +22,8 @@ class Printer:
def getFileName(self): def getFileName(self):
return self.configFile return self.configFile
def loadConfigFile(self, cfgDir, fn): def loadConfigFile(self, fn):
cfgFn = os.path.join(cfgDir, "printer.generic.h") cfgFn = os.path.join(self.cfgDir, "printer.generic.h")
try: try:
self.cfgBuffer = list(open(cfgFn)) self.cfgBuffer = list(open(cfgFn))
except: except:
@ -115,10 +117,11 @@ class Printer:
self.parseDefineValue(ln) self.parseDefineValue(ln)
# Parsing done. All parsed stuff is now in these array and dicts. # Parsing done. All parsed stuff is now in these array and dicts.
# Uncomment for debugging. if self.settings.verbose >= 2:
#print self.cfgValues # #defines with a value and booleans. print self.cfgValues # #defines with a value.
#print self.cfgNames # Names found in the generic file. print self.cfgNames # Names found in the generic file.
#print self.helpText if self.settings.verbose >= 3:
print self.helpText
return True, None return True, None
@ -176,6 +179,11 @@ class Printer:
return False return False
def saveConfigFile(self, path, values): def saveConfigFile(self, path, values):
if self.settings.verbose >= 1:
print("Saving printer: %s." % path)
if self.settings.verbose >= 2:
print values
fp = file(path, 'w') fp = file(path, 'w')
self.configFile = path self.configFile = path

View File

@ -26,10 +26,9 @@ class PrinterPanel(wx.Panel):
self.settings = settings self.settings = settings
self.printer = Printer() self.printer = Printer(self.settings)
self.dir = os.path.join(self.settings.folder, "config") self.dir = os.path.join(self.settings.folder, "config")
self.cfgDir = os.path.join(self.settings.folder, "configtool")
self.SetBackgroundColour(self.deco.getBackgroundColour()) self.SetBackgroundColour(self.deco.getBackgroundColour())
self.Bind(wx.EVT_PAINT, self.deco.onPaintBackground) self.Bind(wx.EVT_PAINT, self.deco.onPaintBackground)
@ -170,7 +169,7 @@ class PrinterPanel(wx.Panel):
return return
def loadConfigFile(self, fn): def loadConfigFile(self, fn):
ok, file = self.printer.loadConfigFile(self.cfgDir, fn) ok, file = self.printer.loadConfigFile(fn)
if not ok: if not ok:
return ok, file return ok, file

View File

@ -23,9 +23,9 @@ R1 = 12
class Settings: class Settings:
def __init__(self, app, folder): def __init__(self, app, folder, ini=None):
self.app = app self.app = app
self.cmdfolder = folder self.folder = folder
self.inifile = os.path.join(folder, INIFILE) self.inifile = os.path.join(folder, INIFILE)
self.section = "configtool" self.section = "configtool"
@ -44,14 +44,24 @@ class Settings:
self.maxAdc = 1023 self.maxAdc = 1023
self.minAdc = 1 self.minAdc = 1
# Runtime settings
self.verbose = 0
self.cfg = ConfigParser.ConfigParser() self.cfg = ConfigParser.ConfigParser()
self.cfg.optionxform = str self.cfg.optionxform = str
if not self.cfg.read(self.inifile): self.loaded = self.readConfig(ini)
if not self.cfg.read(os.path.join(folder, DEFAULT_INIFILE)):
print ("Neither of settings files %s or %s exist. Using default values." def readConfig(self, ini):
% (INIFILE, DEFAULT_INIFILE)) if ini:
return if not self.cfg.read(ini):
return False
else:
if not self.cfg.read(self.inifile):
if not self.cfg.read(os.path.join(self.folder, DEFAULT_INIFILE)):
print ("Neither of settings files %s or %s exist. Using default values."
% (INIFILE, DEFAULT_INIFILE))
return False
if self.cfg.has_section(self.section): if self.cfg.has_section(self.section):
for opt, value in self.cfg.items(self.section): for opt, value in self.cfg.items(self.section):
@ -86,6 +96,9 @@ class Settings:
print "Unknown %s option: %s - ignoring." % (self.section, opt) print "Unknown %s option: %s - ignoring." % (self.section, opt)
else: else:
print "Missing %s section - assuming defaults." % self.section print "Missing %s section - assuming defaults." % self.section
return False
return True
def saveSettings(self): def saveSettings(self):
self.section = "configtool" self.section = "configtool"