summaryrefslogtreecommitdiffstats
path: root/toprammer-unitest
blob: f5cc11695e9f11f542349b485aea4e060c374384 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
#!/usr/bin/env python
"""
#    TOP2049 Open Source programming suite
#
#    Universal Device Tester
#
#    Copyright (c) 2010 Michael Buesch <mb@bu3sch.de>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""

from libtoprammer.toprammer_main import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ConfigParser

def stringRemoveChars(string, chars):
	ret = ""
	for c in string:
		if c not in chars:
			ret += c
	return ret

class ZifWidget(QGroupBox):
	def __init__(self, parent, top):
		QGroupBox.__init__(self, parent.tr("ZIF socket"), parent)
		self.top = top
		self.setLayout(QGridLayout())

		self.nrPins = top.vccx.getNrOfPins()
		assert(self.nrPins == top.vpp.getNrOfPins())
		assert(self.nrPins == top.gnd.getNrOfPins())
		assert(self.nrPins % 2 == 0)

		self.blockedPins = []
		self.ignoreOutChange = False

		label = QLabel(self)
		label.setFrameStyle(QFrame.Panel | QFrame.Sunken)
		label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
		self.layout().addWidget(label, 0, 2, self.nrPins // 2, 1)

		self.pins = [ None ] * self.nrPins
		self.pinOuten = [ None ] * self.nrPins
		for i in range(0, self.nrPins // 2):
			left = i + 1
			right = self.nrPins - i
			self.pins[left - 1] = QCheckBox(str(left), self)
			self.connect(self.pins[left - 1], SIGNAL("stateChanged(int)"),
				     self.__outChanged)
			self.pinOuten[left - 1] = QCheckBox("out", self)
			self.connect(self.pinOuten[left - 1], SIGNAL("stateChanged(int)"),
				     self.__outEnChanged)
			self.layout().addWidget(self.pinOuten[left - 1], left - 1, 0)
			self.layout().addWidget(self.pins[left - 1], left - 1, 1)
			self.pins[right - 1] = QCheckBox(str(right), self)
			self.connect(self.pins[right - 1], SIGNAL("stateChanged(int)"),
				     self.__outChanged)
			self.pinOuten[right - 1] = QCheckBox("out", self)
			self.connect(self.pinOuten[right - 1], SIGNAL("stateChanged(int)"),
				     self.__outEnChanged)
			self.layout().addWidget(self.pins[right - 1], self.nrPins - right, 3)
			self.layout().addWidget(self.pinOuten[right - 1], self.nrPins - right, 4)
		self.__outEnChanged()
		self.__outChanged()

	def readInputs(self):
		try:
			inputMask = self.top.chip.getInputs()
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP communication failed"),
				self.tr("Failed to fetch input states:\n") +\
				str(e))
			return False
		for i in range(0, self.nrPins):
			if self.pinOuten[i].checkState() != Qt.Checked and\
			   i + 1 not in self.blockedPins:
				state = Qt.Unchecked
				if inputMask & (1 << i):
					state = Qt.Checked
				self.ignoreOutChange = True
				self.pins[i].setCheckState(state)
				self.ignoreOutChange = False
		return True

	def __updateInOutStates(self):
		for i in range(0, self.nrPins):
			if i + 1 in self.blockedPins:
				self.pins[i].setEnabled(False)
				self.pins[i].setCheckState(Qt.Unchecked)
				self.pinOuten[i].setEnabled(False)
				self.pinOuten[i].setCheckState(Qt.Unchecked)
			else:
				self.pinOuten[i].setEnabled(True)
				if self.pinOuten[i].checkState() == Qt.Checked:
					self.pins[i].setEnabled(True)
				else:
					self.pins[i].setEnabled(False)

	def __outEnChanged(self):
		self.__updateInOutStates()
		outEnMask = self.getOutEnMask()
		try:
			self.top.chip.setOutputEnableMask(outEnMask)
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP communication failed"),
				self.tr("Failed to set output-enable states:\n") +\
				str(e))
			return
		self.readInputs()

	def __outChanged(self):
		if self.ignoreOutChange:
			return
		outMask = self.getOutMask()
		try:
			self.top.chip.setOutputs(outMask)
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP communication failed"),
				self.tr("Failed to set output states:\n") +\
				str(e))
			return
		self.readInputs()

	def setBlockedPins(self, blockedPins):
		self.blockedPins = blockedPins
		self.__updateInOutStates()
		self.readInputs()

	def getOutEnMask(self):
		outEnMask = 0
		for i in range(0, self.nrPins):
			if self.pinOuten[i].checkState() == Qt.Checked:
				outEnMask |= (1 << i)
		return outEnMask

	def setOutEnMask(self, mask):
		for i in range(0, self.nrPins):
			if mask & (1 << i):
				self.pinOuten[i].setCheckState(Qt.Checked)
			else:
				self.pinOuten[i].setCheckState(Qt.Unchecked)
			mask &= ~(1 << i)
		if mask:
			raise TOPException("ZIF out-en mask has too many bits set")

	def getOutMask(self):
		outMask = 0
		for i in range(0, self.nrPins):
			if self.pins[i].checkState() == Qt.Checked:
				outMask |= (1 << i)
		return outMask

	def setOutMask(self, mask):
		for i in range(0, self.nrPins):
			if mask & (1 << i):
				self.pins[i].setCheckState(Qt.Checked)
			else:
				self.pins[i].setCheckState(Qt.Unchecked)
			mask &= ~(1 << i)
		if mask:
			raise TOPException("ZIF out mask has too many bits set")

class MainWidget(QWidget):
	def __init__(self, mainwnd):
		QWidget.__init__(self, mainwnd)
		self.mainwnd = mainwnd
		self.setLayout(QGridLayout())
		try:
			self.top = TOP(verbose=2)
			self.top.initializeChip("unitest")

			self.zifWidget = ZifWidget(self, self.top)
			self.layout().addWidget(self.zifWidget, 0, 0, 10, 1)
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP init failed"),
				self.tr("Initialization of TOP device failed:\n") +\
				str(e))
			raise

		group = QGroupBox(self.tr("GND layout"), self)
		group.setLayout(QGridLayout())
		self.gndLayout = QComboBox(self)
		self.gndLayout.addItem(self.tr("Not connected"), QVariant(0))
		for (layId, layMask) in self.top.gnd.supportedLayouts():
			if not layMask:
				continue
			descr = self.tr("GND on pin ")
			for i in range(0, self.top.gnd.getNrOfPins()):
				if layMask & (1 << i):
					descr += str(i + 1) + " "
			self.gndLayout.addItem(descr, QVariant(layId))
		group.layout().addWidget(self.gndLayout, 0, 0)
		self.layout().addWidget(group, 0, 1)

		group = QGroupBox(self.tr("VCCX layout"), self)
		group.setLayout(QGridLayout())
		self.vccxVoltage = QDoubleSpinBox(self)
		self.vccxVoltage.setSuffix(self.tr(" V"))
		self.vccxVoltage.setMinimum(self.top.vccx.minVoltage())
		self.vccxVoltage.setMaximum(self.top.vccx.maxVoltage())
		self.vccxVoltage.setSingleStep(0.1)
		group.layout().addWidget(self.vccxVoltage, 0, 0)
		self.vccxLayout = QComboBox(self)
		self.vccxLayout.addItem(self.tr("Not connected"), QVariant(0))
		for (layId, layMask) in self.top.vccx.supportedLayouts():
			if not layMask:
				continue
			descr = self.tr("VCCX on pin ")
			for i in range(0, self.top.vccx.getNrOfPins()):
				if layMask & (1 << i):
					descr += str(i + 1) + " "
			self.vccxLayout.addItem(descr, QVariant(layId))
		group.layout().addWidget(self.vccxLayout, 1, 0)
		self.layout().addWidget(group, 1, 1)

		group = QGroupBox(self.tr("Input polling"), self)
		group.setLayout(QGridLayout())
		self.inputPollEn = QCheckBox(self.tr("Input polling enabled"), self)
		self.inputPollEn.setCheckState(Qt.Checked)
		group.layout().addWidget(self.inputPollEn, 0, 0)
		self.inputPollInterval = QDoubleSpinBox(self)
		self.inputPollInterval.setPrefix(self.tr("Interval "))
		self.inputPollInterval.setSuffix(self.tr(" seconds"))
		self.inputPollInterval.setMinimum(0.25)
		self.inputPollInterval.setSingleStep(0.25)
		self.inputPollInterval.setValue(1.0)
		group.layout().addWidget(self.inputPollInterval, 1, 0)
		self.layout().addWidget(group, 2, 1)

		group = QGroupBox(self.tr("Oscillator"), self)
		group.setLayout(QGridLayout())
		self.oscPin = QComboBox(self)
		self.oscPin.addItem("Disabled", QVariant(0))
		for i in range(0, self.zifWidget.nrPins):
			self.oscPin.addItem("On pin %d" % (i + 1), QVariant(1 << i))
		group.layout().addWidget(self.oscPin, 0, 0)
		self.oscDiv = QSpinBox(self)
		self.oscDiv.setPrefix("Divider ")
		self.oscDiv.setSingleStep(1)
		self.oscDiv.setMinimum(1)
		self.oscDiv.setMaximum(24000000)
		self.oscDiv.setValue(24)
		group.layout().addWidget(self.oscDiv, 1, 0)
		self.oscFreq = QLabel(self)
		group.layout().addWidget(self.oscFreq, 2, 0)
		self.layout().addWidget(group, 3, 1)

		group = QGroupBox(self.tr("VPP layout"), self)
		group.setLayout(QGridLayout())
		self.vppVoltage = QDoubleSpinBox(self)
		self.vppVoltage.setSuffix(self.tr(" V"))
		self.vppVoltage.setMinimum(self.top.vpp.minVoltage())
		self.vppVoltage.setMaximum(self.top.vpp.maxVoltage())
		self.vppVoltage.setSingleStep(0.1)
		group.layout().addWidget(self.vppVoltage, 0, 0, 1, 2)
		self.vppLayouts = {}
		xOffset = 0
		yOffset = 0
		for (layId, layMask) in self.top.vpp.supportedLayouts():
			if not layMask:
				continue
			for i in range(0, self.top.vpp.getNrOfPins()):
				if layMask & (1 << i):
					descr = str(i + 1) + " "
			self.vppLayouts[layId] = QCheckBox(descr, self)
			self.connect(self.vppLayouts[layId], SIGNAL("stateChanged(int)"),
				     self.vppLayoutChanged)
			group.layout().addWidget(self.vppLayouts[layId],
					yOffset + 1, xOffset)
			yOffset += 1
			if yOffset == len(self.top.vpp.supportedLayouts()) // 2:
				yOffset = 0
				xOffset += 1
		self.layout().addWidget(group, 0, 2, 8, 1)

		self.inputPollTimer = QTimer()
		self.connect(self.inputPollTimer, SIGNAL("timeout()"),
			     self.doInputPollTimer)

		self.connect(self.inputPollEn, SIGNAL("stateChanged(int)"),
			     self.inputPollChanged)
		self.connect(self.inputPollInterval, SIGNAL("valueChanged(double)"),
			     self.inputPollChanged)
		self.connect(self.gndLayout, SIGNAL("currentIndexChanged(int)"),
			     self.gndLayoutChanged)
		self.connect(self.vccxVoltage, SIGNAL("valueChanged(double)"),
			     self.vccxLayoutChanged)
		self.connect(self.vccxLayout, SIGNAL("currentIndexChanged(int)"),
			     self.vccxLayoutChanged)
		self.connect(self.vppVoltage, SIGNAL("valueChanged(double)"),
			     self.vppLayoutChanged)
		self.connect(self.oscPin, SIGNAL("currentIndexChanged(int)"),
			     self.oscChanged)
		self.connect(self.oscDiv, SIGNAL("valueChanged(int)"),
			     self.oscChanged)
		self.gndLayoutChanged()
		self.vccxLayoutChanged()
		self.inputPollChanged()
		self.oscChanged()

	def shutdown(self):
		self.inputPollTimer.stop()
		try:
			self.top.shutdownChip()
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP shutdown failed"),
				self.tr("Failed to shutdown TOP device:\n") +\
				str(e))

	def updateZifCheckboxes(self):
		blockedPins = []
		# GND
		idx = self.gndLayout.currentIndex()
		lay = self.gndLayout.itemData(idx).toInt()[0]
		blockedPins.extend(self.top.gnd.ID2pinlist(lay))
		# VCCX
		idx = self.vccxLayout.currentIndex()
		lay = self.vccxLayout.itemData(idx).toInt()[0]
		blockedPins.extend(self.top.vccx.ID2pinlist(lay))
		# VPP
		for key in self.vppLayouts.keys():
			if self.vppLayouts[key].checkState() == Qt.Checked:
				blockedPins.extend(self.top.vpp.ID2pinlist(key))
		# OSC
		idx = self.oscPin.currentIndex()
		mask = self.oscPin.itemData(idx).toInt()[0]
		for i in range(0, self.zifWidget.nrPins):
			if mask & (1 << i):
				blockedPins.append(i + 1)
		self.zifWidget.setBlockedPins(blockedPins)

	def gndLayoutChanged(self, unused=None):
		idx = self.gndLayout.currentIndex()
		selLayout = self.gndLayout.itemData(idx).toInt()[0]
		try:
			self.top.chip.setGND(selLayout)
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP communication failed"),
				self.tr("Failed to set GND layout:\n") +\
				str(e))
			return
		self.updateZifCheckboxes()

	def vccxLayoutChanged(self, unused=None):
		selVoltage = self.vccxVoltage.value()
		idx = self.vccxLayout.currentIndex()
		selLayout = self.vccxLayout.itemData(idx).toInt()[0]
		try:
			self.top.chip.setVCCX(selVoltage, selLayout)
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP communication failed"),
				self.tr("Failed to set VCCX layout:\n") +\
				str(e))
			return
		self.updateZifCheckboxes()

	def vppLayoutChanged(self, unused=None):
		selVoltage = self.vppVoltage.value()
		selLayouts = []
		for key in self.vppLayouts.keys():
			if self.vppLayouts[key].checkState() == Qt.Checked:
				selLayouts.append(key)
		try:
			self.top.chip.setVPP(selVoltage, selLayouts)
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP communication failed"),
				self.tr("Failed to set VPP layout:\n") +\
				str(e))
			return
		self.updateZifCheckboxes()

	def doInputPollTimer(self):
		if not self.zifWidget.readInputs():
			# Whoops, error. Disable input polling
			self.inputPollEn.setCheckState(Qt.Unchecked)
			return False
		return True

	def inputPollChanged(self, unused=None):
		if self.inputPollEn.checkState() == Qt.Checked:
			self.inputPollInterval.setEnabled(True)
			if self.doInputPollTimer():
				inter = int(self.inputPollInterval.value() * 1000)
				self.inputPollTimer.start(inter)
		else:
			self.inputPollInterval.setEnabled(False)
			self.inputPollTimer.stop()

	def oscChanged(self, unused=None):
		try:
			div = self.oscDiv.value()
			self.top.chip.setOscDivider(div)
			idx = self.oscPin.currentIndex()
			mask = self.oscPin.itemData(idx).toInt()[0]
			self.top.chip.setOscMask(mask)
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("TOP communication failed"),
				self.tr("Failed configure oscillator:\n") +\
				str(e))
			return
		self.oscFreq.setText("%.03f Hz" % (24000000.0 / div))
		self.updateZifCheckboxes()

	def loadSettings(self, filename):
		try:
			p = ConfigParser.SafeConfigParser()
			p.read((filename,))

			sect = "TOPRAMMER-UNITEST-SETTINGS"
			if not p.has_section(sect):
				raise TOPException(self.tr("Invalid file format"))
			ver = p.getint(sect, "fileVersion")
			verExpected = 1
			if ver != verExpected:
				raise TOPException(str(self.tr("Unsupported file version (got %d, expected %d)")) %\
					(ver, verExpected))
			pType = p.get(sect, "programmerType")
			pTypeExpected = self.top.topType
			if pType.upper() != pTypeExpected.upper():
				raise TOPException(str(self.tr("Programmer type mismatch (file = %s, connected = %s)")) %\
					(pType, pTypeExpected))

			layout = p.getint(sect, "gndLayout")
			idx = self.gndLayout.findData(QVariant(layout))
			if idx < 0:
				raise TOPException(self.tr("Invalid GND layout"))
			self.gndLayout.setCurrentIndex(idx)

			layout = p.getint(sect, "vccxLayout")
			idx = self.vccxLayout.findData(QVariant(layout))
			if idx < 0:
				raise TOPException(self.tr("Invalid VCCX layout"))
			self.vccxLayout.setCurrentIndex(idx)

			voltage = p.getfloat(sect, "vccxVoltage")
			self.vccxVoltage.setValue(voltage)

			layouts = p.get(sect, "vppLayout").split(",")
			for layId in self.vppLayouts.keys():
				if layId in layouts:
					self.vppLayouts[layId].setCheckState(Qt.Checked)
				else:
					self.vppLayouts[layId].setCheckState(Qt.Unchecked)

			voltage = p.getfloat(sect, "vppVoltage")
			self.vppVoltage.setValue(voltage)

			interval = p.getfloat(sect, "inputPollInterval")
			self.inputPollInterval.setValue(interval)

			enabled = p.getboolean(sect, "inputPollEnabled")
			if enabled:
				self.inputPollEn.setCheckState(Qt.Checked)
			else:
				self.inputPollEn.setCheckState(Qt.Unchecked)

			div = p.getint(sect, "oscillatorDiv")
			self.oscDiv.setValue(div)

			mask = int(p.get(sect, "oscillatorMask"), 16)
			idx = self.oscPin.findData(QVariant(mask))
			if idx < 0:
				raise TOPException("Invalid oscillator mask")
			self.oscPin.setCurrentIndex(idx)

			mask = int(p.get(sect, "zifOutEnMask"), 16)
			self.zifWidget.setOutEnMask(mask)

			mask = int(p.get(sect, "zifOutMask"), 16)
			self.zifWidget.setOutMask(mask)

		except (ConfigParser.Error, TOPException, ValueError), e:
			QMessageBox.critical(self, self.tr("Failed to load settings"),
					     self.tr("Failed to load settings:\n") + str(e))
			return False
		return True

	def saveSettings(self, filename):
		try:
			fd = file(filename, "w+b")

			fd.write("[TOPRAMMER-UNITEST-SETTINGS]\r\n")
			fd.write("fileVersion=%d\r\n" % 1)
			fd.write("programmerType=%s\r\n" % self.top.topType)
			idx = self.gndLayout.currentIndex()
			fd.write("gndLayout=%d\r\n" % self.gndLayout.itemData(idx).toInt()[0])
			idx = self.vccxLayout.currentIndex()
			fd.write("vccxLayout=%d\r\n" % self.vccxLayout.itemData(idx).toInt()[0])
			fd.write("vccxVoltage=%f\r\n" % self.vccxVoltage.value())
			vppLayouts = ""
			for layId in self.vppLayouts.keys():
				if self.vppLayouts[layId].checkState() == Qt.Checked:
					if vppLayouts:
						vppLayouts += ","
					vppLayouts += str(layId)
			if not vppLayouts:
				vppLayouts = "0"
			fd.write("vppLayout=%s\r\n" % vppLayouts)
			fd.write("vppVoltage=%f\r\n" % self.vppVoltage.value())
			fd.write("inputPollEnabled=%d\r\n" % int(self.inputPollEn.checkState() == Qt.Checked))
			fd.write("inputPollInterval=%f\r\n" % self.inputPollInterval.value())
			idx = self.oscPin.currentIndex()
			fd.write("oscillatorMask=%X\r\n" % self.oscPin.itemData(idx).toInt()[0])
			fd.write("oscillatorDiv=%d\r\n" % self.oscDiv.value())
			fd.write("zifOutEnMask=%X\r\n" % self.zifWidget.getOutEnMask())
			fd.write("zifOutMask=%X\r\n" % self.zifWidget.getOutMask())
		except (IOError), e:
			QMessageBox.critical(self, self.tr("Failed to save settings"),
					     self.tr("Failed to write settings to file:\n") +\
					     e.strerror)
			return False
		return True

class MainWindow(QMainWindow):
	def __init__(self, parent=None):
		QMainWindow.__init__(self, parent)

		self.setWindowTitle(self.tr("Toprammer - Universal tester"))
		self.setCentralWidget(MainWidget(self))

		self.setMenuBar(QMenuBar(self))
		menu = QMenu(self.tr("Unitest"), self)
		menu.addAction(self.tr("Load settings..."), self.loadSettings)
		menu.addAction(self.tr("Save settings..."), self.saveSettings)
		menu.addSeparator()
		menu.addAction(self.tr("Raw command..."), self.sendRawCommand)
		menu.addSeparator()
		menu.addAction(self.tr("Exit"), self.close)
		self.menuBar().addMenu(menu)

		self.prevRawCommand = ""

	def closeEvent(self, ev):
		self.centralWidget().shutdown()

	def loadSettings(self):
		fn = QFileDialog.getOpenFileName(self, self.tr("Load settings"), "",
						 self.tr("Toprammer-unitest settings (*.tus)\n" +\
							 "All files (*)"))
		fn = str(fn)
		if fn:
			self.centralWidget().loadSettings(fn)

	def saveSettings(self):
		fn = QFileDialog.getSaveFileName(self, self.tr("Save settings"), "",
						 self.tr("Toprammer-unitest settings (*.tus)"))
		if not fn:
			return
		fn = str(fn)
		if not fn.endswith(".tus"):
			fn += ".tus"
		return self.centralWidget().saveSettings(fn)

	def sendRawCommand(self):
		(string, ok) = QInputDialog.getText(self,
			self.tr("Send raw command"),
			self.tr("Enter raw command to send, in " +\
			"hex format (AABB1122...).\n" +\
			"Warning: The programmer will malfunction on invalid commands."),
			QLineEdit.Normal,
			self.prevRawCommand)
		if not ok:
			return
		string = str(string).strip().upper()
		string = stringRemoveChars(string, " \t\r\n")
		if stringRemoveChars(string, "0123456789ABCDEF"):
			QMessageBox.critical(self, self.tr("Invalid characters"),
				self.tr("Invalid characters in raw command string.\n" +\
				"Only hex characters 0-9,a-f allowed."))
			return
		if len(string) % 2 != 0 or len(string) // 2 > 64:
			QMessageBox.critical(self, self.tr("Invalid length"),
				self.tr("Invalid command length. Length must be even " +\
				"and smaller or equal to 64 bytes."))
			return
		self.prevRawCommand = string
		command = ""
		for i in range(0, len(string), 2):
			byteString = string[i:i+2]
			command += chr(int(byteString, 16))
		assert(len(command) == len(string) // 2)
		try:
			top = self.centralWidget().top
			top.queueCommand(command)
			top.flushCommands()
		except (TOPException), e:
			QMessageBox.critical(self, self.tr("Raw command failed"),
				self.tr("Failed to send raw command:\n") + str(e))
			return
		self.centralWidget().doInputPollTimer()

def main(argv):
	try:
		app = QApplication(argv)
		mainwnd = MainWindow()
		mainwnd.show()
		return app.exec_()
	except (TOPException), e:
		print e
		return 1

if __name__ == "__main__":
	sys.exit(main(sys.argv))
bues.ch cgit interface