toprammer-gui 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890
  1. #!/usr/bin/env python
  2. """
  3. # TOP2049 Open Source programming suite
  4. #
  5. # Qt-based graphical user interface
  6. #
  7. # Copyright (c) 2010-2012 Michael Buesch <m@bues.ch>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. """
  23. from libtoprammer.main import *
  24. from libtoprammer.util import *
  25. import sys
  26. import time
  27. import cgi
  28. import ConfigParser
  29. try:
  30. from PySide.QtCore import *
  31. from PySide.QtGui import *
  32. except (ImportError), e:
  33. print "Failed to import PySide modules: %s" % str(e)
  34. print "Please install PySide. On Debian Linux run: aptitude install python-pyside"
  35. sys.exit(1)
  36. EVENT_HWTHREAD = QEvent.Type(QEvent.User + 0)
  37. def stringRemoveChars(string, chars):
  38. ret = []
  39. for c in string:
  40. if c not in chars:
  41. ret.append(c)
  42. return "".join(ret)
  43. def htmlEscape(plaintext):
  44. return cgi.escape(plaintext)
  45. def getIconPath(name):
  46. return pkg_resources.resource_filename("libtoprammer",
  47. "icons/" + name + ".png")
  48. def getIcon(name):
  49. return QIcon(getIconPath(name))
  50. class Wrapper(object):
  51. def __init__(self, obj):
  52. self.obj = obj
  53. def __eq__(self, other):
  54. return self.obj == other.obj
  55. def __ne__(self, other):
  56. return self.obj != other.obj
  57. class ZifPinButton(QWidget):
  58. TEXT_RIGHT = 0
  59. TEXT_LEFT = 1
  60. stateChanged = Signal(bool)
  61. class Label(QLabel):
  62. clicked = Signal()
  63. def __init__(self, text, parent=None):
  64. QLabel.__init__(self, text, parent)
  65. def mousePressEvent(self, event):
  66. self.clicked.emit()
  67. def __init__(self, text, textPos=TEXT_RIGHT, parent=None):
  68. QWidget.__init__(self, parent)
  69. self.setLayout(QHBoxLayout(self))
  70. self.layout().setContentsMargins(QMargins())
  71. self.checkbox = QCheckBox(self)
  72. self.checkbox.stateChanged.connect(self.__cbStateChanged)
  73. self.label = self.Label(text, self)
  74. self.label.clicked.connect(self.toggle)
  75. if textPos == self.TEXT_RIGHT:
  76. self.label.setAlignment(Qt.AlignLeft)
  77. self.layout().addWidget(self.checkbox)
  78. self.layout().addWidget(self.label)
  79. else:
  80. self.label.setAlignment(Qt.AlignRight)
  81. self.layout().addWidget(self.label)
  82. self.layout().addWidget(self.checkbox)
  83. def __cbStateChanged(self, newState):
  84. self.stateChanged.emit(newState == Qt.Checked)
  85. def state(self):
  86. return self.checkbox.checkState() == Qt.Checked
  87. def setState(self, en):
  88. self.checkbox.setCheckState(Qt.Checked if en else Qt.Unchecked)
  89. def toggle(self):
  90. self.setState(not self.state())
  91. class ZifWidget(QGroupBox):
  92. def __init__(self, unitest, nrZifPins):
  93. QGroupBox.__init__(self, "ZIF socket", unitest)
  94. self.unitest = unitest
  95. self.setLayout(QGridLayout())
  96. self.nrPins = nrZifPins
  97. assert(self.nrPins % 2 == 0)
  98. self.blockedPins = []
  99. self.ignoreOutChange = False
  100. label = QLabel("ZIF\nsocket", self)
  101. label.setFrameStyle(QFrame.Panel | QFrame.Sunken)
  102. label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
  103. label.setMinimumWidth(80)
  104. self.layout().addWidget(label, 0, 2, self.nrPins // 2, 1)
  105. self.pins = [ None ] * self.nrPins
  106. self.pinOuten = [ None ] * self.nrPins
  107. for i in range(0, self.nrPins // 2):
  108. left = i + 1
  109. right = self.nrPins - i
  110. self.pins[left - 1] = ZifPinButton(str(left),
  111. ZifPinButton.TEXT_LEFT, self)
  112. self.pins[left - 1].stateChanged.connect(self.__outChanged)
  113. self.pinOuten[left - 1] = ZifPinButton("out",
  114. ZifPinButton.TEXT_LEFT, self)
  115. self.pinOuten[left - 1].stateChanged.connect(self.__outEnChanged)
  116. self.layout().addWidget(self.pinOuten[left - 1], left - 1, 0)
  117. self.layout().addWidget(self.pins[left - 1], left - 1, 1)
  118. self.pins[right - 1] = ZifPinButton(str(right),
  119. ZifPinButton.TEXT_RIGHT, self)
  120. self.pins[right - 1].stateChanged.connect(self.__outChanged)
  121. self.pinOuten[right - 1] = ZifPinButton("out",
  122. ZifPinButton.TEXT_RIGHT, self)
  123. self.pinOuten[right - 1].stateChanged.connect(self.__outEnChanged)
  124. self.layout().addWidget(self.pins[right - 1], self.nrPins - right, 3)
  125. self.layout().addWidget(self.pinOuten[right - 1], self.nrPins - right, 4)
  126. self.__outEnChanged()
  127. self.__outChanged()
  128. def readInputs(self):
  129. try:
  130. inputMask = self.unitest.queryTop("top.getChip().getInputs()")
  131. except (TOPException), e:
  132. QMessageBox.critical(self, "TOP communication failed",
  133. "Failed to fetch input states:\n" +\
  134. str(e))
  135. return False
  136. for i in range(0, self.nrPins):
  137. if not self.pinOuten[i].state() and\
  138. i + 1 not in self.blockedPins:
  139. state = False
  140. if inputMask & bit(i):
  141. state = True
  142. self.ignoreOutChange = True
  143. self.pins[i].setState(state)
  144. self.ignoreOutChange = False
  145. return True
  146. def __updateInOutStates(self):
  147. for i in range(0, self.nrPins):
  148. if i + 1 in self.blockedPins:
  149. self.pins[i].setEnabled(False)
  150. self.pins[i].setState(False)
  151. self.pinOuten[i].setEnabled(False)
  152. self.pinOuten[i].setState(False)
  153. else:
  154. self.pinOuten[i].setEnabled(True)
  155. if self.pinOuten[i].state():
  156. self.pins[i].setEnabled(True)
  157. else:
  158. self.pins[i].setEnabled(False)
  159. def __outEnChanged(self, unused=False):
  160. self.__updateInOutStates()
  161. outEnMask = self.getOutEnMask()
  162. try:
  163. self.unitest.queryTop("top.getChip().setOutputEnableMask(...)",
  164. outEnMask)
  165. except (TOPException), e:
  166. QMessageBox.critical(self, "TOP communication failed",
  167. "Failed to set output-enable states:\n" +\
  168. str(e))
  169. return
  170. self.readInputs()
  171. def __outChanged(self, unused=False):
  172. if self.ignoreOutChange:
  173. return
  174. outMask = self.getOutMask()
  175. try:
  176. self.unitest.queryTop("top.getChip().setOutputs(...)",
  177. outMask)
  178. except (TOPException), e:
  179. QMessageBox.critical(self, "TOP communication failed",
  180. "Failed to set output states:\n" +\
  181. str(e))
  182. return
  183. self.readInputs()
  184. def setBlockedPins(self, blockedPins):
  185. self.blockedPins = blockedPins
  186. self.__updateInOutStates()
  187. self.readInputs()
  188. def getOutEnMask(self):
  189. outEnMask = 0
  190. for i in range(0, self.nrPins):
  191. if self.pinOuten[i].state():
  192. outEnMask |= bit(i)
  193. return outEnMask
  194. def setOutEnMask(self, mask):
  195. for i in range(0, self.nrPins):
  196. if mask & bit(i):
  197. self.pinOuten[i].setState(True)
  198. else:
  199. self.pinOuten[i].setState(False)
  200. mask &= ~bit(i)
  201. if mask:
  202. raise TOPException("ZIF out-en mask has too many bits set")
  203. def getOutMask(self):
  204. outMask = 0
  205. for i in range(0, self.nrPins):
  206. if self.pins[i].state():
  207. outMask |= bit(i)
  208. return outMask
  209. def setOutMask(self, mask):
  210. for i in range(0, self.nrPins):
  211. if mask & bit(i):
  212. self.pins[i].setState(True)
  213. else:
  214. self.pins[i].setState(False)
  215. mask &= ~bit(i)
  216. if mask:
  217. raise TOPException("ZIF out mask has too many bits set")
  218. class UnitestDialog(QDialog):
  219. def __init__(self, mainWindow):
  220. QDialog.__init__(self, mainWindow)
  221. self.setWindowTitle("Universal logic tester")
  222. self.mainWindow = mainWindow
  223. self.setLayout(QGridLayout())
  224. self.inputPollBlocked = 0
  225. self.uiChangeBlocked = 0
  226. # Initialize the unitest chip
  227. (failed, returnValue) = self.mainWindow.runOperationSync(
  228. HwThread.TASK_INITCHIP,
  229. "unitest")
  230. if failed:
  231. raise TOPException("Failed to load 'unitest' chip: %s" % str(returnValue))
  232. self.queryTop("top.getChip().reset()")
  233. # Query the hardware layer for common parameters
  234. self.param_topType = self.queryTop("top.getProgrammerType()")
  235. self.param_gndLayouts = self.queryTop("top.gnd.supportedLayouts()")
  236. self.param_nrZifPins = self.queryTop("top.gnd.getNrOfPins()")
  237. self.param_vccLayouts = self.queryTop("top.vcc.supportedLayouts()")
  238. self.param_minVccVolt = self.queryTop("top.vcc.minVoltage()")
  239. self.param_maxVccVolt = self.queryTop("top.vcc.maxVoltage()")
  240. self.param_vppLayouts = self.queryTop("top.vpp.supportedLayouts()")
  241. self.param_minVppVolt = self.queryTop("top.vpp.minVoltage()")
  242. self.param_maxVppVolt = self.queryTop("top.vpp.maxVoltage()")
  243. self.param_oscFreq = self.queryTop("top.getOscillatorHz()")
  244. assert(self.param_nrZifPins % 2 == 0)
  245. self.param_vppLayouts.sort(key=lambda (layId, layMask): layMask)
  246. self.menuBar = QMenuBar(self)
  247. self.menuBar.addAction("&Load settings...", self.loadSettings)
  248. self.menuBar.addAction("&Save settings...", self.saveSettings)
  249. self.menuBar.addAction("&Raw command...", self.mainWindow.sendRawCommand)
  250. self.layout().addWidget(self.menuBar, 0, 0, 1, 3)
  251. self.zifWidget = ZifWidget(self, self.param_nrZifPins)
  252. self.layout().addWidget(self.zifWidget, 1, 0, 10, 1)
  253. group = QGroupBox("GND layout", self)
  254. group.setLayout(QGridLayout())
  255. self.gndLayout = QComboBox(self)
  256. self.gndLayout.addItem("Not connected", 0)
  257. for (layId, layMask) in self.param_gndLayouts:
  258. if not layMask:
  259. continue
  260. descr = "GND on pin "
  261. for i in range(0, self.param_nrZifPins):
  262. if layMask & bit(i):
  263. descr += str(i + 1) + " "
  264. self.gndLayout.addItem(descr, layId)
  265. group.layout().addWidget(self.gndLayout, 0, 0)
  266. self.layout().addWidget(group, 1, 1)
  267. group = QGroupBox("VCC layout", self)
  268. group.setLayout(QGridLayout())
  269. self.vccVoltage = QDoubleSpinBox(self)
  270. self.vccVoltage.setSuffix(" V")
  271. self.vccVoltage.setMinimum(self.param_minVccVolt)
  272. self.vccVoltage.setMaximum(self.param_maxVccVolt)
  273. self.vccVoltage.setSingleStep(0.1)
  274. group.layout().addWidget(self.vccVoltage, 0, 0)
  275. self.vccLayout = QComboBox(self)
  276. self.vccLayout.addItem("Not connected", 0)
  277. for (layId, layMask) in self.param_vccLayouts:
  278. if not layMask:
  279. continue
  280. descr = "VCC on pin "
  281. for i in range(0, self.param_nrZifPins):
  282. if layMask & bit(i):
  283. descr += str(i + 1) + " "
  284. self.vccLayout.addItem(descr, layId)
  285. group.layout().addWidget(self.vccLayout, 1, 0)
  286. self.layout().addWidget(group, 2, 1)
  287. group = QGroupBox("Input polling", self)
  288. group.setLayout(QGridLayout())
  289. self.inputPollEn = QCheckBox("Enabled", self)
  290. self.inputPollEn.setCheckState(Qt.Checked)
  291. group.layout().addWidget(self.inputPollEn, 0, 0)
  292. self.inputPollInterval = QDoubleSpinBox(self)
  293. self.inputPollInterval.setPrefix("Interval ")
  294. self.inputPollInterval.setSuffix(" seconds")
  295. self.inputPollInterval.setMinimum(0.25)
  296. self.inputPollInterval.setSingleStep(0.25)
  297. self.inputPollInterval.setValue(1.0)
  298. group.layout().addWidget(self.inputPollInterval, 1, 0)
  299. self.layout().addWidget(group, 3, 1)
  300. group = QGroupBox("Frequency counter", self)
  301. group.setLayout(QGridLayout())
  302. self.fcntEn = QCheckBox("Enabled", self)
  303. self.fcntEn.setCheckState(Qt.Unchecked)
  304. group.layout().addWidget(self.fcntEn, 0, 0)
  305. self.fcntPosEdge = QCheckBox("Positive edge", self)
  306. self.fcntPosEdge.setCheckState(Qt.Checked)
  307. group.layout().addWidget(self.fcntPosEdge, 1, 0)
  308. self.fcntPin = QComboBox(self)
  309. group.layout().addWidget(self.fcntPin, 2, 0)
  310. self.fcntValueLabel = QLabel(self)
  311. group.layout().addWidget(self.fcntValueLabel, 3, 0)
  312. self.fcntValue = 0
  313. self.layout().addWidget(group, 4, 1)
  314. group = QGroupBox("Oscillator", self)
  315. group.setLayout(QGridLayout())
  316. self.oscPin = QComboBox(self)
  317. self.oscPin.addItem("Disabled", Wrapper(0))
  318. for i in range(0, self.param_nrZifPins):
  319. self.oscPin.addItem("On pin %d" % (i + 1),
  320. Wrapper(bit(i)))
  321. group.layout().addWidget(self.oscPin, 0, 0)
  322. self.oscDiv = QSpinBox(self)
  323. self.oscDiv.setPrefix("Divider ")
  324. self.oscDiv.setSingleStep(1)
  325. self.oscDiv.setMinimum(1)
  326. self.oscDiv.setMaximum(self.param_oscFreq)
  327. self.oscDiv.setValue(self.param_oscFreq // 1000)
  328. group.layout().addWidget(self.oscDiv, 1, 0)
  329. self.oscFreq = QLabel(self)
  330. group.layout().addWidget(self.oscFreq, 2, 0)
  331. self.layout().addWidget(group, 5, 1)
  332. group = QGroupBox("VPP layout", self)
  333. group.setLayout(QGridLayout())
  334. self.vppVoltage = QDoubleSpinBox(self)
  335. self.vppVoltage.setSuffix(" V")
  336. self.vppVoltage.setMinimum(self.param_minVppVolt)
  337. self.vppVoltage.setMaximum(self.param_maxVppVolt)
  338. self.vppVoltage.setSingleStep(0.1)
  339. group.layout().addWidget(self.vppVoltage, 0, 0, 1, 2)
  340. self.vppLayouts = {}
  341. xOffset = 0
  342. yOffset = 0
  343. for (layId, layMask) in self.param_vppLayouts:
  344. if not layMask:
  345. continue
  346. for i in range(0, self.param_nrZifPins):
  347. if layMask & bit(i):
  348. descr = str(i + 1) + " "
  349. self.vppLayouts[layId] = QCheckBox(descr, self)
  350. self.vppLayouts[layId].stateChanged.connect(
  351. self.vppLayoutChanged)
  352. group.layout().addWidget(self.vppLayouts[layId],
  353. yOffset + 1, xOffset)
  354. yOffset += 1
  355. if yOffset == len(self.param_vppLayouts) // 2:
  356. yOffset = 0
  357. xOffset += 1
  358. self.layout().addWidget(group, 1, 2, 8, 1)
  359. self.inputPollTimer = QTimer()
  360. self.inputPollTimer.setSingleShot(True)
  361. self.inputPollTimer.timeout.connect(self.doInputPollTimer)
  362. self.inputPollEn.stateChanged.connect(self.inputPollChanged)
  363. self.inputPollInterval.valueChanged.connect(self.inputPollChanged)
  364. self.gndLayout.currentIndexChanged.connect(self.gndLayoutChanged)
  365. self.vccVoltage.valueChanged.connect(self.vccLayoutChanged)
  366. self.vccLayout.currentIndexChanged.connect(self.vccLayoutChanged)
  367. self.vppVoltage.valueChanged.connect(self.vppLayoutChanged)
  368. self.fcntEn.stateChanged.connect(self.fcntChanged)
  369. self.fcntPosEdge.stateChanged.connect(self.fcntChanged)
  370. self.fcntPin.currentIndexChanged.connect(self.fcntChanged)
  371. self.oscPin.currentIndexChanged.connect(self.oscChanged)
  372. self.oscDiv.valueChanged.connect(self.oscChanged)
  373. self.__modeChanged()
  374. self.gndLayoutChanged()
  375. self.vccLayoutChanged()
  376. self.inputPollChanged()
  377. self.oscChanged()
  378. def __readFcntValue(self):
  379. try:
  380. self.fcntValue = self.queryTop("top.getChip().getFreqCount()")
  381. except (TOPException), e:
  382. QMessageBox.critical(self, "TOP communication failed",
  383. "Failed to read frequency counter value:\n" +\
  384. str(e))
  385. return False
  386. return True
  387. def __updateFcntValueLabel(self):
  388. if self.getMode() != Chip_Unitest.MODE_FCNT:
  389. self.fcntValueLabel.clear()
  390. return
  391. if self.fcntValue:
  392. hz = "%.3f" % (float(self.param_oscFreq) / self.fcntValue)
  393. else:
  394. hz = "~~~"
  395. self.fcntValueLabel.setText("Measured: %s Hz" % hz)
  396. def __modeChanged(self):
  397. mode = self.getMode()
  398. activePinMask = self.queryTop("top.getChip().getActivePinMask()")
  399. self.uiChangeBlocked += 1
  400. # Update freq count UI
  401. self.fcntValue = 0
  402. self.fcntPin.clear()
  403. self.fcntPin.setEnabled(False)
  404. self.fcntPosEdge.setEnabled(False)
  405. if mode == Chip_Unitest.MODE_FCNT:
  406. for i in range(0, self.param_nrZifPins):
  407. if bit(i) & activePinMask == 0:
  408. continue
  409. self.fcntPin.addItem("On pin %d" % (i + 1), i)
  410. self.fcntPin.setEnabled(True)
  411. self.fcntPosEdge.setEnabled(True)
  412. self.__updateFcntValueLabel()
  413. # Update the ZIF widget
  414. self.updateZifCheckboxes()
  415. self.uiChangeBlocked -= 1
  416. def switchMode(self, mode):
  417. if self.getMode() == mode:
  418. return
  419. self.queryTop("top.getChip().setMode(...)", mode)
  420. self.__modeChanged()
  421. def __loadFile(self, filename):
  422. try:
  423. p = ConfigParser.SafeConfigParser()
  424. p.read((filename,))
  425. sect = "TOPRAMMER-UNITEST-SETTINGS"
  426. if not p.has_section(sect):
  427. raise TOPException("Invalid file format")
  428. ver = p.getint(sect, "fileVersion")
  429. verExpected = 1
  430. if ver != verExpected:
  431. raise TOPException("Unsupported file version (got %d, expected %d)" %\
  432. (ver, verExpected))
  433. pType = p.get(sect, "programmerType")
  434. if pType.upper() != self.param_topType.upper():
  435. raise TOPException("Programmer type mismatch (file = %s, connected = %s)" %\
  436. (pType, self.param_topType))
  437. layout = p.getint(sect, "gndLayout")
  438. idx = self.gndLayout.findData(layout)
  439. if idx < 0:
  440. raise TOPException("Invalid GND layout")
  441. self.gndLayout.setCurrentIndex(idx)
  442. layout = p.getint(sect, "vccLayout")
  443. idx = self.vccLayout.findData(layout)
  444. if idx < 0:
  445. raise TOPException("Invalid VCC layout")
  446. self.vccLayout.setCurrentIndex(idx)
  447. voltage = p.getfloat(sect, "vccVoltage")
  448. self.vccVoltage.setValue(voltage)
  449. layouts = p.get(sect, "vppLayout").split(",")
  450. for layId in self.vppLayouts.keys():
  451. if layId in layouts:
  452. self.vppLayouts[layId].setCheckState(Qt.Checked)
  453. else:
  454. self.vppLayouts[layId].setCheckState(Qt.Unchecked)
  455. voltage = p.getfloat(sect, "vppVoltage")
  456. self.vppVoltage.setValue(voltage)
  457. interval = p.getfloat(sect, "inputPollInterval")
  458. self.inputPollInterval.setValue(interval)
  459. enabled = p.getboolean(sect, "inputPollEnabled")
  460. if enabled:
  461. self.inputPollEn.setCheckState(Qt.Checked)
  462. else:
  463. self.inputPollEn.setCheckState(Qt.Unchecked)
  464. div = p.getint(sect, "oscillatorDiv")
  465. self.oscDiv.setValue(div)
  466. mask = int(p.get(sect, "oscillatorMask"), 16)
  467. for i in range(0, self.oscPin.count()):
  468. if self.oscPin.itemData(i).obj == mask:
  469. break
  470. else:
  471. raise TOPException("Invalid oscillator mask")
  472. self.oscPin.setCurrentIndex(i)
  473. mask = int(p.get(sect, "zifOutEnMask"), 16)
  474. self.zifWidget.setOutEnMask(mask)
  475. mask = int(p.get(sect, "zifOutMask"), 16)
  476. self.zifWidget.setOutMask(mask)
  477. enabled = p.getboolean(sect, "fcntEnabled")
  478. if enabled:
  479. self.fcntEn.setCheckState(Qt.Checked)
  480. else:
  481. self.fcntEn.setCheckState(Qt.Unchecked)
  482. pos = p.getboolean(sect, "fcntPosEdge")
  483. if pos:
  484. self.fcntPosEdge.setCheckState(Qt.Checked)
  485. else:
  486. self.fcntPosEdge.setCheckState(Qt.Unchecked)
  487. pin = p.getint(sect, "fcntPin")
  488. if pin >= 0:
  489. idx = self.fcntPin.findData(pin)
  490. if idx < 0:
  491. raise TOPException("Invalid fcntPin")
  492. self.fcntPin.setCurrentIndex(idx)
  493. except (ConfigParser.Error, TOPException, ValueError), e:
  494. QMessageBox.critical(self, "Failed to load settings",
  495. "Failed to load settings: %s" % str(e))
  496. def loadSettings(self):
  497. (fn, selFltr) = QFileDialog.getOpenFileName(
  498. self, "Load settings", "",
  499. "Toprammer-unitest settings (*.tus);;"
  500. "All files (*)")
  501. if not fn:
  502. return
  503. self.__loadFile(fn)
  504. def __saveFile(self, filename):
  505. try:
  506. fd = open(filename, "w+b")
  507. fd.write("[TOPRAMMER-UNITEST-SETTINGS]\r\n")
  508. fd.write("fileVersion=%d\r\n" % 1)
  509. fd.write("programmerType=%s\r\n" % self.param_topType)
  510. idx = self.gndLayout.currentIndex()
  511. fd.write("gndLayout=%d\r\n" % self.gndLayout.itemData(idx))
  512. idx = self.vccLayout.currentIndex()
  513. fd.write("vccLayout=%d\r\n" % self.vccLayout.itemData(idx))
  514. fd.write("vccVoltage=%f\r\n" % self.vccVoltage.value())
  515. vppLayouts = ""
  516. for layId in self.vppLayouts.keys():
  517. if self.vppLayouts[layId].checkState() == Qt.Checked:
  518. if vppLayouts:
  519. vppLayouts += ","
  520. vppLayouts += str(layId)
  521. if not vppLayouts:
  522. vppLayouts = "0"
  523. fd.write("vppLayout=%s\r\n" % vppLayouts)
  524. fd.write("vppVoltage=%f\r\n" % self.vppVoltage.value())
  525. fd.write("inputPollEnabled=%d\r\n" % int(self.inputPollEn.checkState() == Qt.Checked))
  526. fd.write("inputPollInterval=%f\r\n" % self.inputPollInterval.value())
  527. fd.write("fcntEnabled=%d\r\n" % (int(self.fcntEn.checkState() == Qt.Checked)))
  528. fd.write("fcntPosEdge=%d\r\n" % (int(self.fcntPosEdge.checkState() == Qt.Checked)))
  529. idx = self.fcntPin.currentIndex()
  530. pin = -1
  531. if idx >= 0:
  532. pin = self.fcntPin.itemData(idx)
  533. fd.write("fcntPin=%d\r\n" % pin)
  534. idx = self.oscPin.currentIndex()
  535. fd.write("oscillatorMask=%X\r\n" % self.oscPin.itemData(idx).obj)
  536. fd.write("oscillatorDiv=%d\r\n" % self.oscDiv.value())
  537. fd.write("zifOutEnMask=%X\r\n" % self.zifWidget.getOutEnMask())
  538. fd.write("zifOutMask=%X\r\n" % self.zifWidget.getOutMask())
  539. except (IOError), e:
  540. QMessageBox.critical(self, "Failed to save settings",
  541. "Failed to write settings to file: %s" % str(e))
  542. def saveSettings(self):
  543. (fn, selFltr) = QFileDialog.getSaveFileName(
  544. self, "Save settings", "",
  545. "Toprammer-unitest settings (*.tus)")
  546. if not fn:
  547. return
  548. if not fn.endswith(".tus"):
  549. fn += ".tus"
  550. self.__saveFile(fn)
  551. def closeEvent(self, e):
  552. self.inputPollTimer.stop()
  553. def queryTop(self, funcname, *parameters):
  554. self.inputPollBlocked += 1 # Avoid recursion
  555. (failed, returnValue) = self.mainWindow.runOperationSync(
  556. HwThread.TASK_GENERICTOPCALL,
  557. GenericTopCall(funcname, *parameters))
  558. self.inputPollBlocked -= 1
  559. if failed:
  560. raise TOPException("Failed to query TOP %s\n%s" % (funcname, str(returnValue)))
  561. return returnValue
  562. def getMode(self):
  563. return self.queryTop("top.getChip().getMode()")
  564. def shutdown(self):
  565. self.inputPollTimer.stop()
  566. def updateZifCheckboxes(self):
  567. mode = self.getMode()
  568. blockedPins = []
  569. # Basic mask
  570. activePinMask = self.queryTop("top.getChip().getActivePinMask()")
  571. for i in range(0, self.zifWidget.nrPins):
  572. if activePinMask & bit(i) == 0:
  573. blockedPins.append(i + 1)
  574. # GND
  575. idx = self.gndLayout.currentIndex()
  576. lay = self.gndLayout.itemData(idx)
  577. blockedPins.extend(self.queryTop("top.gnd.ID2pinlist(...)", lay))
  578. # VCC
  579. idx = self.vccLayout.currentIndex()
  580. lay = self.vccLayout.itemData(idx)
  581. blockedPins.extend(self.queryTop("top.vcc.ID2pinlist(...)", lay))
  582. # VPP
  583. for key in self.vppLayouts.keys():
  584. if self.vppLayouts[key].checkState() == Qt.Checked:
  585. blockedPins.extend(self.queryTop("top.vpp.ID2pinlist(...)", key))
  586. # OSC
  587. idx = self.oscPin.currentIndex()
  588. mask = self.oscPin.itemData(idx).obj
  589. for i in range(0, self.zifWidget.nrPins):
  590. if mask & bit(i):
  591. blockedPins.append(i + 1)
  592. # Freq counter
  593. if mode == Chip_Unitest.MODE_FCNT:
  594. idx = self.fcntPin.currentIndex()
  595. pinNumber = self.fcntPin.itemData(idx)
  596. blockedPins.append(pinNumber + 1)
  597. # Set blocked pins in ZIF widget
  598. self.zifWidget.setBlockedPins(tuple(set(blockedPins)))
  599. def gndLayoutChanged(self, unused=None):
  600. if self.uiChangeBlocked:
  601. return
  602. idx = self.gndLayout.currentIndex()
  603. selLayout = self.gndLayout.itemData(idx)
  604. try:
  605. self.queryTop("top.getChip().setGND(...)", selLayout)
  606. except (TOPException), e:
  607. QMessageBox.critical(self, "TOP communication failed",
  608. "Failed to set GND layout:\n" +\
  609. str(e))
  610. return
  611. self.updateZifCheckboxes()
  612. def vccLayoutChanged(self, unused=None):
  613. if self.uiChangeBlocked:
  614. return
  615. selVoltage = self.vccVoltage.value()
  616. idx = self.vccLayout.currentIndex()
  617. selLayout = self.vccLayout.itemData(idx)
  618. try:
  619. self.queryTop("top.getChip().setVCC(...)", selVoltage, selLayout)
  620. except (TOPException), e:
  621. QMessageBox.critical(self, "TOP communication failed",
  622. "Failed to set VCC layout:\n" +\
  623. str(e))
  624. return
  625. self.updateZifCheckboxes()
  626. def vppLayoutChanged(self, unused=None):
  627. if self.uiChangeBlocked:
  628. return
  629. selVoltage = self.vppVoltage.value()
  630. selLayouts = []
  631. for key in self.vppLayouts.keys():
  632. if self.vppLayouts[key].checkState() == Qt.Checked:
  633. selLayouts.append(key)
  634. try:
  635. self.queryTop("top.getChip().setVPP(...)", selVoltage, selLayouts)
  636. except (TOPException), e:
  637. QMessageBox.critical(self, "TOP communication failed",
  638. "Failed to set VPP layout:\n" +\
  639. str(e))
  640. return
  641. self.updateZifCheckboxes()
  642. def doInputPollTimer(self):
  643. if self.inputPollBlocked:
  644. # Blocked. Reschedule.
  645. self.inputPollTimer.start(1)
  646. return
  647. ok = self.zifWidget.readInputs()
  648. if ok:
  649. if self.fcntEn.checkState() == Qt.Checked:
  650. ok = self.__readFcntValue()
  651. if ok:
  652. self.__updateFcntValueLabel()
  653. if not ok:
  654. # Whoops, error. Disable input polling
  655. self.inputPollEn.setCheckState(Qt.Unchecked)
  656. return False
  657. # Reschedule
  658. inter = int(self.inputPollInterval.value() * 1000)
  659. self.inputPollTimer.start(inter)
  660. return True
  661. def inputPollChanged(self, unused=None):
  662. if self.uiChangeBlocked:
  663. return
  664. if self.inputPollEn.checkState() == Qt.Checked:
  665. self.inputPollInterval.setEnabled(True)
  666. if self.doInputPollTimer():
  667. inter = int(self.inputPollInterval.value() * 1000)
  668. self.inputPollTimer.start(inter)
  669. else:
  670. self.inputPollInterval.setEnabled(False)
  671. self.inputPollTimer.stop()
  672. def fcntChanged(self, unused=None):
  673. if self.uiChangeBlocked:
  674. return
  675. try:
  676. if self.fcntEn.checkState() == Qt.Checked:
  677. self.switchMode(Chip_Unitest.MODE_FCNT)
  678. idx = self.fcntPin.currentIndex()
  679. pinNumber = self.fcntPin.itemData(idx)
  680. inv = (self.fcntPosEdge.checkState() != Qt.Checked)
  681. self.queryTop("top.getChip().setFreqCountPin(...)",
  682. pinNumber, inv)
  683. self.__readFcntValue()
  684. self.__updateFcntValueLabel()
  685. # Force enable input polling
  686. self.inputPollEn.setCheckState(Qt.Checked)
  687. self.inputPollEn.setEnabled(False)
  688. else:
  689. self.switchMode(Chip_Unitest.MODE_UNITEST)
  690. self.__updateFcntValueLabel()
  691. self.inputPollEn.setEnabled(True)
  692. except (TOPException), e:
  693. QMessageBox.critical(self, "TOP communication failed",
  694. "Failed configure frequency counter:\n" +\
  695. str(e))
  696. return
  697. self.updateZifCheckboxes()
  698. def oscChanged(self, unused=None):
  699. if self.uiChangeBlocked:
  700. return
  701. try:
  702. div = self.oscDiv.value()
  703. self.queryTop("top.getChip().setOscDivider(...)", div)
  704. idx = self.oscPin.currentIndex()
  705. mask = self.oscPin.itemData(idx).obj
  706. self.queryTop("top.getChip().setOscMask(...)", mask)
  707. except (TOPException), e:
  708. QMessageBox.critical(self, "TOP communication failed",
  709. "Failed configure oscillator:\n" +\
  710. str(e))
  711. return
  712. self.oscFreq.setText("%.03f Hz" % (float(self.param_oscFreq) / div))
  713. self.updateZifCheckboxes()
  714. class GuiUserInterface(AbstractUserInterface):
  715. # Global progress
  716. PROGRESSMETER_USER_GLOBAL = AbstractUserInterface.PROGRESSMETER_USER + 0
  717. def __init__(self, hwThread):
  718. self.hwThread = hwThread
  719. def progressMeterInit(self, meterId, message, nrSteps):
  720. self.hwThread.appendMessage("progrInit", (meterId, message, nrSteps))
  721. def progressMeterFinish(self, meterId):
  722. self.hwThread.appendMessage("progrFinish", meterId)
  723. def progressMeter(self, meterId, step):
  724. self.hwThread.appendMessage("progress", (meterId, step))
  725. def __consoleMessage(self, message):
  726. self.hwThread.appendMessage("console", message + "\n")
  727. def warningMessage(self, message):
  728. self.__consoleMessage("WARNING: " + message)
  729. def infoMessage(self, message):
  730. self.__consoleMessage(message)
  731. def debugMessage(self, message):
  732. self.__consoleMessage(message)
  733. class GenericTopCall(object):
  734. "One call to 'class Top'. Used by TASK_GENERICTOPCALL"
  735. def __init__(self, methodName, *parameters, **userData):
  736. self.methodName = methodName
  737. self.parameters = parameters
  738. self.result = None
  739. self.userData = userData
  740. class HwThread(QThread):
  741. TASK_SHUTDOWN = 0
  742. TASK_INITCHIP = 1
  743. TASK_GENERICTOPCALL = 2
  744. class CancelException(Exception):
  745. def __init__(self):
  746. Exception.__init__(self, "Operation cancelled")
  747. def __init__(self, mainWindow):
  748. QThread.__init__(self, mainWindow)
  749. self.mainWindow = mainWindow
  750. self.killRequest = False
  751. self.messageQueue = []
  752. self.top = None
  753. self.task = None
  754. self.opaqueId = None
  755. self.taskParameter = None
  756. self.cancel = False
  757. self.cancellationBlocked = 0
  758. self.waitCondition = QWaitCondition()
  759. self.mutex = QMutex()
  760. self.setTopParameters()
  761. self.setDevice()
  762. self.start()
  763. def killThread(self):
  764. if self.isRunning():
  765. self.mutex.lock()
  766. self.task = self.TASK_SHUTDOWN
  767. self.killRequest = True
  768. self.waitCondition.wakeAll()
  769. self.mutex.unlock()
  770. self.wait()
  771. def setDevice(self, devIdentifier=None):
  772. assert(self.top is None and self.task is None)
  773. self.param_devIdentifier = devIdentifier
  774. def setTopParameters(self, verbose=2, forceLevel=0,
  775. usebroken=True, forceBitfileUpload=False):
  776. assert(self.top is None and self.task is None)
  777. self.param_verbose = verbose
  778. self.param_forceLevel = forceLevel
  779. self.param_usebroken = usebroken
  780. self.param_forceBitfileUpload = forceBitfileUpload
  781. def triggerTask(self, task, taskParameter=None,
  782. opaqueId=None, mutexIsLocked=False):
  783. if not mutexIsLocked:
  784. self.mutex.lock()
  785. self.cancel = False
  786. self.task = task
  787. self.opaqueId = opaqueId
  788. self.taskParameter = taskParameter
  789. self.waitCondition.wakeAll()
  790. if not mutexIsLocked:
  791. self.mutex.unlock()
  792. def run(self):
  793. self.mutex.lock()
  794. while True:
  795. if not self.killRequest and self.task is None:
  796. self.waitCondition.wait(self.mutex)
  797. self.mutex.unlock()
  798. self.__taskWorker()
  799. self.mutex.lock()
  800. if self.killRequest and self.task is None:
  801. break
  802. self.mutex.unlock()
  803. def cancelTask(self):
  804. self.mutex.lock()
  805. self.cancel = True
  806. self.mutex.unlock()
  807. def __blockCancellation(self):
  808. self.cancellationBlocked += 1
  809. def __unblockCancellation(self):
  810. self.cancellationBlocked -= 1
  811. def __cancellationPoint(self):
  812. # Mutex must be locked
  813. if not self.cancel:
  814. return
  815. if self.cancellationBlocked:
  816. return
  817. self.cancel = False
  818. self.mutex.unlock()
  819. raise HwThread.CancelException() # Caught in __taskWorker
  820. def __doCancelTask(self):
  821. # Make sure the device is in a consistent state.
  822. self.__blockCancellation()
  823. if self.top:
  824. print "Operation cancelled. Resetting chip."
  825. self.top.resetChip()
  826. self.__unblockCancellation()
  827. def appendMessage(self, message, data, nocancel=False):
  828. # Append a message to the message queue.
  829. # This is a cancellation point!
  830. self.mutex.lock()
  831. if not nocancel:
  832. self.__cancellationPoint()
  833. self.messageQueue.append( (message, data) )
  834. self.mutex.unlock()
  835. self.__notifyMainWindow()
  836. def __taskWorker(self):
  837. failed = True
  838. try:
  839. self.cancellationBlocked = 0
  840. result = self.__runTask(self.task)
  841. failed = False
  842. except (TOPException), e:
  843. result = e
  844. except (HwThread.CancelException), e:
  845. self.__doCancelTask()
  846. result = e
  847. except (Exception), e:
  848. result = e
  849. self.appendMessage("finished", (self.opaqueId, failed, result),
  850. nocancel=True)
  851. self.task = None
  852. self.taskParameter = None
  853. self.opaqueId = None
  854. def __runTask(self, task):
  855. retval = None
  856. if task == self.TASK_SHUTDOWN or task == self.TASK_INITCHIP:
  857. if self.top:
  858. self.__blockCancellation()
  859. self.top.shutdownChip()
  860. self.top.shutdownProgrammer()
  861. self.top = None
  862. self.__unblockCancellation()
  863. if task == self.TASK_SHUTDOWN:
  864. return None
  865. if not self.top:
  866. # Initialize Hardware access
  867. self.__blockCancellation()
  868. self.top = TOP(devIdentifier = self.param_devIdentifier,
  869. verbose = self.param_verbose,
  870. forceLevel = self.param_forceLevel,
  871. usebroken = self.param_usebroken,
  872. forceBitfileUpload = self.param_forceBitfileUpload,
  873. userInterface = GuiUserInterface(self))
  874. self.__unblockCancellation()
  875. if task == self.TASK_INITCHIP:
  876. self.__blockCancellation()
  877. self.top.initializeChip(self.taskParameter)
  878. chip = self.top.getChip()
  879. asciiArtLayout = None
  880. layoutGen = chip.getLayoutGenerator()
  881. if layoutGen:
  882. asciiArtLayout = layoutGen.zifLayoutAsciiArt()
  883. self.__unblockCancellation()
  884. retval = (chip, asciiArtLayout)
  885. elif task == self.TASK_GENERICTOPCALL:
  886. # The parameter is one GenericTopCall
  887. # or a list of calls.
  888. topCallList = self.taskParameter
  889. if not isinstance(topCallList, list) and\
  890. not isinstance(topCallList, tuple):
  891. # It is only a single call. Make an iterable.
  892. topCallList = (topCallList, )
  893. self.__globalProgressInit(len(topCallList))
  894. # Iterate over the list of GenericTopCalls
  895. for topCallIndex, topCall in enumerate(topCallList):
  896. method = topCall.methodName.strip()
  897. if method.endswith(")"): # strip (...) suffix
  898. method = method[:method.rfind("(")]
  899. if method.startswith("top."): # strip 'top.' prefix
  900. method = method[4:]
  901. paramList = []
  902. for i in range(len(topCall.parameters)):
  903. paramList.append("topCall.parameters[%d]" % i)
  904. result = eval("self.top.%s(%s)" % (method, ", ".join(paramList)))
  905. topCall.result = result
  906. self.__globalProgress(topCallIndex + 1)
  907. # If there was only one call, return the result.
  908. # Otherwise return the complete call-list including results.
  909. if len(topCallList) == 1:
  910. retval = topCallList[0].result
  911. else:
  912. retval = topCallList
  913. else:
  914. raise TOPException("INTERNAL ERROR: HwThread: unknown task")
  915. return retval
  916. def __globalProgressInit(self, nrSteps):
  917. self.appendMessage("progrInit",
  918. (GuiUserInterface.PROGRESSMETER_USER_GLOBAL,
  919. None, nrSteps))
  920. def __globalProgress(self, step):
  921. self.appendMessage("progress",
  922. (GuiUserInterface.PROGRESSMETER_USER_GLOBAL,
  923. step))
  924. return step
  925. def __notifyMainWindow(self):
  926. QApplication.postEvent(self.mainWindow, QEvent(EVENT_HWTHREAD))
  927. def handleMessageQueue(self):
  928. self.mutex.lock()
  929. for (message, data) in self.messageQueue:
  930. if message == "finished":
  931. self.mainWindow.hardwareTaskFinished(
  932. opaqueId=data[0], failed=data[1], returnValue=data[2])
  933. elif message == "console":
  934. self.mainWindow.console.showMessage(data)
  935. elif message == "progrInit":
  936. (meterId, message, nrSteps) = data
  937. self.mainWindow.console.progressMeterInit(meterId, nrSteps)
  938. elif message == "progrFinish":
  939. meterId = data
  940. self.mainWindow.console.progressMeter(meterId, -1)
  941. elif message == "progress":
  942. (meterId, step) = data
  943. self.mainWindow.console.progressMeter(meterId, step)
  944. else:
  945. assert(0)
  946. self.messageQueue = []
  947. self.mutex.unlock()
  948. class Console(QDockWidget):
  949. STAT_OK = 0
  950. STAT_ERROR = 1
  951. STAT_PROGRESS = 2
  952. def __init__(self, mainWindow):
  953. QDockWidget.__init__(self, "Console", mainWindow)
  954. self.addPrefix = True
  955. self.statusUpdateBlocked = 0
  956. self.setFeatures(self.DockWidgetMovable | self.DockWidgetFloatable)
  957. self.setWidget(QWidget(self))
  958. self.widget().show()
  959. self.widget().setLayout(QGridLayout(self.widget()))
  960. self.consoleMsgs = []
  961. self.consoleText = QTextEdit(self)
  962. self.consoleText.setReadOnly(True)
  963. self.widget().layout().addWidget(self.consoleText, 0, 0, 1, 3)
  964. self.statusLabel = QLabel(self)
  965. self.widget().layout().addWidget(self.statusLabel, 1, 0, 2, 1)
  966. self.chipaccessProgress = QProgressBar(self)
  967. self.widget().layout().addWidget(self.chipaccessProgress, 1, 1)
  968. self.globalProgress = QProgressBar(self)
  969. self.widget().layout().addWidget(self.globalProgress, 2, 1)
  970. self.cancelButton = QPushButton("Cancel", self)
  971. self.cancelButton.setEnabled(False)
  972. self.widget().layout().addWidget(self.cancelButton, 1, 2, 2, 1)
  973. self.setStatus(self.STAT_OK)
  974. self.idToProgressBar = {
  975. GuiUserInterface.PROGRESSMETER_CHIPACCESS : self.chipaccessProgress,
  976. GuiUserInterface.PROGRESSMETER_USER_GLOBAL : self.globalProgress,
  977. }
  978. self.cancelButton.released.connect(mainWindow.cancelHardwareTask)
  979. def blockStatusUpdate(self):
  980. self.statusUpdateBlocked += 1
  981. def unblockStatusUpdate(self):
  982. self.statusUpdateBlocked -= 1
  983. def setTaskRunning(self, running, success=True):
  984. if self.statusUpdateBlocked:
  985. return
  986. self.cancelButton.setEnabled(running)
  987. if running:
  988. self.setStatus(Console.STAT_PROGRESS)
  989. # Set progress meters to "busy"
  990. for meterId in self.idToProgressBar.keys():
  991. self.progressMeterInit(meterId, 0)
  992. else:
  993. if success:
  994. self.setStatus(Console.STAT_OK)
  995. else:
  996. self.setStatus(Console.STAT_ERROR)
  997. # Reset progress meters to 0%
  998. for meterId in self.idToProgressBar.keys():
  999. self.progressMeterInit(meterId, 2)
  1000. def setStatus(self, status):
  1001. if self.statusUpdateBlocked:
  1002. return
  1003. if status == self.STAT_OK:
  1004. path = getIconPath("ok")
  1005. elif status == self.STAT_ERROR:
  1006. path = getIconPath("error")
  1007. elif status == self.STAT_PROGRESS:
  1008. path = getIconPath("progress")
  1009. else:
  1010. assert(0)
  1011. self.statusLabel.setPixmap(QPixmap(path))
  1012. def __commitText(self):
  1013. limit = 100
  1014. if len(self.consoleMsgs) > limit:
  1015. self.consoleMsgs.pop(0)
  1016. assert(len(self.consoleMsgs) == limit)
  1017. html = "<HTML><BODY>" + "".join(self.consoleMsgs) + "</BODY></HTML>"
  1018. self.consoleText.setHtml(html)
  1019. # Scroll to end
  1020. scroll = self.consoleText.verticalScrollBar()
  1021. scroll.setTracking(True)
  1022. scroll.setSliderPosition(scroll.maximum())
  1023. scroll.setValue(scroll.maximum())
  1024. def showMessage(self, message, bold=False):
  1025. message = str(message)
  1026. if not message:
  1027. return
  1028. newline = False
  1029. if message.endswith("\n"):
  1030. newline = True
  1031. message = message[:-1]
  1032. message = htmlEscape(message)
  1033. if bold:
  1034. message = "<B>" + message + "</B>"
  1035. if self.addPrefix:
  1036. time = str(QTime.currentTime().toString("hh:mm:ss"))
  1037. message = "<I>[%s]</I>&nbsp;&nbsp;%s" % (time, message)
  1038. self.addPrefix = newline
  1039. if newline:
  1040. message += "<BR />"
  1041. lastmsg = None
  1042. if self.consoleMsgs:
  1043. lastmsg = self.consoleMsgs[-1]
  1044. if lastmsg and not lastmsg.endswith("<BR />"):
  1045. self.consoleMsgs[-1] = self.consoleMsgs[-1] + message
  1046. else:
  1047. self.consoleMsgs.append(message)
  1048. self.__commitText()
  1049. def progressMeterInit(self, meterId, nrSteps):
  1050. if self.statusUpdateBlocked:
  1051. return
  1052. progress = self.idToProgressBar[meterId]
  1053. progress.setMinimum(0)
  1054. progress.setMaximum(max(0, nrSteps - 1))
  1055. progress.setValue(progress.maximum())
  1056. progress.setValue(0)
  1057. def progressMeter(self, meterId, step):
  1058. if self.statusUpdateBlocked:
  1059. return
  1060. progress = self.idToProgressBar[meterId]
  1061. if progress.maximum() == 0:
  1062. progress.setMaximum(1)
  1063. progress.setValue(1)
  1064. else:
  1065. progress.setValue(step)
  1066. class HexEditWidget(QWidget):
  1067. def __init__(self, scrollArea, parent=None):
  1068. QWidget.__init__(self, parent)
  1069. self.scrollArea = scrollArea
  1070. self.bgColor = QColor("#FFFFFF")
  1071. self.cursor0Color = QColor("#A0A07F")
  1072. self.cursor1Color = QColor("#D0D0AF")
  1073. font = self.font()
  1074. font.setFamily("monospace")
  1075. font.setFixedPitch(True)
  1076. font.setPointSize(10)
  1077. self.setFont(font)
  1078. self.charWidth = self.fontMetrics().width("x")
  1079. self.charHeight = self.fontMetrics().height()
  1080. self.bytesPerLine = 16
  1081. self.previousData = b""
  1082. self.setData(b"")
  1083. self.__setCursor(0, False)
  1084. self.setFocusPolicy(Qt.StrongFocus)
  1085. def updateText(self):
  1086. lines = []
  1087. if self.data:
  1088. for i in range(0, len(self.data), self.bytesPerLine):
  1089. end = min(i + self.bytesPerLine, len(self.data))
  1090. data = self.data[i : end]
  1091. try:
  1092. prevData = self.previousData[i : end]
  1093. except IndexError:
  1094. prevData = None
  1095. if prevData == data:
  1096. lines.append(self.textLines[i // self.bytesPerLine])
  1097. else:
  1098. text = [ "[%08X]: " % i ]
  1099. for byte in data:
  1100. text.append(" " + byte2hex(byte))
  1101. if len(data) % self.bytesPerLine:
  1102. # padding
  1103. nrLeft = self.bytesPerLine - (len(data) % self.bytesPerLine)
  1104. text.append(" " * nrLeft)
  1105. text.append(" |")
  1106. for byte in data:
  1107. text.append(bytes2ascii(byte))
  1108. text.append("|")
  1109. lines.append("".join(text))
  1110. else:
  1111. lines = [ "<The buffer is empty>", ]
  1112. self.textLines = lines
  1113. self.nrLines = len(lines)
  1114. self.previousData = self.data
  1115. width = self.fontMetrics().width(self.textLines[0])
  1116. height = self.nrLines * self.charHeight
  1117. self.resize(width + 20, height + 20)
  1118. self.repaint()
  1119. def getData(self):
  1120. return self.data
  1121. def setData(self, data):
  1122. if not data:
  1123. data = ""
  1124. self.data = data
  1125. self.updateText()
  1126. self.__setCursor(0, False)
  1127. def charInput(self, char):
  1128. if not self.data:
  1129. return
  1130. data = list(self.data)
  1131. assert(self.cursorByte < len(data))
  1132. if self.cursorOnAscii:
  1133. data[self.cursorByte] = char
  1134. self.__setCursor(self.cursorByte + 1, True)
  1135. else:
  1136. dataByte = byte2int(data[self.cursorByte])
  1137. char = ord(char.upper())
  1138. if char >= ord("0") and char <= ord("9"):
  1139. nibble = char - ord("0")
  1140. elif char >= ord("A") and char <= ord("F"):
  1141. nibble = char - ord("A") + 10
  1142. else:
  1143. return
  1144. if self.cursorNibble == 0:
  1145. dataByte = (dataByte & 0xF0) | nibble
  1146. else:
  1147. dataByte = (dataByte & 0x0F) | (nibble << 4)
  1148. data[self.cursorByte] = chr(dataByte)
  1149. if self.cursorNibble == 1:
  1150. self.cursorNibble = 0
  1151. else:
  1152. self.__setCursor(self.cursorByte + 1, False)
  1153. self.data = "".join(data)
  1154. self.updateText()
  1155. def keyPressEvent(self, e):
  1156. linesOnScreen = self.scrollArea.viewport().height() // self.charHeight
  1157. if e.matches(QKeySequence.Delete) or\
  1158. e.key() == Qt.Key_Backspace:
  1159. self.__setCursor(self.cursorByte - 1, self.cursorOnAscii)
  1160. return
  1161. if e.matches(QKeySequence.MoveToNextChar):
  1162. self.__setCursor(self.cursorByte + 1, self.cursorOnAscii)
  1163. return
  1164. if e.matches(QKeySequence.MoveToPreviousChar):
  1165. self.__setCursor(self.cursorByte - 1, self.cursorOnAscii)
  1166. return
  1167. if e.matches(QKeySequence.MoveToStartOfLine):
  1168. self.__setCursor(self.cursorByte - self.cursorByte % self.bytesPerLine,
  1169. self.cursorOnAscii)
  1170. return
  1171. if e.matches(QKeySequence.MoveToEndOfLine):
  1172. self.__setCursor(self.cursorByte - self.cursorByte % self.bytesPerLine
  1173. + self.bytesPerLine - 1,
  1174. self.cursorOnAscii)
  1175. return
  1176. if e.matches(QKeySequence.MoveToNextLine):
  1177. self.__setCursor(self.cursorByte + self.bytesPerLine, self.cursorOnAscii)
  1178. return
  1179. if e.matches(QKeySequence.MoveToPreviousLine):
  1180. self.__setCursor(self.cursorByte - self.bytesPerLine, self.cursorOnAscii)
  1181. return
  1182. if e.matches(QKeySequence.MoveToStartOfDocument):
  1183. self.__setCursor(0, self.cursorOnAscii)
  1184. return
  1185. if e.matches(QKeySequence.MoveToEndOfDocument):
  1186. self.__setCursor(len(self.data) - 1, self.cursorOnAscii)
  1187. return
  1188. if e.matches(QKeySequence.MoveToNextPage):
  1189. self.__setCursor(self.cursorByte + int(linesOnScreen * 0.8) * self.bytesPerLine,
  1190. self.cursorOnAscii)
  1191. return
  1192. if e.matches(QKeySequence.MoveToPreviousPage):
  1193. self.__setCursor(self.cursorByte - int(linesOnScreen * 0.8) * self.bytesPerLine,
  1194. self.cursorOnAscii)
  1195. return
  1196. text = str(e.text())
  1197. if text:
  1198. key = ord(text[0])
  1199. if self.cursorOnAscii:
  1200. self.charInput(chr(key))
  1201. else:
  1202. if (key >= ord("0") and key <= ord("9")) or\
  1203. (key >= ord("a") and key <= ord("f")) or\
  1204. (key >= ord("A") and key <= ord("F")):
  1205. self.charInput(chr(key))
  1206. def __setCursor(self, byteNr, asciiArea):
  1207. byteNr = min(byteNr, len(self.data) - 1)
  1208. byteNr = max(byteNr, 0)
  1209. self.cursorOnAscii = asciiArea
  1210. self.cursorByte = byteNr
  1211. self.cursorNibble = 1
  1212. self.repaint()
  1213. (x, y) = self.__cursorUpperLeftEdge()
  1214. self.scrollArea.ensureVisible(x, y)
  1215. def mousePressEvent(self, e):
  1216. x = e.pos().x()
  1217. y = e.pos().y()
  1218. byteAreaX = self.charWidth * 13
  1219. byteAreaY = 3
  1220. asciiAreaX = self.charWidth * (13 + 3 * self.bytesPerLine + 3 - 1)
  1221. asciiAreaY = 3
  1222. if x >= byteAreaX and\
  1223. y >= byteAreaY and\
  1224. x <= byteAreaX + self.charWidth * 3 * self.bytesPerLine and\
  1225. y <= byteAreaY + self.charHeight * self.nrLines:
  1226. # Click in byte area.
  1227. x -= byteAreaX
  1228. y -= byteAreaY
  1229. line = y // self.charHeight
  1230. column = x // (self.charWidth * 3)
  1231. self.__setCursor(line * self.bytesPerLine + column,
  1232. False)
  1233. return
  1234. if x >= asciiAreaX and\
  1235. y >= asciiAreaY and\
  1236. x <= asciiAreaX + self.charWidth * self.bytesPerLine and\
  1237. y <= asciiAreaY + self.charHeight * self.nrLines:
  1238. # Click on ascii area.
  1239. x -= asciiAreaX
  1240. y -= asciiAreaY
  1241. line = y // self.charHeight
  1242. column = x // self.charWidth
  1243. self.__setCursor(line * self.bytesPerLine + column,
  1244. True)
  1245. return
  1246. def __cursorUpperLeftEdge(self):
  1247. if self.cursorOnAscii:
  1248. x = self.charWidth * (13 + 3 * self.bytesPerLine + 3 - 1)
  1249. x += self.charWidth * (self.cursorByte % self.bytesPerLine)
  1250. y = self.charHeight * (self.cursorByte // self.bytesPerLine)
  1251. y += 3
  1252. else:
  1253. x = self.charWidth * 13
  1254. x += self.charWidth * 3 * (self.cursorByte % self.bytesPerLine)
  1255. y = self.charHeight * (self.cursorByte // self.bytesPerLine)
  1256. y += 3
  1257. return (x, y)
  1258. def paintEvent(self, e):
  1259. p = QPainter(self)
  1260. # Background
  1261. p.fillRect(0, 0, self.width(), self.height(), self.bgColor)
  1262. # Cursor
  1263. if self.data and self.hasFocus():
  1264. (x, y) = self.__cursorUpperLeftEdge()
  1265. if self.cursorOnAscii:
  1266. p.fillRect(x, y, self.charWidth, self.charHeight,
  1267. self.cursor0Color)
  1268. else:
  1269. p.fillRect(x, y, self.charWidth * 2, self.charHeight,
  1270. self.cursor1Color)
  1271. if self.cursorNibble == 0:
  1272. x += self.charWidth
  1273. p.fillRect(x, y, self.charWidth, self.charHeight,
  1274. self.cursor0Color)
  1275. # Text
  1276. y = self.charHeight
  1277. for line in self.textLines:
  1278. p.drawText(0, y, line)
  1279. y += self.charHeight
  1280. class HexEdit(QScrollArea):
  1281. def __init__(self, parent=None):
  1282. QScrollArea.__init__(self, parent)
  1283. self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
  1284. self.setWidgetResizable(False)
  1285. self.setWidget(HexEditWidget(self, self))
  1286. def setData(self, data):
  1287. self.widget().setData(data)
  1288. def getData(self):
  1289. return self.widget().getData()
  1290. class BufferWidget(QWidget):
  1291. def __init__(self, mainWindow, name):
  1292. QWidget.__init__(self, mainWindow)
  1293. self.mainWindow = mainWindow
  1294. self.name = name
  1295. self.hide()
  1296. self.setLayout(QGridLayout(self))
  1297. self.setAvailable(False)
  1298. self.setReadOnly()
  1299. def getName(self):
  1300. return self.name
  1301. def setAvailable(self, available):
  1302. self.available = available
  1303. def isAvailable(self):
  1304. return self.available
  1305. def setReadOnly(self, readOnly=True):
  1306. self.readOnly = readOnly
  1307. def isReadOnly(self):
  1308. return self.readOnly
  1309. def getRawData(self):
  1310. return None
  1311. def setRawData(self, data):
  1312. return False
  1313. def setDataWithIHexInterpreter(self, interp, readRaw):
  1314. return False
  1315. def clear(self):
  1316. pass
  1317. class InfoBufferWidget(BufferWidget):
  1318. def __init__(self, mainWindow, name):
  1319. BufferWidget.__init__(self, mainWindow, name)
  1320. self.zifLayout = QLabel(self)
  1321. font = self.zifLayout.font()
  1322. font.setFixedPitch(True)
  1323. font.setFamily("monospace")
  1324. font.setPointSize(7)
  1325. self.zifLayout.setFont(font)
  1326. self.layout().addWidget(self.zifLayout, 0, 0, 6, 1)
  1327. def addLabel(name, y):
  1328. l = QLabel(name, self)
  1329. l.setAlignment(Qt.AlignTop | Qt.AlignLeft)
  1330. self.layout().addWidget(l, y, 1)
  1331. label = QLabel(self)
  1332. label.setAlignment(Qt.AlignTop | Qt.AlignLeft)
  1333. font = label.font()
  1334. font.setBold(True)
  1335. label.setFont(font)
  1336. self.layout().addWidget(label, y, 2)
  1337. return label
  1338. self.chipName = addLabel("Chip name:", 0)
  1339. self.comment = addLabel("Comment:", 1)
  1340. self.packages = addLabel("Packages:", 2)
  1341. self.chipSig = addLabel("Chip signature bytes:", 3)
  1342. self.maintainer = addLabel("Chip maintainer:", 4)
  1343. self.layout().setColumnStretch(3, 99)
  1344. self.layout().setRowStretch(5, 99)
  1345. self.clear()
  1346. def clear(self):
  1347. self.chipName.setText("<No chip selected>")
  1348. self.setComment(None)
  1349. self.setChipSignature(None)
  1350. self.setChipLayout(None)
  1351. self.setPackages(None)
  1352. self.setMaintainer(None)
  1353. def setChipSignature(self, bindata):
  1354. if bindata:
  1355. self.chipSig.setText(bytes2hex(bindata))
  1356. else:
  1357. self.chipSig.setText("None")
  1358. def setComment(self, comment):
  1359. if comment:
  1360. self.comment.setText(comment)
  1361. else:
  1362. self.comment.setText("None")
  1363. def setPackages(self, packages):
  1364. def p2str(param):
  1365. (packageName, description) = param
  1366. text = packageName
  1367. if description:
  1368. text += " (%s)" % description
  1369. return text
  1370. if packages:
  1371. pckgs = map(p2str, packages)
  1372. self.packages.setText("\n".join(pckgs))
  1373. else:
  1374. self.packages.setText("Unknown")
  1375. def setMaintainer(self, maintainer):
  1376. if maintainer:
  1377. # Remove email address
  1378. idx = maintainer.find("<")
  1379. if idx >= 0:
  1380. maintainer = maintainer[:idx]
  1381. self.maintainer.setText(maintainer.strip())
  1382. else:
  1383. self.maintainer.setText("None")
  1384. def setupDescription(self, chipDescription):
  1385. self.chipName.setText(chipDescription.description)
  1386. self.setComment(chipDescription.comment)
  1387. self.setPackages(chipDescription.packages)
  1388. self.setMaintainer(chipDescription.maintainer)
  1389. def setChipLayout(self, asciiArtLayout):
  1390. if asciiArtLayout:
  1391. self.zifLayout.setText(asciiArtLayout)
  1392. self.zifLayout.setFrameShape(QFrame.StyledPanel)
  1393. else:
  1394. self.zifLayout.clear()
  1395. self.zifLayout.setFrameShape(QFrame.NoFrame)
  1396. class ImageBufferWidget(BufferWidget):
  1397. def __init__(self, mainWindow, name):
  1398. BufferWidget.__init__(self, mainWindow, name)
  1399. self.browser = HexEdit(self)
  1400. self.layout().addWidget(self.browser, 0, 0)
  1401. def loadImage(self, image):
  1402. self.browser.setData(image)
  1403. def getRawData(self):
  1404. return self.browser.getData()
  1405. def setRawData(self, data):
  1406. if self.isReadOnly():
  1407. return False
  1408. self.loadImage(data)
  1409. return True
  1410. def clear(self):
  1411. self.loadImage(None)
  1412. class BitBufferWidget(BufferWidget):
  1413. def __init__(self, mainWindow, name, bitDescriptionsAttr):
  1414. BufferWidget.__init__(self, mainWindow, name)
  1415. self.bitDescriptionsAttr = bitDescriptionsAttr
  1416. self.bitsAreaScroll = QScrollArea(self)
  1417. self.layout().addWidget(self.bitsAreaScroll, 0, 0)
  1418. self.bitsAreaScroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
  1419. self.bitsAreaScroll.setWidgetResizable(False)
  1420. self.bitsArea = None
  1421. self.image = None
  1422. self.checkboxes = []
  1423. def __getBitDescription(self, bitNr):
  1424. if not self.mainWindow.currentChipDescription:
  1425. return ""
  1426. bitDescList = getattr(self.mainWindow.currentChipDescription,
  1427. self.bitDescriptionsAttr, None)
  1428. if not bitDescList:
  1429. return ""
  1430. bitDesc = filter(lambda x: x.bitNr == bitNr,
  1431. bitDescList)
  1432. if not bitDesc:
  1433. return ""
  1434. return bitDesc[0].description
  1435. def loadImage(self, image):
  1436. self.image = image
  1437. for checkbox in self.checkboxes:
  1438. checkbox.deleteLater()
  1439. self.checkboxes = []
  1440. if self.bitsArea:
  1441. self.bitsArea.deleteLater()
  1442. self.bitsArea = None
  1443. if not self.image:
  1444. return
  1445. self.bitsArea = QWidget(self)
  1446. self.bitsArea.setLayout(QGridLayout(self.bitsArea))
  1447. self.bitsArea.layout().addWidget(QLabel("Currently set %s:" % self.getName(),
  1448. self.bitsArea),
  1449. 0, 0)
  1450. self.hexView = QLabel(self.bitsArea)
  1451. font = self.hexView.font()
  1452. font.setBold(True)
  1453. self.hexView.setFont(font)
  1454. self.bitsArea.layout().addWidget(self.hexView, 0, 1)
  1455. for i in range(0, len(image) * 8):
  1456. desc = self.__getBitDescription(i)
  1457. if desc:
  1458. desc = " (%s)" % desc
  1459. checkbox = QCheckBox("bit %d%s" % (i, desc), self.bitsArea)
  1460. if byte2int(image[i // 8]) & bit(i % 8):
  1461. checkbox.setCheckState(Qt.Checked)
  1462. self.bitsArea.layout().addWidget(checkbox, 1 + i, 0, 1, 2)
  1463. checkbox.stateChanged.connect(self.__bitStateChanged)
  1464. self.checkboxes.append(checkbox)
  1465. self.__updateHexView()
  1466. def __updateHexView(self):
  1467. self.hexView.setText(bytes2hex(self.image))
  1468. self.bitsAreaScroll.setWidget(self.bitsArea)
  1469. def __bitStateChanged(self, unused):
  1470. self.image = ""
  1471. tmp = 0
  1472. i = 0
  1473. for checkbox in self.checkboxes:
  1474. if checkbox.checkState() == Qt.Checked:
  1475. tmp |= bit(i)
  1476. i += 1
  1477. if i == 8:
  1478. self.image += chr(tmp)
  1479. i = 0
  1480. tmp = 0
  1481. assert(i == 0)
  1482. self.__updateHexView()
  1483. def getRawData(self):
  1484. return self.image
  1485. def setRawData(self, data):
  1486. if self.isReadOnly():
  1487. return False
  1488. if len(data) > 32: # Don't want huge files
  1489. return False
  1490. self.loadImage(data)
  1491. return True
  1492. def clear(self):
  1493. self.loadImage(None)
  1494. class ProgmemBufferWidget(ImageBufferWidget):
  1495. def __init__(self, mainWindow):
  1496. ImageBufferWidget.__init__(self, mainWindow, "program memory")
  1497. def setDataWithIHexInterpreter(self, interp, readRaw):
  1498. return self.setRawData(interp.getProgmem(dontInterpretSections = readRaw))
  1499. class EEPROMBufferWidget(ImageBufferWidget):
  1500. def __init__(self, mainWindow):
  1501. ImageBufferWidget.__init__(self, mainWindow, "(E)EPROM memory")
  1502. def setDataWithIHexInterpreter(self, interp, readRaw):
  1503. return self.setRawData(interp.getEEPROM(dontInterpretSections = readRaw))
  1504. class RAMBufferWidget(ImageBufferWidget):
  1505. def __init__(self, mainWindow):
  1506. ImageBufferWidget.__init__(self, mainWindow, "RAM memory")
  1507. def setDataWithIHexInterpreter(self, interp, readRaw):
  1508. return self.setRawData(interp.getRAM(dontInterpretSections = readRaw))
  1509. class FuseBufferWidget(BitBufferWidget):
  1510. def __init__(self, mainWindow):
  1511. BitBufferWidget.__init__(self, mainWindow, "fuse bits", "fuseDesc")
  1512. def setDataWithIHexInterpreter(self, interp, readRaw):
  1513. return self.setRawData(interp.getFusebits(dontInterpretSections = readRaw))
  1514. class LockBufferWidget(BitBufferWidget):
  1515. def __init__(self, mainWindow):
  1516. BitBufferWidget.__init__(self, mainWindow, "lock bits", "lockbitDesc")
  1517. def setDataWithIHexInterpreter(self, interp, readRaw):
  1518. return self.setRawData(interp.getLockbits(dontInterpretSections = readRaw))
  1519. class BufferTabWidget(QTabWidget):
  1520. def __init__(self, mainWindow):
  1521. QTabWidget.__init__(self, mainWindow)
  1522. self.mainWindow = mainWindow
  1523. self.infoBuffer = InfoBufferWidget(mainWindow, "chip info")
  1524. self.progmemBuffer = ProgmemBufferWidget(mainWindow)
  1525. self.eepromBuffer = EEPROMBufferWidget(mainWindow)
  1526. self.fuseBuffer = FuseBufferWidget(mainWindow)
  1527. self.lockBuffer = LockBufferWidget(mainWindow)
  1528. self.ramBuffer = RAMBufferWidget(mainWindow)
  1529. self.setTabPosition(self.South)
  1530. self.__addBufferTab(self.infoBuffer, readOnly=True)
  1531. self.removeAll()
  1532. def __addBufferTab(self, bufferWidget, readOnly=False):
  1533. self.addTab(bufferWidget, bufferWidget.getName())
  1534. bufferWidget.setReadOnly(readOnly)
  1535. bufferWidget.setAvailable(True)
  1536. def __removeBufferTab(self, bufferWidget):
  1537. self.removeTab(self.indexOf(bufferWidget))
  1538. bufferWidget.clear()
  1539. bufferWidget.setAvailable(False)
  1540. def __removeAll(self):
  1541. self.__removeBufferTab(self.progmemBuffer)
  1542. self.__removeBufferTab(self.eepromBuffer)
  1543. self.__removeBufferTab(self.fuseBuffer)
  1544. self.__removeBufferTab(self.lockBuffer)
  1545. self.__removeBufferTab(self.ramBuffer)
  1546. def removeAll(self):
  1547. self.__removeAll()
  1548. def setupBuffers(self, chipSupportFlags):
  1549. prevSelect = self.getCurrentBuffer()
  1550. self.__removeAll()
  1551. for (bufferWidget, flagsMask) in (
  1552. (self.progmemBuffer, Chip.SUPPORT_PROGMEMREAD | Chip.SUPPORT_PROGMEMWRITE),
  1553. (self.eepromBuffer, Chip.SUPPORT_EEPROMREAD | Chip.SUPPORT_EEPROMWRITE),
  1554. (self.fuseBuffer, Chip.SUPPORT_FUSEREAD | Chip.SUPPORT_FUSEWRITE),
  1555. (self.lockBuffer, Chip.SUPPORT_LOCKREAD | Chip.SUPPORT_LOCKWRITE),
  1556. (self.ramBuffer, Chip.SUPPORT_RAMREAD | Chip.SUPPORT_RAMWRITE)):
  1557. if chipSupportFlags & flagsMask:
  1558. self.__addBufferTab(bufferWidget)
  1559. if prevSelect and prevSelect.isAvailable():
  1560. self.setCurrentIndex(self.indexOf(prevSelect))
  1561. def loadBuffers(self, images):
  1562. try:
  1563. self.progmemBuffer.loadImage(images["progmem"])
  1564. except KeyError:
  1565. pass # Ignore
  1566. try:
  1567. self.eepromBuffer.loadImage(images["eeprom"])
  1568. except KeyError:
  1569. pass # Ignore
  1570. try:
  1571. self.fuseBuffer.loadImage(images["fusebits"])
  1572. except KeyError:
  1573. pass # Ignore
  1574. try:
  1575. self.lockBuffer.loadImage(images["lockbits"])
  1576. except KeyError:
  1577. pass # Ignore
  1578. try:
  1579. self.ramBuffer.loadImage(images["ram"])
  1580. except KeyError:
  1581. pass # Ignore
  1582. def verifyBuffers(self, images):
  1583. fail = False
  1584. for (imageName, bufferWidget) in (("progmem", self.progmemBuffer),
  1585. ("eeprom", self.eepromBuffer),
  1586. ("fusebits", self.fuseBuffer),
  1587. ("ram", self.ramBuffer)):
  1588. try:
  1589. image = images[imageName]
  1590. except KeyError:
  1591. continue
  1592. bufImage = bufferWidget.getRawData()
  1593. if not bufImage:
  1594. if not image:
  1595. # Both images are empty. Go on...
  1596. continue
  1597. self.mainWindow.console.showMessage(
  1598. "Chip verify of %s FAILED! "
  1599. "There is no data in the "
  1600. "%s buffer. First load data into "
  1601. "the buffer tab, please.\n" %\
  1602. (bufferWidget.getName(),
  1603. bufferWidget.getName()),
  1604. bold=True)
  1605. fail = True
  1606. continue
  1607. if len(bufImage) > len(image):
  1608. self.mainWindow.console.showMessage(
  1609. "Chip verify of %s FAILED! "
  1610. "Buffer data is larger than "
  1611. "chip memory.\n" %\
  1612. bufferWidget.getName(),
  1613. bold=True)
  1614. fail = True
  1615. continue
  1616. compareSize = min(len(image), len(bufImage))
  1617. if len(image) != len(bufImage):
  1618. self.mainWindow.console.showMessage(
  1619. "%s: Only comparing the first 0x%X bytes due "
  1620. "to a mismatch of the buffer size (0x%X) "
  1621. "with the actual device image size (0x%X).\n" %\
  1622. (bufferWidget.getName(), compareSize,
  1623. len(bufImage), len(image)))
  1624. if bufImage[:compareSize] != image[:compareSize]:
  1625. self.mainWindow.console.showMessage(
  1626. "Chip verify of %s FAILED! "
  1627. "Image data mismatch.\n" %\
  1628. bufferWidget.getName(),
  1629. bold=True)
  1630. fail = True
  1631. continue
  1632. if fail:
  1633. self.mainWindow.console.setStatus(Console.STAT_ERROR)
  1634. else:
  1635. self.mainWindow.console.showMessage("Chip verify succeed\n", bold=True)
  1636. self.mainWindow.console.setStatus(Console.STAT_OK)
  1637. return not fail
  1638. def getCurrentBuffer(self):
  1639. return self.currentWidget()
  1640. class ChipSelectDialog(QDialog):
  1641. ALL_VENDORS = "--- All vendors ---"
  1642. def __init__(self, parent):
  1643. QDialog.__init__(self, parent)
  1644. self.setWindowTitle("Select chip")
  1645. self.setLayout(QGridLayout(self))
  1646. groupBox = QGroupBox("Chip type", self)
  1647. groupBox.setLayout(QGridLayout(groupBox))
  1648. self.allRadio = QRadioButton("All types", groupBox)
  1649. self.allRadio.setChecked(Qt.Checked)
  1650. groupBox.layout().addWidget(self.allRadio, 0, 0)
  1651. self.mcuRadio = QRadioButton("Microcontrollers", groupBox)
  1652. groupBox.layout().addWidget(self.mcuRadio, 1, 0)
  1653. self.epromRadio = QRadioButton("EPROMs", groupBox)
  1654. groupBox.layout().addWidget(self.epromRadio, 2, 0)
  1655. self.eepromRadio = QRadioButton("EEPROMs", groupBox)
  1656. groupBox.layout().addWidget(self.eepromRadio, 3, 0)
  1657. self.galRadio = QRadioButton("PALs / GALs", groupBox)
  1658. groupBox.layout().addWidget(self.galRadio, 4, 0)
  1659. self.sramRadio = QRadioButton("Static RAM", groupBox)
  1660. groupBox.layout().addWidget(self.sramRadio, 5, 0)
  1661. self.logicRadio = QRadioButton("Logic chips", groupBox)
  1662. groupBox.layout().addWidget(self.logicRadio, 6, 0)
  1663. self.showBroken = QCheckBox("Show broken implementations", groupBox)
  1664. groupBox.layout().addWidget(self.showBroken, 7, 0)
  1665. self.layout().addWidget(groupBox, 0, 0, 2, 2)
  1666. l = QLabel("Vendor:", self)
  1667. self.layout().addWidget(l, 0, 2, 1, 2)
  1668. self.vendorList = QListWidget(self)
  1669. self.layout().addWidget(self.vendorList, 1, 2, 1, 2)
  1670. l = QLabel("Chip:", self)
  1671. self.layout().addWidget(l, 0, 4, 1, 2)
  1672. self.chipList = QListWidget(self)
  1673. self.layout().addWidget(self.chipList, 1, 4, 1, 2)
  1674. self.okButton = QPushButton("&Ok", self)
  1675. self.layout().addWidget(self.okButton, 2, 0, 1, 3)
  1676. self.cancelButton = QPushButton("&Cancel", self)
  1677. self.layout().addWidget(self.cancelButton, 2, 3, 1, 3)
  1678. self.okButton.released.connect(self.accept)
  1679. self.cancelButton.released.connect(self.reject)
  1680. self.vendorList.itemSelectionChanged.connect(self.vendorSelectionChanged)
  1681. self.chipList.itemSelectionChanged.connect(self.chipSelectionChanged)
  1682. self.chipList.itemDoubleClicked.connect(self.accept)
  1683. self.showBroken.stateChanged.connect(self.typeToggled)
  1684. for radio in (self.allRadio, self.mcuRadio, self.epromRadio,
  1685. self.eepromRadio, self.galRadio,
  1686. self.sramRadio, self.logicRadio):
  1687. radio.toggled.connect(self.typeToggled)
  1688. self.__updateVendorList()
  1689. self.__updateChipList()
  1690. def __updateVendorList(self):
  1691. previousVendor = self.__getSelectedVendor()
  1692. selType = self.__getSelectedChipType()
  1693. vendors = getRegisteredVendors()
  1694. self.vendorList.clear()
  1695. QListWidgetItem(self.ALL_VENDORS, self.vendorList)
  1696. for vendorName in vendors.keys():
  1697. descriptors = vendors[vendorName]
  1698. if self.showBroken.checkState() != Qt.Checked:
  1699. descriptors = filter(lambda d: not d.broken,
  1700. descriptors)
  1701. descriptors = filter(lambda d: (d.chipType == selType or selType == -1) and\
  1702. (d.chipType != ChipDescription.TYPE_INTERNAL),
  1703. descriptors)
  1704. if not descriptors:
  1705. continue
  1706. item = QListWidgetItem(vendorName, self.vendorList)
  1707. item.setData(Qt.UserRole, descriptors)
  1708. self.vendorList.sortItems()
  1709. if previousVendor:
  1710. items = self.vendorList.findItems(previousVendor, Qt.MatchExactly)
  1711. if len(items) == 1:
  1712. self.vendorList.setCurrentItem(items[0])
  1713. else:
  1714. self.vendorList.setCurrentRow(0)
  1715. else:
  1716. self.vendorList.setCurrentRow(0)
  1717. def __descriptorText(self, descriptor):
  1718. text = descriptor.description
  1719. if not descriptor.maintainer:
  1720. text += " (Orphaned)"
  1721. return text
  1722. def __updateChipList(self):
  1723. previousChip = self.getSelectedChip()
  1724. selType = self.__getSelectedChipType()
  1725. selVendor = self.__getSelectedVendor()
  1726. self.chipList.clear()
  1727. for descriptor in getRegisteredChips():
  1728. if descriptor.broken and\
  1729. self.showBroken.checkState() != Qt.Checked:
  1730. continue
  1731. if descriptor.chipType != selType and selType != -1:
  1732. continue
  1733. if descriptor.chipType == ChipDescription.TYPE_INTERNAL:
  1734. continue
  1735. if selVendor != self.ALL_VENDORS and selVendor not in descriptor.chipVendors:
  1736. continue
  1737. item = QListWidgetItem(self.__descriptorText(descriptor),
  1738. self.chipList)
  1739. item.setData(Qt.UserRole, descriptor)
  1740. self.chipList.sortItems()
  1741. if previousChip:
  1742. items = self.chipList.findItems(self.__descriptorText(previousChip),
  1743. Qt.MatchExactly)
  1744. if len(items) == 1:
  1745. self.chipList.setCurrentItem(items[0])
  1746. else:
  1747. self.chipList.setCurrentRow(0)
  1748. else:
  1749. self.chipList.setCurrentRow(0)
  1750. def typeToggled(self, unused):
  1751. self.__updateVendorList()
  1752. self.__updateChipList()
  1753. def vendorSelectionChanged(self):
  1754. self.__updateChipList()
  1755. def chipSelectionChanged(self):
  1756. item = self.chipList.currentItem()
  1757. self.okButton.setEnabled(bool(item))
  1758. def __getSelectedVendor(self):
  1759. item = self.vendorList.currentItem()
  1760. if not item:
  1761. return None
  1762. return str(item.text())
  1763. def __getSelectedChipType(self):
  1764. # Returns ChipDescription.TYPE_... or -1 if all are selected
  1765. for (typeId, radioButton) in (
  1766. (ChipDescription.TYPE_MCU, self.mcuRadio),
  1767. (ChipDescription.TYPE_EPROM, self.epromRadio),
  1768. (ChipDescription.TYPE_EEPROM, self.eepromRadio),
  1769. (ChipDescription.TYPE_GAL, self.galRadio),
  1770. (ChipDescription.TYPE_SRAM, self.sramRadio),
  1771. (ChipDescription.TYPE_LOGIC, self.logicRadio)):
  1772. if radioButton.isChecked():
  1773. return typeId
  1774. assert(self.allRadio.isChecked())
  1775. return -1
  1776. def getSelectedChip(self):
  1777. item = self.chipList.currentItem()
  1778. if not item:
  1779. return None
  1780. chipDescription = item.data(Qt.UserRole)
  1781. return chipDescription
  1782. class StatusBar(QStatusBar):
  1783. def __init__(self, mainWindow):
  1784. QStatusBar.__init__(self, mainWindow)
  1785. class TopToolBar(QToolBar):
  1786. def __init__(self, mainWindow):
  1787. QToolBar.__init__(self, "Toolbar", mainWindow)
  1788. self.mainWindow = mainWindow
  1789. self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  1790. self.setup(0)
  1791. def setup(self, chipSupportFlags):
  1792. mainWindow = self.mainWindow
  1793. self.clear()
  1794. a = self.addAction(getIcon("open"), "Load buffer", mainWindow.loadBuffer)
  1795. a.setEnabled(chipSupportFlags != 0)
  1796. a = self.addAction(getIcon("save"), "Save buffer", mainWindow.saveBuffer)
  1797. a.setEnabled(chipSupportFlags != 0)
  1798. self.addSeparator()
  1799. self.addAction(getIcon("chip"), "Run logic tester", mainWindow.startUnitest)
  1800. self.addAction(getIcon("chip"), "Select chip", mainWindow.selectChip)
  1801. self.addSeparator()
  1802. a = self.addAction(getIcon("up"), "Read chip", mainWindow.readChip)
  1803. a.setEnabled(chipSupportFlags != 0)
  1804. a = self.addAction(getIcon("verify"), "Verify all", mainWindow.verifyChip)
  1805. a.setEnabled(chipSupportFlags != 0)
  1806. class RightToolBar(QToolBar):
  1807. def __init__(self, mainWindow):
  1808. QToolBar.__init__(self, "Toolbar", mainWindow)
  1809. self.mainWindow = mainWindow
  1810. self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  1811. self.setup(0)
  1812. def setup(self, chipSupportFlags):
  1813. mainWindow = self.mainWindow
  1814. self.clear()
  1815. if chipSupportFlags & Chip.SUPPORT_ERASE:
  1816. self.addAction(getIcon("erase"), "Erase", mainWindow.eraseChip)
  1817. if chipSupportFlags & Chip.SUPPORT_PROGMEMWRITE:
  1818. self.addAction(getIcon("memory"), "Write progmem", mainWindow.writeChipProgmem)
  1819. if chipSupportFlags & Chip.SUPPORT_EEPROMWRITE:
  1820. self.addAction(getIcon("memory"), "Write EPROM", mainWindow.writeChipEeprom)
  1821. if chipSupportFlags & Chip.SUPPORT_FUSEWRITE:
  1822. self.addAction(getIcon("memory"), "Write fuses", mainWindow.writeChipFuses)
  1823. if chipSupportFlags & Chip.SUPPORT_RAMWRITE:
  1824. self.addAction(getIcon("memory"), "Write RAM", mainWindow.writeRam)
  1825. if chipSupportFlags & Chip.SUPPORT_LOCKWRITE:
  1826. self.addAction(getIcon("lock"), "Write lockbits", mainWindow.writeChipLockbits)
  1827. if chipSupportFlags & Chip.SUPPORT_TEST:
  1828. self.addAction(getIcon("test"), "Run unit-test", mainWindow.runTest)
  1829. class AutorunWidget(QDockWidget):
  1830. def __init__(self, mainWindow):
  1831. QDockWidget.__init__(self, "Autorun", mainWindow)
  1832. self.mainWindow = mainWindow
  1833. self.running = False
  1834. self.currentAction = -1
  1835. self.setFeatures(self.DockWidgetMovable | self.DockWidgetFloatable)
  1836. self.setup(0)
  1837. def __addCheckBox(self, row, condition, text, checked):
  1838. if condition:
  1839. checkbox = QCheckBox(text, self.widget())
  1840. if checked:
  1841. checkbox.setCheckState(Qt.Checked)
  1842. self.widget().layout().addWidget(checkbox, row, 0)
  1843. row += 1
  1844. return (checkbox, row)
  1845. return (None, row)
  1846. def setup(self, chipSupportFlags):
  1847. self.setWidget(QWidget(self))
  1848. self.widget().show()
  1849. self.widget().setLayout(QGridLayout(self.widget()))
  1850. row = 0
  1851. (self.testCheckBox, row) = self.__addCheckBox(row,
  1852. chipSupportFlags & Chip.SUPPORT_TEST,
  1853. "Run unit-test", True)
  1854. (self.eraseCheckBox, row) = self.__addCheckBox(row,
  1855. chipSupportFlags & Chip.SUPPORT_ERASE,
  1856. "Erase", True)
  1857. (self.progmemCheckBox, row) = self.__addCheckBox(row,
  1858. chipSupportFlags & Chip.SUPPORT_PROGMEMWRITE,
  1859. "Write program memory", True)
  1860. (self.eepromCheckBox, row) = self.__addCheckBox(row,
  1861. chipSupportFlags & Chip.SUPPORT_EEPROMWRITE,
  1862. "Write (E)EPROM", True)
  1863. (self.ramCheckBox, row) = self.__addCheckBox(row,
  1864. chipSupportFlags & Chip.SUPPORT_RAMWRITE,
  1865. "Write RAM", True)
  1866. (self.fusesCheckBox, row) = self.__addCheckBox(row,
  1867. chipSupportFlags & Chip.SUPPORT_FUSEWRITE,
  1868. "Write fuses", True)
  1869. (self.verifyCheckBox, row) = self.__addCheckBox(row,
  1870. chipSupportFlags != 0,
  1871. "Verify selected memories", True)
  1872. (self.lockbitsCheckBox, row) = self.__addCheckBox(row,
  1873. chipSupportFlags & Chip.SUPPORT_LOCKWRITE,
  1874. "Write lock bits", False)
  1875. self.runButton = None
  1876. if chipSupportFlags != 0:
  1877. self.runButton = QPushButton("Run", self.widget())
  1878. self.runButton.setIconSize(QSize(32, 32))
  1879. self.runButton.setIcon(getIcon("run"))
  1880. self.widget().layout().addWidget(self.runButton, row, 0)
  1881. row += 1
  1882. self.runButton.released.connect(self.runNextChip)
  1883. self.widget().layout().setRowStretch(row, 99)
  1884. def isRunning(self):
  1885. return self.running
  1886. def abortRunWithMessage(self):
  1887. self.abortRun(withMessage=True)
  1888. def abortRun(self, withMessage=False):
  1889. if withMessage:
  1890. QMessageBox.critical(self, "Aborting autorun",
  1891. "One action failed. Aborting autorun.\n"
  1892. "See console messages for details.")
  1893. self.running = False
  1894. self.currentAction = -1;
  1895. self.mainWindow.guiUpdateEnable()
  1896. def runNextChip(self):
  1897. self.running = True
  1898. self.currentAction = 0
  1899. res = QMessageBox.information(self, "Autorun - Please insert chip",
  1900. "Please insert a new %s chip into the ZIF socket "
  1901. "and press Ok to perform the operations..." %\
  1902. self.mainWindow.currentChipDescription.description,
  1903. QMessageBox.Ok | QMessageBox.Cancel,
  1904. QMessageBox.Ok)
  1905. if res != QMessageBox.Ok:
  1906. self.abortRun()
  1907. return
  1908. self.runNextAction()
  1909. def runNextAction(self):
  1910. assert(self.currentAction >= 0)
  1911. action = 0
  1912. if self.testCheckBox:
  1913. if self.currentAction == action:
  1914. if self.__runAction(self.mainWindow.runTest,
  1915. self.testCheckBox,
  1916. "Run unit-test"):
  1917. return
  1918. action += 1
  1919. if self.eraseCheckBox:
  1920. if self.currentAction == action:
  1921. if self.__runAction(self.mainWindow.eraseChip,
  1922. self.eraseCheckBox,
  1923. "Erase"):
  1924. return
  1925. action += 1
  1926. if self.progmemCheckBox:
  1927. if self.currentAction == action:
  1928. if self.__runAction(self.mainWindow.writeChipProgmem,
  1929. self.progmemCheckBox,
  1930. "Write program memory"):
  1931. return
  1932. action += 1
  1933. if self.eepromCheckBox:
  1934. if self.currentAction == action:
  1935. if self.__runAction(self.mainWindow.writeChipEeprom,
  1936. self.eepromCheckBox,
  1937. "Write (E)EPROM"):
  1938. return
  1939. action += 1
  1940. if self.ramCheckBox:
  1941. if self.currentAction == action:
  1942. if self.__runAction(self.mainWindow.writeRam,
  1943. self.ramCheckBox,
  1944. "Write RAM"):
  1945. return
  1946. action += 1
  1947. if self.fusesCheckBox:
  1948. if self.currentAction == action:
  1949. if self.__runAction(self.mainWindow.writeChipFuses,
  1950. self.fusesCheckBox,
  1951. "Write fuses"):
  1952. return
  1953. action += 1
  1954. if self.verifyCheckBox:
  1955. if self.currentAction == action:
  1956. if self.__runAction(self.__verifySelectedMemories,
  1957. self.verifyCheckBox,
  1958. "Verify selected memories"):
  1959. return
  1960. action += 1
  1961. if self.lockbitsCheckBox:
  1962. if self.currentAction == action:
  1963. if self.__runAction(self.mainWindow.writeChipLockbits,
  1964. self.lockbitsCheckBox,
  1965. "Write lock bits"):
  1966. return
  1967. action += 1
  1968. self.runNextChip()
  1969. def __runAction(self, function, checkbox, actionName):
  1970. self.currentAction += 1
  1971. if checkbox.checkState() == Qt.Checked:
  1972. self.mainWindow.console.showMessage(
  1973. "Running action: %s\n" % actionName, bold=True)
  1974. if not function():
  1975. self.abortRun(withMessage=True)
  1976. return True
  1977. return False
  1978. def __verifySelectedMemories(self):
  1979. def checked(cb):
  1980. return cb and (cb.checkState() == Qt.Checked)
  1981. return self.mainWindow.verifySelectedMemories(
  1982. verifyProgmem = checked(self.progmemCheckBox),
  1983. verifyEEPROM = checked(self.eepromCheckBox),
  1984. verifyFuse = checked(self.fusesCheckBox),
  1985. verifyRAM = checked(self.ramCheckBox))
  1986. class ProgrammerSelectDialog(QDialog):
  1987. def __init__(self, parent=None):
  1988. QDialog.__init__(self, parent)
  1989. self.setWindowTitle("Select programmer device")
  1990. self.setLayout(QGridLayout(self))
  1991. self.deviceList = QListWidget(self)
  1992. self.layout().addWidget(self.deviceList, 0, 0, 1, 2)
  1993. self.rescanButton = QPushButton("&Rescan USB busses", self)
  1994. self.layout().addWidget(self.rescanButton, 1, 0, 1, 2)
  1995. self.okButton = QPushButton("&OK", self)
  1996. self.layout().addWidget(self.okButton, 2, 0)
  1997. self.cancelButton = QPushButton("&Cancel", self)
  1998. self.layout().addWidget(self.cancelButton, 2, 1)
  1999. self.rescan()
  2000. self.deviceList.currentRowChanged.connect(self.selectionChanged)
  2001. self.deviceList.itemDoubleClicked.connect(self.accept)
  2002. self.okButton.released.connect(self.accept)
  2003. self.cancelButton.released.connect(self.reject)
  2004. self.rescanButton.released.connect(self.rescan)
  2005. def rescan(self):
  2006. self.deviceList.clear()
  2007. for foundDev in TOP.findDevices():
  2008. text = "%s (%s)" % (foundDev.toptype,
  2009. foundDev.devIdentifier)
  2010. item = QListWidgetItem(text, self.deviceList)
  2011. item.setData(Qt.UserRole, foundDev.devIdentifier)
  2012. self.deviceList.setCurrentRow(0)
  2013. def getIdentifier(self):
  2014. item = self.deviceList.currentItem()
  2015. if not item:
  2016. return None
  2017. return item.data(Qt.UserRole)
  2018. def selectionChanged(self, unused):
  2019. if self.deviceList.currentItem():
  2020. self.okButton.setEnabled(True)
  2021. else:
  2022. self.okButton.setEnabled(False)
  2023. class Operation(object):
  2024. OP_NONE = 0
  2025. OP_SHUTDOWN = 1
  2026. OP_INITCHIP = 2
  2027. OP_READALL = 3
  2028. OP_ERASE = 4
  2029. OP_WRITEPROG = 5
  2030. OP_WRITEEPROM = 6
  2031. OP_WRITEFUSE = 7
  2032. OP_WRITELOCK = 8
  2033. OP_WRITERAM = 9
  2034. OP_TEST = 10
  2035. OP_VERIFY = 11
  2036. OP_RAWCOMMAND = 12
  2037. OP_SYNCHRONOUS = 13
  2038. def __init__(self, op, hwTask, hwTaskParam=None):
  2039. self.op = op
  2040. self.hwTask = hwTask
  2041. self.hwTaskParam = hwTaskParam
  2042. self.returnValue = None
  2043. self.failed = False
  2044. self.finished = False
  2045. class MainWindow(QMainWindow):
  2046. def __init__(self, parent=None):
  2047. QMainWindow.__init__(self, parent)
  2048. self.setWindowTitle("TOPrammer v%s - Open Source programming suite" % VERSION)
  2049. self.guiDisable = 0
  2050. self.chip = None # Chip instance
  2051. self.currentChipDescription = None
  2052. self.previousRawCommand = ""
  2053. self.setStatusBar(StatusBar(self))
  2054. self.topToolBar = TopToolBar(self)
  2055. self.rightToolBar = RightToolBar(self)
  2056. self.addToolBar(Qt.TopToolBarArea, self.topToolBar)
  2057. self.addToolBar(Qt.RightToolBarArea, self.rightToolBar)
  2058. self.setMenuBar(QMenuBar(self))
  2059. menu = QMenu("&File", self)
  2060. menu.addAction("&Load buffer...", self.loadBuffer)
  2061. menu.addAction("&Save buffer...", self.saveBuffer)
  2062. menu.addSeparator()
  2063. menu.addAction("&Exit", self.close)
  2064. self.menuBar().addMenu(menu)
  2065. self.runMenu = QMenu("&Run", self)
  2066. self.setupRunMenu(0)
  2067. self.menuBar().addMenu(self.runMenu)
  2068. menu = QMenu("&Programmer", self)
  2069. menu.addAction("&Universal logic tester...", self.startUnitest)
  2070. menu.addSeparator()
  2071. menu.addAction("Select &programmer...", self.selectProgrammer)
  2072. menu.addAction("&Send raw command...", self.sendRawCommand)
  2073. self.menuBar().addMenu(menu)
  2074. menu = QMenu("&Help", self)
  2075. menu.addAction("&About", self.showAbout)
  2076. self.menuBar().addMenu(menu)
  2077. self.bufferTab = BufferTabWidget(self)
  2078. self.setCentralWidget(self.bufferTab)
  2079. self.console = Console(self)
  2080. self.addDockWidget(Qt.BottomDockWidgetArea, self.console)
  2081. self.autorun = AutorunWidget(self)
  2082. self.addDockWidget(Qt.LeftDockWidgetArea, self.autorun)
  2083. self.hwThread = HwThread(self)
  2084. self.threadRunning = False
  2085. self.queuedOps = []
  2086. self.runningOps = {}
  2087. def setupRunMenu(self, chipSupportFlags):
  2088. menu = self.runMenu
  2089. menu.clear()
  2090. menu.addAction("&Select chip", self.selectChip)
  2091. menu.addSeparator()
  2092. a = menu.addAction("&Read chip", self.readChip)
  2093. a.setEnabled(chipSupportFlags != 0)
  2094. a = menu.addAction("&Erase", self.eraseChip)
  2095. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_ERASE))
  2096. a = menu.addAction("Write &program memory", self.writeChipProgmem)
  2097. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_PROGMEMWRITE))
  2098. a = menu.addAction("Write (E)EP&ROM", self.writeChipEeprom)
  2099. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_EEPROMWRITE))
  2100. a = menu.addAction("Write &fuses", self.writeChipFuses)
  2101. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_FUSEWRITE))
  2102. a = menu.addAction("Write &lock bits", self.writeChipLockbits)
  2103. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_LOCKWRITE))
  2104. a = menu.addAction("Write R&AM", self.writeRam)
  2105. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_RAMWRITE))
  2106. a = menu.addAction("Run &Unit-test", self.runTest)
  2107. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_TEST))
  2108. a = menu.addAction("&Verify whole chip", self.verifyChip)
  2109. a.setEnabled(chipSupportFlags != 0)
  2110. def event(self, e):
  2111. if e.type() == EVENT_HWTHREAD:
  2112. self.hwThread.handleMessageQueue()
  2113. e.accept()
  2114. return True
  2115. return QMainWindow.event(self, e)
  2116. def closeEvent(self, e):
  2117. if self.threadRunning:
  2118. res = QMessageBox.critical(self, "Task running",
  2119. "A hardware access task is running.\n\n"
  2120. "'Cancel' the close request and continue, or\n"
  2121. "'Abort' the task an quit the application?",
  2122. QMessageBox.Cancel | QMessageBox.Abort,
  2123. QMessageBox.Cancel)
  2124. if res == QMessageBox.Abort:
  2125. e.accept()
  2126. # Force quit
  2127. QApplication.exit(1)
  2128. return
  2129. e.ignore()
  2130. return
  2131. self.threadRunning = False
  2132. self.hwThread.killThread()
  2133. e.accept()
  2134. def showAbout(self):
  2135. QMessageBox.information(self, "About TOPrammer",
  2136. "Copyright (c) Michael Buesch <m@bues.ch>")
  2137. def startUnitest(self):
  2138. self.bufferTab.setupBuffers(0)
  2139. self.bufferTab.infoBuffer.clear()
  2140. self.autorun.setup(0)
  2141. self.guiDisable += 1
  2142. self.console.blockStatusUpdate()
  2143. try:
  2144. dlg = UnitestDialog(self)
  2145. dlg.exec_()
  2146. except (TOPException), e:
  2147. self.console.showMessage("Failed to start Unitest: %s\n" % str(e),
  2148. bold=True)
  2149. self.console.unblockStatusUpdate()
  2150. self.guiDisable -= 1
  2151. self.guiUpdateEnable()
  2152. self.runOperation(Operation(Operation.OP_SHUTDOWN,
  2153. HwThread.TASK_SHUTDOWN))
  2154. def selectProgrammer(self):
  2155. dlg = ProgrammerSelectDialog(self)
  2156. if dlg.exec_() != QDialog.Accepted:
  2157. return
  2158. devIdentifier = dlg.getIdentifier()
  2159. self.runOperationSync(HwThread.TASK_SHUTDOWN)
  2160. self.hwThread.setDevice(devIdentifier)
  2161. if self.currentChipDescription:
  2162. self.runOperation(Operation(Operation.OP_INITCHIP,
  2163. HwThread.TASK_INITCHIP,
  2164. self.currentChipDescription.chipID))
  2165. def sendRawCommand(self):
  2166. (string, ok) = QInputDialog.getText(self,
  2167. "Send raw command to programmer",
  2168. "Enter raw command to send, in " +\
  2169. "hex format (AABB1122...).\n" +\
  2170. "WARNING: The programmer will malfunction on invalid commands.",
  2171. QLineEdit.Normal,
  2172. self.previousRawCommand)
  2173. if not ok:
  2174. return
  2175. string = str(string).strip().upper()
  2176. string = stringRemoveChars(string, " \t\r\n")
  2177. if stringRemoveChars(string, "0123456789ABCDEF"):
  2178. QMessageBox.critical(self, "Invalid characters",
  2179. "Invalid characters in raw command string.\n" +\
  2180. "Only hex characters 0-9,a-f allowed.")
  2181. return
  2182. if len(string) % 2 != 0 or len(string) // 2 > 64:
  2183. QMessageBox.critical(self, "Invalid length",
  2184. "Invalid command length. Length must be even " +\
  2185. "and smaller or equal to 64 bytes.")
  2186. return
  2187. self.previousRawCommand = string
  2188. command = hex2bin(string)
  2189. if len(command) == 0:
  2190. return
  2191. self.runOperation(Operation(Operation.OP_RAWCOMMAND,
  2192. HwThread.TASK_GENERICTOPCALL,
  2193. GenericTopCall("top.hw.runCommandSync(...)", command)))
  2194. def loadBuffer(self):
  2195. bufWidget = self.bufferTab.getCurrentBuffer()
  2196. data = None
  2197. if not bufWidget:
  2198. return
  2199. if bufWidget.isReadOnly():
  2200. QMessageBox.critical(self, "Buffer is read only",
  2201. "Cannot load data into the %s buffer.\n"
  2202. "The buffer is read-only." %\
  2203. bufWidget.getName())
  2204. return
  2205. (fn, selectedFilter) = QFileDialog.getOpenFileName(self,
  2206. "%s - open file" % bufWidget.getName(),
  2207. "",
  2208. "Autodetect file format (*);;"
  2209. "Intel hex file (*.ihex *.hex);;"
  2210. "Hex file with ASCII dump (*.ahex);;"
  2211. "Binary file (*.bin)")
  2212. if not fn:
  2213. return
  2214. extensions = str(selectedFilter).split("(")[1].\
  2215. split(")")[0].replace("*", "").strip().split()
  2216. try:
  2217. dataIn = open(fn, "rb").read()
  2218. except (IOError), e:
  2219. QMessageBox.critical(self, "Failed to read file",
  2220. "Failed to read %s:\n%s" %\
  2221. (str(fn), str(e.strerror)))
  2222. return
  2223. try:
  2224. if ".bin" in extensions:
  2225. handler = IO_binary()
  2226. elif ".ahex" in extensions:
  2227. handler = IO_ahex()
  2228. elif ".ihex" in extensions:
  2229. handler = IO_ihex()
  2230. elif not extensions: # auto
  2231. handler = IO_autodetect(dataIn)()
  2232. else:
  2233. assert(0)
  2234. if isinstance(handler, IO_ihex):
  2235. interp = self.chip.getIHexInterpreter()
  2236. interp.interpret(dataIn)
  2237. if interp.cumulativeSupported():
  2238. res = QMessageBox.question(self,
  2239. "Parse IHEX sections?",
  2240. "This IHEX file might contain sections for "
  2241. "the different memory areas (progmem, eeprom, etc...).\n"
  2242. "\n"
  2243. "Should the sections be interpreted?\n"
  2244. "\n"
  2245. "If 'Yes' is selected, only the section corresponding "
  2246. "to the current buffer is extracted from the IHEX file.\n"
  2247. "If 'No' is selected, the IHEX file will be read "
  2248. "in raw mode and all of its data will be "
  2249. "put into the current buffer.",
  2250. QMessageBox.Yes | QMessageBox.No,
  2251. QMessageBox.Yes)
  2252. readRaw = (res != QMessageBox.Yes)
  2253. else:
  2254. readRaw = True
  2255. ok = bufWidget.setDataWithIHexInterpreter(interp, readRaw)
  2256. else:
  2257. ok = bufWidget.setRawData(handler.toBinary(dataIn))
  2258. if not ok:
  2259. QMessageBox.critical(self, "Failed to load data",
  2260. "Failed to load the file into the buffer")
  2261. except (TOPException), e:
  2262. QMessageBox.critical(self, "Failed to convert data",
  2263. "Failed to convert the input file data to binary\n%s" % str(e))
  2264. return
  2265. def saveBuffer(self):
  2266. bufWidget = self.bufferTab.getCurrentBuffer()
  2267. if not bufWidget:
  2268. return
  2269. data = bufWidget.getRawData()
  2270. if not data:
  2271. return
  2272. (fn, selectedFilter) = QFileDialog.getSaveFileName(self,
  2273. "%s - save file" % bufWidget.getName(),
  2274. "",
  2275. "Intel hex file (*.ihex *.hex);;"
  2276. "Hex file with ASCII dump (*.ahex);;"
  2277. "Binary file (*)")
  2278. if not fn:
  2279. return
  2280. extensions = str(selectedFilter).split("(")[1].\
  2281. split(")")[0].replace("*", "").strip().split()
  2282. if not extensions:
  2283. extensions = [ "" ]
  2284. if not '.' in fn or\
  2285. not '.' + fn.split('.')[-1] in extensions:
  2286. fn += extensions[0] # Default ext
  2287. if ".ihex" in extensions:
  2288. data = IO_ihex().fromBinary(data)
  2289. elif ".ahex" in extensions:
  2290. data = IO_ahex().fromBinary(data)
  2291. elif not extensions[0]:
  2292. data = IO_binary().fromBinary(data)
  2293. else:
  2294. assert(0)
  2295. try:
  2296. open(fn, "wb").write(data)
  2297. except (IOError), e:
  2298. QMessageBox.critical(self, "Failed to write file",
  2299. "Failed to write %s:\n%s" %\
  2300. (str(fn), str(e.strerror)))
  2301. return
  2302. def selectChip(self):
  2303. dlg = ChipSelectDialog(self)
  2304. if dlg.exec_() != QDialog.Accepted:
  2305. return
  2306. chipDescription = dlg.getSelectedChip()
  2307. if not chipDescription:
  2308. return
  2309. self.currentChipDescription = chipDescription
  2310. return self.runOperation(Operation(Operation.OP_INITCHIP,
  2311. HwThread.TASK_INITCHIP,
  2312. chipDescription.chipID))
  2313. def __makeReadCallChain(self, mayReadSig=True, mayReadProgmem=True,
  2314. mayReadEEPROM=True, mayReadFuse=True,
  2315. mayReadLockbits=True, mayReadRAM=True):
  2316. callChain = []
  2317. suppFlags = self.chip.getSupportFlags()
  2318. callChain.append(GenericTopCall("top.checkChip()",
  2319. name = "check"))
  2320. if mayReadSig and (suppFlags & Chip.SUPPORT_SIGREAD):
  2321. callChain.append(GenericTopCall("top.readSignature()",
  2322. name = "signature"))
  2323. if mayReadProgmem and (suppFlags & Chip.SUPPORT_PROGMEMREAD):
  2324. callChain.append(GenericTopCall("top.readProgmem()",
  2325. name = "progmem"))
  2326. if mayReadEEPROM and (suppFlags & Chip.SUPPORT_EEPROMREAD):
  2327. callChain.append(GenericTopCall("top.readEEPROM()",
  2328. name = "eeprom"))
  2329. if mayReadFuse and (suppFlags & Chip.SUPPORT_FUSEREAD):
  2330. callChain.append(GenericTopCall("top.readFuse()",
  2331. name = "fusebits"))
  2332. if mayReadLockbits and (suppFlags & Chip.SUPPORT_LOCKREAD):
  2333. callChain.append(GenericTopCall("top.readLockbits()",
  2334. name = "lockbits"))
  2335. if mayReadRAM and (suppFlags & Chip.SUPPORT_RAMREAD):
  2336. callChain.append(GenericTopCall("top.readRAM()",
  2337. name = "ram"))
  2338. return callChain
  2339. def __readCallChain_GetResultImages(self, callChain):
  2340. images = {}
  2341. for topCall in (callChain if callChain else []):
  2342. name = topCall.userData["name"]
  2343. if name in ("signature", "progmem", "eeprom",
  2344. "fusebits", "lockbits", "ram"):
  2345. images[name] = topCall.result
  2346. elif name == "check":
  2347. pass # Nothing to do
  2348. else:
  2349. assert(0)
  2350. return images
  2351. def readChip(self):
  2352. return self.runOperation(Operation(Operation.OP_READALL,
  2353. HwThread.TASK_GENERICTOPCALL,
  2354. self.__makeReadCallChain()))
  2355. def eraseChip(self):
  2356. return self.runOperation(Operation(Operation.OP_ERASE,
  2357. HwThread.TASK_GENERICTOPCALL,
  2358. GenericTopCall("top.eraseChip()")))
  2359. def writeChipProgmem(self):
  2360. bufferWidget = self.bufferTab.progmemBuffer
  2361. data = bufferWidget.getRawData()
  2362. if not bufferWidget.isAvailable() or not data:
  2363. QMessageBox.critical(self, "No program memory",
  2364. "No program memory available")
  2365. return False
  2366. return self.runOperation(Operation(Operation.OP_WRITEPROG,
  2367. HwThread.TASK_GENERICTOPCALL,
  2368. GenericTopCall("top.writeProgmem(...)", data)))
  2369. def writeChipEeprom(self):
  2370. bufferWidget = self.bufferTab.eepromBuffer
  2371. data = bufferWidget.getRawData()
  2372. if not bufferWidget.isAvailable() or not data:
  2373. QMessageBox.critical(self, "No (E)EPROM memory",
  2374. "No (E)EPROM memory available")
  2375. return False
  2376. return self.runOperation(Operation(Operation.OP_WRITEEPROM,
  2377. HwThread.TASK_GENERICTOPCALL,
  2378. GenericTopCall("top.writeEEPROM(...)", data)))
  2379. def writeChipFuses(self):
  2380. bufferWidget = self.bufferTab.fuseBuffer
  2381. data = bufferWidget.getRawData()
  2382. if not bufferWidget.isAvailable() or not data:
  2383. QMessageBox.critical(self, "No fuse bits",
  2384. "No fuse bits available")
  2385. return False
  2386. return self.runOperation(Operation(Operation.OP_WRITEFUSE,
  2387. HwThread.TASK_GENERICTOPCALL,
  2388. GenericTopCall("top.writeFuse(...)", data)))
  2389. def writeChipLockbits(self):
  2390. bufferWidget = self.bufferTab.lockBuffer
  2391. data = bufferWidget.getRawData()
  2392. if not bufferWidget.isAvailable() or not data:
  2393. QMessageBox.critical(self, "No lock bits",
  2394. "No lock bits available")
  2395. return False
  2396. return self.runOperation(Operation(Operation.OP_WRITELOCK,
  2397. HwThread.TASK_GENERICTOPCALL,
  2398. GenericTopCall("top.writeLockbits(...)", data)))
  2399. def writeRam(self):
  2400. bufferWidget = self.bufferTab.ramBuffer
  2401. data = bufferWidget.getRawData()
  2402. if not bufferWidget.isAvailable() or not data:
  2403. QMessageBox.critical(self, "No RAM memory",
  2404. "No RAM memory available")
  2405. return False
  2406. return self.runOperation(Operation(Operation.OP_WRITERAM,
  2407. HwThread.TASK_GENERICTOPCALL,
  2408. GenericTopCall("top.writeRAM(...)", data)))
  2409. def runTest(self):
  2410. return self.runOperation(Operation(Operation.OP_TEST,
  2411. HwThread.TASK_GENERICTOPCALL,
  2412. GenericTopCall("top.testChip()")))
  2413. def verifyChip(self):
  2414. return self.verifySelectedMemories() # defaults to "all".
  2415. def verifySelectedMemories(self, verifyProgmem=True,
  2416. verifyEEPROM=True,
  2417. verifyFuse=True,
  2418. verifyRAM=True):
  2419. callChain = self.__makeReadCallChain(
  2420. mayReadSig = False,
  2421. mayReadProgmem = verifyProgmem,
  2422. mayReadEEPROM = verifyEEPROM,
  2423. mayReadFuse = verifyFuse,
  2424. mayReadLockbits = False,
  2425. mayReadRAM = verifyRAM)
  2426. return self.runOperation(Operation(Operation.OP_VERIFY,
  2427. HwThread.TASK_GENERICTOPCALL,
  2428. callChain))
  2429. def guiUpdateEnable(self):
  2430. enable = not self.guiDisable and\
  2431. not self.threadRunning and\
  2432. not self.autorun.isRunning()
  2433. self.menuBar().setEnabled(enable)
  2434. self.topToolBar.setEnabled(enable)
  2435. self.rightToolBar.setEnabled(enable)
  2436. self.autorun.setEnabled(enable)
  2437. self.bufferTab.setEnabled(enable)
  2438. def cancelHardwareTask(self):
  2439. if self.autorun.isRunning():
  2440. self.autorun.abortRun()
  2441. if self.threadRunning:
  2442. self.hwThread.cancelTask()
  2443. def __triggerOperation(self, op, threadMutexIsLocked=False):
  2444. self.hwThread.triggerTask(op.hwTask, op.hwTaskParam,
  2445. id(op), threadMutexIsLocked)
  2446. self.threadRunning = True
  2447. self.runningOps[id(op)] = op
  2448. self.console.setTaskRunning(True)
  2449. self.guiUpdateEnable()
  2450. def __triggerNextOperation(self, threadMutexIsLocked=False):
  2451. assert(self.queuedOps)
  2452. op = self.queuedOps.pop(0)
  2453. self.__triggerOperation(op, threadMutexIsLocked)
  2454. def runOperation(self, op):
  2455. self.queuedOps.append(op)
  2456. if not self.threadRunning:
  2457. self.__triggerNextOperation()
  2458. return True
  2459. def runOperationSync(self, hwTask, taskParameter=None):
  2460. op = Operation(Operation.OP_SYNCHRONOUS,
  2461. hwTask, taskParameter)
  2462. self.runOperation(op)
  2463. while not op.finished:
  2464. QApplication.processEvents(QEventLoop.AllEvents, 50)
  2465. self.runningOps.pop(id(op))
  2466. return (op.failed, op.returnValue)
  2467. def setOperationFinished(self, failed):
  2468. self.console.setTaskRunning(running=False, success=not failed)
  2469. if self.autorun.isRunning():
  2470. if failed:
  2471. QTimer.singleShot(0, self.autorun.abortRunWithMessage)
  2472. else:
  2473. QTimer.singleShot(0, self.autorun.runNextAction)
  2474. def __hardwareTaskFinished(self, op):
  2475. if op.op == Operation.OP_SYNCHRONOUS:
  2476. self.console.setTaskRunning(running=False, success=True)
  2477. return
  2478. self.runningOps.pop(id(op))
  2479. if op.failed:
  2480. self.console.showMessage("[op %d task %d failed] %s\n" %\
  2481. (op.op, op.hwTask, str(op.returnValue)),
  2482. bold=True)
  2483. self.setOperationFinished(failed=True)
  2484. return
  2485. # Task succeed
  2486. if op.op == Operation.OP_INITCHIP:
  2487. assert(op.hwTask == HwThread.TASK_INITCHIP)
  2488. (self.chip, asciiArtLayout) = op.returnValue
  2489. self.bufferTab.setupBuffers(self.chip.getSupportFlags())
  2490. self.bufferTab.infoBuffer.clear()
  2491. self.bufferTab.infoBuffer.setupDescription(self.currentChipDescription)
  2492. self.bufferTab.infoBuffer.setChipLayout(asciiArtLayout)
  2493. self.autorun.setup(self.chip.getSupportFlags())
  2494. self.topToolBar.setup(self.chip.getSupportFlags())
  2495. self.rightToolBar.setup(self.chip.getSupportFlags())
  2496. self.setupRunMenu(self.chip.getSupportFlags())
  2497. elif op.op == Operation.OP_SHUTDOWN:
  2498. pass # Nothing to do
  2499. elif op.op == Operation.OP_READALL:
  2500. assert(op.hwTask == HwThread.TASK_GENERICTOPCALL)
  2501. topCallList = op.returnValue
  2502. images = self.__readCallChain_GetResultImages(topCallList)
  2503. self.bufferTab.setupBuffers(self.chip.getSupportFlags())
  2504. self.bufferTab.loadBuffers(images)
  2505. try:
  2506. self.bufferTab.infoBuffer.setChipSignature(images["signature"])
  2507. except KeyError:
  2508. pass
  2509. elif op.op == Operation.OP_ERASE:
  2510. pass # Nothing to do
  2511. elif op.op == Operation.OP_WRITEPROG:
  2512. pass # Nothing to do
  2513. elif op.op == Operation.OP_WRITEEPROM:
  2514. pass # Nothing to do
  2515. elif op.op == Operation.OP_WRITEFUSE:
  2516. pass # Nothing to do
  2517. elif op.op == Operation.OP_WRITELOCK:
  2518. pass # Nothing to do
  2519. elif op.op == Operation.OP_WRITERAM:
  2520. pass # Nothing to do
  2521. elif op.op == Operation.OP_TEST:
  2522. self.console.showMessage("Unit-test success. The chip seems to be OK.\n",
  2523. bold=True)
  2524. elif op.op == Operation.OP_VERIFY:
  2525. assert(op.hwTask == HwThread.TASK_GENERICTOPCALL)
  2526. topCallList = op.returnValue
  2527. images = self.__readCallChain_GetResultImages(topCallList)
  2528. op.failed = not self.bufferTab.verifyBuffers(images)
  2529. elif op.op == Operation.OP_RAWCOMMAND:
  2530. self.console.showMessage("Successfully sent raw command\n", bold=True)
  2531. else:
  2532. print "ERROR: No handler for op %d task %d" % (op.op, op.hwTask)
  2533. self.setOperationFinished(op.failed)
  2534. def hardwareTaskFinished(self, opaqueId, failed, returnValue):
  2535. if opaqueId is None:
  2536. return
  2537. op = self.runningOps[opaqueId]
  2538. op.returnValue = returnValue
  2539. op.failed = failed
  2540. self.threadRunning = False
  2541. self.__hardwareTaskFinished(op)
  2542. op.op = Operation.OP_NONE
  2543. op.finished = True
  2544. if self.queuedOps:
  2545. self.__triggerNextOperation(threadMutexIsLocked=True)
  2546. return
  2547. self.guiUpdateEnable()
  2548. def main():
  2549. app = QApplication(sys.argv)
  2550. mainwnd = MainWindow()
  2551. mainwnd.show()
  2552. mainwnd.resize(int(mainwnd.width() * 1.6),
  2553. int(mainwnd.height() * 1.2))
  2554. return app.exec_()
  2555. if __name__ == "__main__":
  2556. sys.exit(main())