toprammer-gui 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892
  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.fgColor = QColor("#000000")
  1072. self.cursor0Color = QColor("#A0A07F")
  1073. self.cursor1Color = QColor("#D0D0AF")
  1074. font = self.font()
  1075. font.setFamily("monospace")
  1076. font.setFixedPitch(True)
  1077. font.setPointSize(10)
  1078. self.setFont(font)
  1079. self.charWidth = self.fontMetrics().width("x")
  1080. self.charHeight = self.fontMetrics().height()
  1081. self.bytesPerLine = 16
  1082. self.previousData = b""
  1083. self.setData(b"")
  1084. self.__setCursor(0, False)
  1085. self.setFocusPolicy(Qt.StrongFocus)
  1086. def updateText(self):
  1087. lines = []
  1088. if self.data:
  1089. for i in range(0, len(self.data), self.bytesPerLine):
  1090. end = min(i + self.bytesPerLine, len(self.data))
  1091. data = self.data[i : end]
  1092. try:
  1093. prevData = self.previousData[i : end]
  1094. except IndexError:
  1095. prevData = None
  1096. if prevData == data:
  1097. lines.append(self.textLines[i // self.bytesPerLine])
  1098. else:
  1099. text = [ "[%08X]: " % i ]
  1100. for byte in data:
  1101. text.append(" " + byte2hex(byte))
  1102. if len(data) % self.bytesPerLine:
  1103. # padding
  1104. nrLeft = self.bytesPerLine - (len(data) % self.bytesPerLine)
  1105. text.append(" " * nrLeft)
  1106. text.append(" |")
  1107. for byte in data:
  1108. text.append(bytes2ascii(byte))
  1109. text.append("|")
  1110. lines.append("".join(text))
  1111. else:
  1112. lines = [ "<The buffer is empty>", ]
  1113. self.textLines = lines
  1114. self.nrLines = len(lines)
  1115. self.previousData = self.data
  1116. width = self.fontMetrics().width(self.textLines[0])
  1117. height = self.nrLines * self.charHeight
  1118. self.resize(width + 20, height + 20)
  1119. self.repaint()
  1120. def getData(self):
  1121. return self.data
  1122. def setData(self, data):
  1123. if not data:
  1124. data = ""
  1125. self.data = data
  1126. self.updateText()
  1127. self.__setCursor(0, False)
  1128. def charInput(self, char):
  1129. if not self.data:
  1130. return
  1131. data = list(self.data)
  1132. assert(self.cursorByte < len(data))
  1133. if self.cursorOnAscii:
  1134. data[self.cursorByte] = char
  1135. self.__setCursor(self.cursorByte + 1, True)
  1136. else:
  1137. dataByte = byte2int(data[self.cursorByte])
  1138. char = ord(char.upper())
  1139. if char >= ord("0") and char <= ord("9"):
  1140. nibble = char - ord("0")
  1141. elif char >= ord("A") and char <= ord("F"):
  1142. nibble = char - ord("A") + 10
  1143. else:
  1144. return
  1145. if self.cursorNibble == 0:
  1146. dataByte = (dataByte & 0xF0) | nibble
  1147. else:
  1148. dataByte = (dataByte & 0x0F) | (nibble << 4)
  1149. data[self.cursorByte] = chr(dataByte)
  1150. if self.cursorNibble == 1:
  1151. self.cursorNibble = 0
  1152. else:
  1153. self.__setCursor(self.cursorByte + 1, False)
  1154. self.data = "".join(data)
  1155. self.updateText()
  1156. def keyPressEvent(self, e):
  1157. linesOnScreen = self.scrollArea.viewport().height() // self.charHeight
  1158. if e.matches(QKeySequence.Delete) or\
  1159. e.key() == Qt.Key_Backspace:
  1160. self.__setCursor(self.cursorByte - 1, self.cursorOnAscii)
  1161. return
  1162. if e.matches(QKeySequence.MoveToNextChar):
  1163. self.__setCursor(self.cursorByte + 1, self.cursorOnAscii)
  1164. return
  1165. if e.matches(QKeySequence.MoveToPreviousChar):
  1166. self.__setCursor(self.cursorByte - 1, self.cursorOnAscii)
  1167. return
  1168. if e.matches(QKeySequence.MoveToStartOfLine):
  1169. self.__setCursor(self.cursorByte - self.cursorByte % self.bytesPerLine,
  1170. self.cursorOnAscii)
  1171. return
  1172. if e.matches(QKeySequence.MoveToEndOfLine):
  1173. self.__setCursor(self.cursorByte - self.cursorByte % self.bytesPerLine
  1174. + self.bytesPerLine - 1,
  1175. self.cursorOnAscii)
  1176. return
  1177. if e.matches(QKeySequence.MoveToNextLine):
  1178. self.__setCursor(self.cursorByte + self.bytesPerLine, self.cursorOnAscii)
  1179. return
  1180. if e.matches(QKeySequence.MoveToPreviousLine):
  1181. self.__setCursor(self.cursorByte - self.bytesPerLine, self.cursorOnAscii)
  1182. return
  1183. if e.matches(QKeySequence.MoveToStartOfDocument):
  1184. self.__setCursor(0, self.cursorOnAscii)
  1185. return
  1186. if e.matches(QKeySequence.MoveToEndOfDocument):
  1187. self.__setCursor(len(self.data) - 1, self.cursorOnAscii)
  1188. return
  1189. if e.matches(QKeySequence.MoveToNextPage):
  1190. self.__setCursor(self.cursorByte + int(linesOnScreen * 0.8) * self.bytesPerLine,
  1191. self.cursorOnAscii)
  1192. return
  1193. if e.matches(QKeySequence.MoveToPreviousPage):
  1194. self.__setCursor(self.cursorByte - int(linesOnScreen * 0.8) * self.bytesPerLine,
  1195. self.cursorOnAscii)
  1196. return
  1197. text = str(e.text())
  1198. if text:
  1199. key = ord(text[0])
  1200. if self.cursorOnAscii:
  1201. self.charInput(chr(key))
  1202. else:
  1203. if (key >= ord("0") and key <= ord("9")) or\
  1204. (key >= ord("a") and key <= ord("f")) or\
  1205. (key >= ord("A") and key <= ord("F")):
  1206. self.charInput(chr(key))
  1207. def __setCursor(self, byteNr, asciiArea):
  1208. byteNr = min(byteNr, len(self.data) - 1)
  1209. byteNr = max(byteNr, 0)
  1210. self.cursorOnAscii = asciiArea
  1211. self.cursorByte = byteNr
  1212. self.cursorNibble = 1
  1213. self.repaint()
  1214. (x, y) = self.__cursorUpperLeftEdge()
  1215. self.scrollArea.ensureVisible(x, y)
  1216. def mousePressEvent(self, e):
  1217. x = e.pos().x()
  1218. y = e.pos().y()
  1219. byteAreaX = self.charWidth * 13
  1220. byteAreaY = 3
  1221. asciiAreaX = self.charWidth * (13 + 3 * self.bytesPerLine + 3 - 1)
  1222. asciiAreaY = 3
  1223. if x >= byteAreaX and\
  1224. y >= byteAreaY and\
  1225. x <= byteAreaX + self.charWidth * 3 * self.bytesPerLine and\
  1226. y <= byteAreaY + self.charHeight * self.nrLines:
  1227. # Click in byte area.
  1228. x -= byteAreaX
  1229. y -= byteAreaY
  1230. line = y // self.charHeight
  1231. column = x // (self.charWidth * 3)
  1232. self.__setCursor(line * self.bytesPerLine + column,
  1233. False)
  1234. return
  1235. if x >= asciiAreaX and\
  1236. y >= asciiAreaY and\
  1237. x <= asciiAreaX + self.charWidth * self.bytesPerLine and\
  1238. y <= asciiAreaY + self.charHeight * self.nrLines:
  1239. # Click on ascii area.
  1240. x -= asciiAreaX
  1241. y -= asciiAreaY
  1242. line = y // self.charHeight
  1243. column = x // self.charWidth
  1244. self.__setCursor(line * self.bytesPerLine + column,
  1245. True)
  1246. return
  1247. def __cursorUpperLeftEdge(self):
  1248. if self.cursorOnAscii:
  1249. x = self.charWidth * (13 + 3 * self.bytesPerLine + 3 - 1)
  1250. x += self.charWidth * (self.cursorByte % self.bytesPerLine)
  1251. y = self.charHeight * (self.cursorByte // self.bytesPerLine)
  1252. y += 3
  1253. else:
  1254. x = self.charWidth * 13
  1255. x += self.charWidth * 3 * (self.cursorByte % self.bytesPerLine)
  1256. y = self.charHeight * (self.cursorByte // self.bytesPerLine)
  1257. y += 3
  1258. return (x, y)
  1259. def paintEvent(self, e):
  1260. p = QPainter(self)
  1261. # Background
  1262. p.fillRect(0, 0, self.width(), self.height(), self.bgColor)
  1263. # Cursor
  1264. if self.data and self.hasFocus():
  1265. (x, y) = self.__cursorUpperLeftEdge()
  1266. if self.cursorOnAscii:
  1267. p.fillRect(x, y, self.charWidth, self.charHeight,
  1268. self.cursor0Color)
  1269. else:
  1270. p.fillRect(x, y, self.charWidth * 2, self.charHeight,
  1271. self.cursor1Color)
  1272. if self.cursorNibble == 0:
  1273. x += self.charWidth
  1274. p.fillRect(x, y, self.charWidth, self.charHeight,
  1275. self.cursor0Color)
  1276. # Text
  1277. p.setPen(QPen(self.fgColor))
  1278. y = self.charHeight
  1279. for line in self.textLines:
  1280. p.drawText(0, y, line)
  1281. y += self.charHeight
  1282. class HexEdit(QScrollArea):
  1283. def __init__(self, parent=None):
  1284. QScrollArea.__init__(self, parent)
  1285. self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
  1286. self.setWidgetResizable(False)
  1287. self.setWidget(HexEditWidget(self, self))
  1288. def setData(self, data):
  1289. self.widget().setData(data)
  1290. def getData(self):
  1291. return self.widget().getData()
  1292. class BufferWidget(QWidget):
  1293. def __init__(self, mainWindow, name):
  1294. QWidget.__init__(self, mainWindow)
  1295. self.mainWindow = mainWindow
  1296. self.name = name
  1297. self.hide()
  1298. self.setLayout(QGridLayout(self))
  1299. self.setAvailable(False)
  1300. self.setReadOnly()
  1301. def getName(self):
  1302. return self.name
  1303. def setAvailable(self, available):
  1304. self.available = available
  1305. def isAvailable(self):
  1306. return self.available
  1307. def setReadOnly(self, readOnly=True):
  1308. self.readOnly = readOnly
  1309. def isReadOnly(self):
  1310. return self.readOnly
  1311. def getRawData(self):
  1312. return None
  1313. def setRawData(self, data):
  1314. return False
  1315. def setDataWithIHexInterpreter(self, interp, readRaw):
  1316. return False
  1317. def clear(self):
  1318. pass
  1319. class InfoBufferWidget(BufferWidget):
  1320. def __init__(self, mainWindow, name):
  1321. BufferWidget.__init__(self, mainWindow, name)
  1322. self.zifLayout = QLabel(self)
  1323. font = self.zifLayout.font()
  1324. font.setFixedPitch(True)
  1325. font.setFamily("monospace")
  1326. font.setPointSize(7)
  1327. self.zifLayout.setFont(font)
  1328. self.layout().addWidget(self.zifLayout, 0, 0, 6, 1)
  1329. def addLabel(name, y):
  1330. l = QLabel(name, self)
  1331. l.setAlignment(Qt.AlignTop | Qt.AlignLeft)
  1332. self.layout().addWidget(l, y, 1)
  1333. label = QLabel(self)
  1334. label.setAlignment(Qt.AlignTop | Qt.AlignLeft)
  1335. font = label.font()
  1336. font.setBold(True)
  1337. label.setFont(font)
  1338. self.layout().addWidget(label, y, 2)
  1339. return label
  1340. self.chipName = addLabel("Chip name:", 0)
  1341. self.comment = addLabel("Comment:", 1)
  1342. self.packages = addLabel("Packages:", 2)
  1343. self.chipSig = addLabel("Chip signature bytes:", 3)
  1344. self.maintainer = addLabel("Chip maintainer:", 4)
  1345. self.layout().setColumnStretch(3, 99)
  1346. self.layout().setRowStretch(5, 99)
  1347. self.clear()
  1348. def clear(self):
  1349. self.chipName.setText("<No chip selected>")
  1350. self.setComment(None)
  1351. self.setChipSignature(None)
  1352. self.setChipLayout(None)
  1353. self.setPackages(None)
  1354. self.setMaintainer(None)
  1355. def setChipSignature(self, bindata):
  1356. if bindata:
  1357. self.chipSig.setText(bytes2hex(bindata))
  1358. else:
  1359. self.chipSig.setText("None")
  1360. def setComment(self, comment):
  1361. if comment:
  1362. self.comment.setText(comment)
  1363. else:
  1364. self.comment.setText("None")
  1365. def setPackages(self, packages):
  1366. def p2str(param):
  1367. (packageName, description) = param
  1368. text = packageName
  1369. if description:
  1370. text += " (%s)" % description
  1371. return text
  1372. if packages:
  1373. pckgs = map(p2str, packages)
  1374. self.packages.setText("\n".join(pckgs))
  1375. else:
  1376. self.packages.setText("Unknown")
  1377. def setMaintainer(self, maintainer):
  1378. if maintainer:
  1379. # Remove email address
  1380. idx = maintainer.find("<")
  1381. if idx >= 0:
  1382. maintainer = maintainer[:idx]
  1383. self.maintainer.setText(maintainer.strip())
  1384. else:
  1385. self.maintainer.setText("None")
  1386. def setupDescription(self, chipDescription):
  1387. self.chipName.setText(chipDescription.description)
  1388. self.setComment(chipDescription.comment)
  1389. self.setPackages(chipDescription.packages)
  1390. self.setMaintainer(chipDescription.maintainer)
  1391. def setChipLayout(self, asciiArtLayout):
  1392. if asciiArtLayout:
  1393. self.zifLayout.setText(asciiArtLayout)
  1394. self.zifLayout.setFrameShape(QFrame.StyledPanel)
  1395. else:
  1396. self.zifLayout.clear()
  1397. self.zifLayout.setFrameShape(QFrame.NoFrame)
  1398. class ImageBufferWidget(BufferWidget):
  1399. def __init__(self, mainWindow, name):
  1400. BufferWidget.__init__(self, mainWindow, name)
  1401. self.browser = HexEdit(self)
  1402. self.layout().addWidget(self.browser, 0, 0)
  1403. def loadImage(self, image):
  1404. self.browser.setData(image)
  1405. def getRawData(self):
  1406. return self.browser.getData()
  1407. def setRawData(self, data):
  1408. if self.isReadOnly():
  1409. return False
  1410. self.loadImage(data)
  1411. return True
  1412. def clear(self):
  1413. self.loadImage(None)
  1414. class BitBufferWidget(BufferWidget):
  1415. def __init__(self, mainWindow, name, bitDescriptionsAttr):
  1416. BufferWidget.__init__(self, mainWindow, name)
  1417. self.bitDescriptionsAttr = bitDescriptionsAttr
  1418. self.bitsAreaScroll = QScrollArea(self)
  1419. self.layout().addWidget(self.bitsAreaScroll, 0, 0)
  1420. self.bitsAreaScroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
  1421. self.bitsAreaScroll.setWidgetResizable(False)
  1422. self.bitsArea = None
  1423. self.image = None
  1424. self.checkboxes = []
  1425. def __getBitDescription(self, bitNr):
  1426. if not self.mainWindow.currentChipDescription:
  1427. return ""
  1428. bitDescList = getattr(self.mainWindow.currentChipDescription,
  1429. self.bitDescriptionsAttr, None)
  1430. if not bitDescList:
  1431. return ""
  1432. bitDesc = filter(lambda x: x.bitNr == bitNr,
  1433. bitDescList)
  1434. if not bitDesc:
  1435. return ""
  1436. return bitDesc[0].description
  1437. def loadImage(self, image):
  1438. self.image = image
  1439. for checkbox in self.checkboxes:
  1440. checkbox.deleteLater()
  1441. self.checkboxes = []
  1442. if self.bitsArea:
  1443. self.bitsArea.deleteLater()
  1444. self.bitsArea = None
  1445. if not self.image:
  1446. return
  1447. self.bitsArea = QWidget(self)
  1448. self.bitsArea.setLayout(QGridLayout(self.bitsArea))
  1449. self.bitsArea.layout().addWidget(QLabel("Currently set %s:" % self.getName(),
  1450. self.bitsArea),
  1451. 0, 0)
  1452. self.hexView = QLabel(self.bitsArea)
  1453. font = self.hexView.font()
  1454. font.setBold(True)
  1455. self.hexView.setFont(font)
  1456. self.bitsArea.layout().addWidget(self.hexView, 0, 1)
  1457. for i in range(0, len(image) * 8):
  1458. desc = self.__getBitDescription(i)
  1459. if desc:
  1460. desc = " (%s)" % desc
  1461. checkbox = QCheckBox("bit %d%s" % (i, desc), self.bitsArea)
  1462. if byte2int(image[i // 8]) & bit(i % 8):
  1463. checkbox.setCheckState(Qt.Checked)
  1464. self.bitsArea.layout().addWidget(checkbox, 1 + i, 0, 1, 2)
  1465. checkbox.stateChanged.connect(self.__bitStateChanged)
  1466. self.checkboxes.append(checkbox)
  1467. self.__updateHexView()
  1468. def __updateHexView(self):
  1469. self.hexView.setText(bytes2hex(self.image))
  1470. self.bitsAreaScroll.setWidget(self.bitsArea)
  1471. def __bitStateChanged(self, unused):
  1472. self.image = ""
  1473. tmp = 0
  1474. i = 0
  1475. for checkbox in self.checkboxes:
  1476. if checkbox.checkState() == Qt.Checked:
  1477. tmp |= bit(i)
  1478. i += 1
  1479. if i == 8:
  1480. self.image += chr(tmp)
  1481. i = 0
  1482. tmp = 0
  1483. assert(i == 0)
  1484. self.__updateHexView()
  1485. def getRawData(self):
  1486. return self.image
  1487. def setRawData(self, data):
  1488. if self.isReadOnly():
  1489. return False
  1490. if len(data) > 32: # Don't want huge files
  1491. return False
  1492. self.loadImage(data)
  1493. return True
  1494. def clear(self):
  1495. self.loadImage(None)
  1496. class ProgmemBufferWidget(ImageBufferWidget):
  1497. def __init__(self, mainWindow):
  1498. ImageBufferWidget.__init__(self, mainWindow, "program memory")
  1499. def setDataWithIHexInterpreter(self, interp, readRaw):
  1500. return self.setRawData(interp.getProgmem(dontInterpretSections = readRaw))
  1501. class EEPROMBufferWidget(ImageBufferWidget):
  1502. def __init__(self, mainWindow):
  1503. ImageBufferWidget.__init__(self, mainWindow, "(E)EPROM memory")
  1504. def setDataWithIHexInterpreter(self, interp, readRaw):
  1505. return self.setRawData(interp.getEEPROM(dontInterpretSections = readRaw))
  1506. class RAMBufferWidget(ImageBufferWidget):
  1507. def __init__(self, mainWindow):
  1508. ImageBufferWidget.__init__(self, mainWindow, "RAM memory")
  1509. def setDataWithIHexInterpreter(self, interp, readRaw):
  1510. return self.setRawData(interp.getRAM(dontInterpretSections = readRaw))
  1511. class FuseBufferWidget(BitBufferWidget):
  1512. def __init__(self, mainWindow):
  1513. BitBufferWidget.__init__(self, mainWindow, "fuse bits", "fuseDesc")
  1514. def setDataWithIHexInterpreter(self, interp, readRaw):
  1515. return self.setRawData(interp.getFusebits(dontInterpretSections = readRaw))
  1516. class LockBufferWidget(BitBufferWidget):
  1517. def __init__(self, mainWindow):
  1518. BitBufferWidget.__init__(self, mainWindow, "lock bits", "lockbitDesc")
  1519. def setDataWithIHexInterpreter(self, interp, readRaw):
  1520. return self.setRawData(interp.getLockbits(dontInterpretSections = readRaw))
  1521. class BufferTabWidget(QTabWidget):
  1522. def __init__(self, mainWindow):
  1523. QTabWidget.__init__(self, mainWindow)
  1524. self.mainWindow = mainWindow
  1525. self.infoBuffer = InfoBufferWidget(mainWindow, "chip info")
  1526. self.progmemBuffer = ProgmemBufferWidget(mainWindow)
  1527. self.eepromBuffer = EEPROMBufferWidget(mainWindow)
  1528. self.fuseBuffer = FuseBufferWidget(mainWindow)
  1529. self.lockBuffer = LockBufferWidget(mainWindow)
  1530. self.ramBuffer = RAMBufferWidget(mainWindow)
  1531. self.setTabPosition(self.South)
  1532. self.__addBufferTab(self.infoBuffer, readOnly=True)
  1533. self.removeAll()
  1534. def __addBufferTab(self, bufferWidget, readOnly=False):
  1535. self.addTab(bufferWidget, bufferWidget.getName())
  1536. bufferWidget.setReadOnly(readOnly)
  1537. bufferWidget.setAvailable(True)
  1538. def __removeBufferTab(self, bufferWidget):
  1539. self.removeTab(self.indexOf(bufferWidget))
  1540. bufferWidget.clear()
  1541. bufferWidget.setAvailable(False)
  1542. def __removeAll(self):
  1543. self.__removeBufferTab(self.progmemBuffer)
  1544. self.__removeBufferTab(self.eepromBuffer)
  1545. self.__removeBufferTab(self.fuseBuffer)
  1546. self.__removeBufferTab(self.lockBuffer)
  1547. self.__removeBufferTab(self.ramBuffer)
  1548. def removeAll(self):
  1549. self.__removeAll()
  1550. def setupBuffers(self, chipSupportFlags):
  1551. prevSelect = self.getCurrentBuffer()
  1552. self.__removeAll()
  1553. for (bufferWidget, flagsMask) in (
  1554. (self.progmemBuffer, Chip.SUPPORT_PROGMEMREAD | Chip.SUPPORT_PROGMEMWRITE),
  1555. (self.eepromBuffer, Chip.SUPPORT_EEPROMREAD | Chip.SUPPORT_EEPROMWRITE),
  1556. (self.fuseBuffer, Chip.SUPPORT_FUSEREAD | Chip.SUPPORT_FUSEWRITE),
  1557. (self.lockBuffer, Chip.SUPPORT_LOCKREAD | Chip.SUPPORT_LOCKWRITE),
  1558. (self.ramBuffer, Chip.SUPPORT_RAMREAD | Chip.SUPPORT_RAMWRITE)):
  1559. if chipSupportFlags & flagsMask:
  1560. self.__addBufferTab(bufferWidget)
  1561. if prevSelect and prevSelect.isAvailable():
  1562. self.setCurrentIndex(self.indexOf(prevSelect))
  1563. def loadBuffers(self, images):
  1564. try:
  1565. self.progmemBuffer.loadImage(images["progmem"])
  1566. except KeyError:
  1567. pass # Ignore
  1568. try:
  1569. self.eepromBuffer.loadImage(images["eeprom"])
  1570. except KeyError:
  1571. pass # Ignore
  1572. try:
  1573. self.fuseBuffer.loadImage(images["fusebits"])
  1574. except KeyError:
  1575. pass # Ignore
  1576. try:
  1577. self.lockBuffer.loadImage(images["lockbits"])
  1578. except KeyError:
  1579. pass # Ignore
  1580. try:
  1581. self.ramBuffer.loadImage(images["ram"])
  1582. except KeyError:
  1583. pass # Ignore
  1584. def verifyBuffers(self, images):
  1585. fail = False
  1586. for (imageName, bufferWidget) in (("progmem", self.progmemBuffer),
  1587. ("eeprom", self.eepromBuffer),
  1588. ("fusebits", self.fuseBuffer),
  1589. ("ram", self.ramBuffer)):
  1590. try:
  1591. image = images[imageName]
  1592. except KeyError:
  1593. continue
  1594. bufImage = bufferWidget.getRawData()
  1595. if not bufImage:
  1596. if not image:
  1597. # Both images are empty. Go on...
  1598. continue
  1599. self.mainWindow.console.showMessage(
  1600. "Chip verify of %s FAILED! "
  1601. "There is no data in the "
  1602. "%s buffer. First load data into "
  1603. "the buffer tab, please.\n" %\
  1604. (bufferWidget.getName(),
  1605. bufferWidget.getName()),
  1606. bold=True)
  1607. fail = True
  1608. continue
  1609. if len(bufImage) > len(image):
  1610. self.mainWindow.console.showMessage(
  1611. "Chip verify of %s FAILED! "
  1612. "Buffer data is larger than "
  1613. "chip memory.\n" %\
  1614. bufferWidget.getName(),
  1615. bold=True)
  1616. fail = True
  1617. continue
  1618. compareSize = min(len(image), len(bufImage))
  1619. if len(image) != len(bufImage):
  1620. self.mainWindow.console.showMessage(
  1621. "%s: Only comparing the first 0x%X bytes due "
  1622. "to a mismatch of the buffer size (0x%X) "
  1623. "with the actual device image size (0x%X).\n" %\
  1624. (bufferWidget.getName(), compareSize,
  1625. len(bufImage), len(image)))
  1626. if bufImage[:compareSize] != image[:compareSize]:
  1627. self.mainWindow.console.showMessage(
  1628. "Chip verify of %s FAILED! "
  1629. "Image data mismatch.\n" %\
  1630. bufferWidget.getName(),
  1631. bold=True)
  1632. fail = True
  1633. continue
  1634. if fail:
  1635. self.mainWindow.console.setStatus(Console.STAT_ERROR)
  1636. else:
  1637. self.mainWindow.console.showMessage("Chip verify succeed\n", bold=True)
  1638. self.mainWindow.console.setStatus(Console.STAT_OK)
  1639. return not fail
  1640. def getCurrentBuffer(self):
  1641. return self.currentWidget()
  1642. class ChipSelectDialog(QDialog):
  1643. ALL_VENDORS = "--- All vendors ---"
  1644. def __init__(self, parent):
  1645. QDialog.__init__(self, parent)
  1646. self.setWindowTitle("Select chip")
  1647. self.setLayout(QGridLayout(self))
  1648. groupBox = QGroupBox("Chip type", self)
  1649. groupBox.setLayout(QGridLayout(groupBox))
  1650. self.allRadio = QRadioButton("All types", groupBox)
  1651. self.allRadio.setChecked(Qt.Checked)
  1652. groupBox.layout().addWidget(self.allRadio, 0, 0)
  1653. self.mcuRadio = QRadioButton("Microcontrollers", groupBox)
  1654. groupBox.layout().addWidget(self.mcuRadio, 1, 0)
  1655. self.epromRadio = QRadioButton("EPROMs", groupBox)
  1656. groupBox.layout().addWidget(self.epromRadio, 2, 0)
  1657. self.eepromRadio = QRadioButton("EEPROMs", groupBox)
  1658. groupBox.layout().addWidget(self.eepromRadio, 3, 0)
  1659. self.galRadio = QRadioButton("PALs / GALs", groupBox)
  1660. groupBox.layout().addWidget(self.galRadio, 4, 0)
  1661. self.sramRadio = QRadioButton("Static RAM", groupBox)
  1662. groupBox.layout().addWidget(self.sramRadio, 5, 0)
  1663. self.logicRadio = QRadioButton("Logic chips", groupBox)
  1664. groupBox.layout().addWidget(self.logicRadio, 6, 0)
  1665. self.showBroken = QCheckBox("Show broken implementations", groupBox)
  1666. groupBox.layout().addWidget(self.showBroken, 7, 0)
  1667. self.layout().addWidget(groupBox, 0, 0, 2, 2)
  1668. l = QLabel("Vendor:", self)
  1669. self.layout().addWidget(l, 0, 2, 1, 2)
  1670. self.vendorList = QListWidget(self)
  1671. self.layout().addWidget(self.vendorList, 1, 2, 1, 2)
  1672. l = QLabel("Chip:", self)
  1673. self.layout().addWidget(l, 0, 4, 1, 2)
  1674. self.chipList = QListWidget(self)
  1675. self.layout().addWidget(self.chipList, 1, 4, 1, 2)
  1676. self.okButton = QPushButton("&Ok", self)
  1677. self.layout().addWidget(self.okButton, 2, 0, 1, 3)
  1678. self.cancelButton = QPushButton("&Cancel", self)
  1679. self.layout().addWidget(self.cancelButton, 2, 3, 1, 3)
  1680. self.okButton.released.connect(self.accept)
  1681. self.cancelButton.released.connect(self.reject)
  1682. self.vendorList.itemSelectionChanged.connect(self.vendorSelectionChanged)
  1683. self.chipList.itemSelectionChanged.connect(self.chipSelectionChanged)
  1684. self.chipList.itemDoubleClicked.connect(self.accept)
  1685. self.showBroken.stateChanged.connect(self.typeToggled)
  1686. for radio in (self.allRadio, self.mcuRadio, self.epromRadio,
  1687. self.eepromRadio, self.galRadio,
  1688. self.sramRadio, self.logicRadio):
  1689. radio.toggled.connect(self.typeToggled)
  1690. self.__updateVendorList()
  1691. self.__updateChipList()
  1692. def __updateVendorList(self):
  1693. previousVendor = self.__getSelectedVendor()
  1694. selType = self.__getSelectedChipType()
  1695. vendors = getRegisteredVendors()
  1696. self.vendorList.clear()
  1697. QListWidgetItem(self.ALL_VENDORS, self.vendorList)
  1698. for vendorName in vendors.keys():
  1699. descriptors = vendors[vendorName]
  1700. if self.showBroken.checkState() != Qt.Checked:
  1701. descriptors = filter(lambda d: not d.broken,
  1702. descriptors)
  1703. descriptors = filter(lambda d: (d.chipType == selType or selType == -1) and\
  1704. (d.chipType != ChipDescription.TYPE_INTERNAL),
  1705. descriptors)
  1706. if not descriptors:
  1707. continue
  1708. item = QListWidgetItem(vendorName, self.vendorList)
  1709. item.setData(Qt.UserRole, descriptors)
  1710. self.vendorList.sortItems()
  1711. if previousVendor:
  1712. items = self.vendorList.findItems(previousVendor, Qt.MatchExactly)
  1713. if len(items) == 1:
  1714. self.vendorList.setCurrentItem(items[0])
  1715. else:
  1716. self.vendorList.setCurrentRow(0)
  1717. else:
  1718. self.vendorList.setCurrentRow(0)
  1719. def __descriptorText(self, descriptor):
  1720. text = descriptor.description
  1721. if not descriptor.maintainer:
  1722. text += " (Orphaned)"
  1723. return text
  1724. def __updateChipList(self):
  1725. previousChip = self.getSelectedChip()
  1726. selType = self.__getSelectedChipType()
  1727. selVendor = self.__getSelectedVendor()
  1728. self.chipList.clear()
  1729. for descriptor in getRegisteredChips():
  1730. if descriptor.broken and\
  1731. self.showBroken.checkState() != Qt.Checked:
  1732. continue
  1733. if descriptor.chipType != selType and selType != -1:
  1734. continue
  1735. if descriptor.chipType == ChipDescription.TYPE_INTERNAL:
  1736. continue
  1737. if selVendor != self.ALL_VENDORS and selVendor not in descriptor.chipVendors:
  1738. continue
  1739. item = QListWidgetItem(self.__descriptorText(descriptor),
  1740. self.chipList)
  1741. item.setData(Qt.UserRole, descriptor)
  1742. self.chipList.sortItems()
  1743. if previousChip:
  1744. items = self.chipList.findItems(self.__descriptorText(previousChip),
  1745. Qt.MatchExactly)
  1746. if len(items) == 1:
  1747. self.chipList.setCurrentItem(items[0])
  1748. else:
  1749. self.chipList.setCurrentRow(0)
  1750. else:
  1751. self.chipList.setCurrentRow(0)
  1752. def typeToggled(self, unused):
  1753. self.__updateVendorList()
  1754. self.__updateChipList()
  1755. def vendorSelectionChanged(self):
  1756. self.__updateChipList()
  1757. def chipSelectionChanged(self):
  1758. item = self.chipList.currentItem()
  1759. self.okButton.setEnabled(bool(item))
  1760. def __getSelectedVendor(self):
  1761. item = self.vendorList.currentItem()
  1762. if not item:
  1763. return None
  1764. return str(item.text())
  1765. def __getSelectedChipType(self):
  1766. # Returns ChipDescription.TYPE_... or -1 if all are selected
  1767. for (typeId, radioButton) in (
  1768. (ChipDescription.TYPE_MCU, self.mcuRadio),
  1769. (ChipDescription.TYPE_EPROM, self.epromRadio),
  1770. (ChipDescription.TYPE_EEPROM, self.eepromRadio),
  1771. (ChipDescription.TYPE_GAL, self.galRadio),
  1772. (ChipDescription.TYPE_SRAM, self.sramRadio),
  1773. (ChipDescription.TYPE_LOGIC, self.logicRadio)):
  1774. if radioButton.isChecked():
  1775. return typeId
  1776. assert(self.allRadio.isChecked())
  1777. return -1
  1778. def getSelectedChip(self):
  1779. item = self.chipList.currentItem()
  1780. if not item:
  1781. return None
  1782. chipDescription = item.data(Qt.UserRole)
  1783. return chipDescription
  1784. class StatusBar(QStatusBar):
  1785. def __init__(self, mainWindow):
  1786. QStatusBar.__init__(self, mainWindow)
  1787. class TopToolBar(QToolBar):
  1788. def __init__(self, mainWindow):
  1789. QToolBar.__init__(self, "Toolbar", mainWindow)
  1790. self.mainWindow = mainWindow
  1791. self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  1792. self.setup(0)
  1793. def setup(self, chipSupportFlags):
  1794. mainWindow = self.mainWindow
  1795. self.clear()
  1796. a = self.addAction(getIcon("open"), "Load buffer", mainWindow.loadBuffer)
  1797. a.setEnabled(chipSupportFlags != 0)
  1798. a = self.addAction(getIcon("save"), "Save buffer", mainWindow.saveBuffer)
  1799. a.setEnabled(chipSupportFlags != 0)
  1800. self.addSeparator()
  1801. self.addAction(getIcon("chip"), "Run logic tester", mainWindow.startUnitest)
  1802. self.addAction(getIcon("chip"), "Select chip", mainWindow.selectChip)
  1803. self.addSeparator()
  1804. a = self.addAction(getIcon("up"), "Read chip", mainWindow.readChip)
  1805. a.setEnabled(chipSupportFlags != 0)
  1806. a = self.addAction(getIcon("verify"), "Verify all", mainWindow.verifyChip)
  1807. a.setEnabled(chipSupportFlags != 0)
  1808. class RightToolBar(QToolBar):
  1809. def __init__(self, mainWindow):
  1810. QToolBar.__init__(self, "Toolbar", mainWindow)
  1811. self.mainWindow = mainWindow
  1812. self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  1813. self.setup(0)
  1814. def setup(self, chipSupportFlags):
  1815. mainWindow = self.mainWindow
  1816. self.clear()
  1817. if chipSupportFlags & Chip.SUPPORT_ERASE:
  1818. self.addAction(getIcon("erase"), "Erase", mainWindow.eraseChip)
  1819. if chipSupportFlags & Chip.SUPPORT_PROGMEMWRITE:
  1820. self.addAction(getIcon("memory"), "Write progmem", mainWindow.writeChipProgmem)
  1821. if chipSupportFlags & Chip.SUPPORT_EEPROMWRITE:
  1822. self.addAction(getIcon("memory"), "Write EPROM", mainWindow.writeChipEeprom)
  1823. if chipSupportFlags & Chip.SUPPORT_FUSEWRITE:
  1824. self.addAction(getIcon("memory"), "Write fuses", mainWindow.writeChipFuses)
  1825. if chipSupportFlags & Chip.SUPPORT_RAMWRITE:
  1826. self.addAction(getIcon("memory"), "Write RAM", mainWindow.writeRam)
  1827. if chipSupportFlags & Chip.SUPPORT_LOCKWRITE:
  1828. self.addAction(getIcon("lock"), "Write lockbits", mainWindow.writeChipLockbits)
  1829. if chipSupportFlags & Chip.SUPPORT_TEST:
  1830. self.addAction(getIcon("test"), "Run unit-test", mainWindow.runTest)
  1831. class AutorunWidget(QDockWidget):
  1832. def __init__(self, mainWindow):
  1833. QDockWidget.__init__(self, "Autorun", mainWindow)
  1834. self.mainWindow = mainWindow
  1835. self.running = False
  1836. self.currentAction = -1
  1837. self.setFeatures(self.DockWidgetMovable | self.DockWidgetFloatable)
  1838. self.setup(0)
  1839. def __addCheckBox(self, row, condition, text, checked):
  1840. if condition:
  1841. checkbox = QCheckBox(text, self.widget())
  1842. if checked:
  1843. checkbox.setCheckState(Qt.Checked)
  1844. self.widget().layout().addWidget(checkbox, row, 0)
  1845. row += 1
  1846. return (checkbox, row)
  1847. return (None, row)
  1848. def setup(self, chipSupportFlags):
  1849. self.setWidget(QWidget(self))
  1850. self.widget().show()
  1851. self.widget().setLayout(QGridLayout(self.widget()))
  1852. row = 0
  1853. (self.testCheckBox, row) = self.__addCheckBox(row,
  1854. chipSupportFlags & Chip.SUPPORT_TEST,
  1855. "Run unit-test", True)
  1856. (self.eraseCheckBox, row) = self.__addCheckBox(row,
  1857. chipSupportFlags & Chip.SUPPORT_ERASE,
  1858. "Erase", True)
  1859. (self.progmemCheckBox, row) = self.__addCheckBox(row,
  1860. chipSupportFlags & Chip.SUPPORT_PROGMEMWRITE,
  1861. "Write program memory", True)
  1862. (self.eepromCheckBox, row) = self.__addCheckBox(row,
  1863. chipSupportFlags & Chip.SUPPORT_EEPROMWRITE,
  1864. "Write (E)EPROM", True)
  1865. (self.ramCheckBox, row) = self.__addCheckBox(row,
  1866. chipSupportFlags & Chip.SUPPORT_RAMWRITE,
  1867. "Write RAM", True)
  1868. (self.fusesCheckBox, row) = self.__addCheckBox(row,
  1869. chipSupportFlags & Chip.SUPPORT_FUSEWRITE,
  1870. "Write fuses", True)
  1871. (self.verifyCheckBox, row) = self.__addCheckBox(row,
  1872. chipSupportFlags != 0,
  1873. "Verify selected memories", True)
  1874. (self.lockbitsCheckBox, row) = self.__addCheckBox(row,
  1875. chipSupportFlags & Chip.SUPPORT_LOCKWRITE,
  1876. "Write lock bits", False)
  1877. self.runButton = None
  1878. if chipSupportFlags != 0:
  1879. self.runButton = QPushButton("Run", self.widget())
  1880. self.runButton.setIconSize(QSize(32, 32))
  1881. self.runButton.setIcon(getIcon("run"))
  1882. self.widget().layout().addWidget(self.runButton, row, 0)
  1883. row += 1
  1884. self.runButton.released.connect(self.runNextChip)
  1885. self.widget().layout().setRowStretch(row, 99)
  1886. def isRunning(self):
  1887. return self.running
  1888. def abortRunWithMessage(self):
  1889. self.abortRun(withMessage=True)
  1890. def abortRun(self, withMessage=False):
  1891. if withMessage:
  1892. QMessageBox.critical(self, "Aborting autorun",
  1893. "One action failed. Aborting autorun.\n"
  1894. "See console messages for details.")
  1895. self.running = False
  1896. self.currentAction = -1;
  1897. self.mainWindow.guiUpdateEnable()
  1898. def runNextChip(self):
  1899. self.running = True
  1900. self.currentAction = 0
  1901. res = QMessageBox.information(self, "Autorun - Please insert chip",
  1902. "Please insert a new %s chip into the ZIF socket "
  1903. "and press Ok to perform the operations..." %\
  1904. self.mainWindow.currentChipDescription.description,
  1905. QMessageBox.Ok | QMessageBox.Cancel,
  1906. QMessageBox.Ok)
  1907. if res != QMessageBox.Ok:
  1908. self.abortRun()
  1909. return
  1910. self.runNextAction()
  1911. def runNextAction(self):
  1912. assert(self.currentAction >= 0)
  1913. action = 0
  1914. if self.testCheckBox:
  1915. if self.currentAction == action:
  1916. if self.__runAction(self.mainWindow.runTest,
  1917. self.testCheckBox,
  1918. "Run unit-test"):
  1919. return
  1920. action += 1
  1921. if self.eraseCheckBox:
  1922. if self.currentAction == action:
  1923. if self.__runAction(self.mainWindow.eraseChip,
  1924. self.eraseCheckBox,
  1925. "Erase"):
  1926. return
  1927. action += 1
  1928. if self.progmemCheckBox:
  1929. if self.currentAction == action:
  1930. if self.__runAction(self.mainWindow.writeChipProgmem,
  1931. self.progmemCheckBox,
  1932. "Write program memory"):
  1933. return
  1934. action += 1
  1935. if self.eepromCheckBox:
  1936. if self.currentAction == action:
  1937. if self.__runAction(self.mainWindow.writeChipEeprom,
  1938. self.eepromCheckBox,
  1939. "Write (E)EPROM"):
  1940. return
  1941. action += 1
  1942. if self.ramCheckBox:
  1943. if self.currentAction == action:
  1944. if self.__runAction(self.mainWindow.writeRam,
  1945. self.ramCheckBox,
  1946. "Write RAM"):
  1947. return
  1948. action += 1
  1949. if self.fusesCheckBox:
  1950. if self.currentAction == action:
  1951. if self.__runAction(self.mainWindow.writeChipFuses,
  1952. self.fusesCheckBox,
  1953. "Write fuses"):
  1954. return
  1955. action += 1
  1956. if self.verifyCheckBox:
  1957. if self.currentAction == action:
  1958. if self.__runAction(self.__verifySelectedMemories,
  1959. self.verifyCheckBox,
  1960. "Verify selected memories"):
  1961. return
  1962. action += 1
  1963. if self.lockbitsCheckBox:
  1964. if self.currentAction == action:
  1965. if self.__runAction(self.mainWindow.writeChipLockbits,
  1966. self.lockbitsCheckBox,
  1967. "Write lock bits"):
  1968. return
  1969. action += 1
  1970. self.runNextChip()
  1971. def __runAction(self, function, checkbox, actionName):
  1972. self.currentAction += 1
  1973. if checkbox.checkState() == Qt.Checked:
  1974. self.mainWindow.console.showMessage(
  1975. "Running action: %s\n" % actionName, bold=True)
  1976. if not function():
  1977. self.abortRun(withMessage=True)
  1978. return True
  1979. return False
  1980. def __verifySelectedMemories(self):
  1981. def checked(cb):
  1982. return cb and (cb.checkState() == Qt.Checked)
  1983. return self.mainWindow.verifySelectedMemories(
  1984. verifyProgmem = checked(self.progmemCheckBox),
  1985. verifyEEPROM = checked(self.eepromCheckBox),
  1986. verifyFuse = checked(self.fusesCheckBox),
  1987. verifyRAM = checked(self.ramCheckBox))
  1988. class ProgrammerSelectDialog(QDialog):
  1989. def __init__(self, parent=None):
  1990. QDialog.__init__(self, parent)
  1991. self.setWindowTitle("Select programmer device")
  1992. self.setLayout(QGridLayout(self))
  1993. self.deviceList = QListWidget(self)
  1994. self.layout().addWidget(self.deviceList, 0, 0, 1, 2)
  1995. self.rescanButton = QPushButton("&Rescan USB busses", self)
  1996. self.layout().addWidget(self.rescanButton, 1, 0, 1, 2)
  1997. self.okButton = QPushButton("&OK", self)
  1998. self.layout().addWidget(self.okButton, 2, 0)
  1999. self.cancelButton = QPushButton("&Cancel", self)
  2000. self.layout().addWidget(self.cancelButton, 2, 1)
  2001. self.rescan()
  2002. self.deviceList.currentRowChanged.connect(self.selectionChanged)
  2003. self.deviceList.itemDoubleClicked.connect(self.accept)
  2004. self.okButton.released.connect(self.accept)
  2005. self.cancelButton.released.connect(self.reject)
  2006. self.rescanButton.released.connect(self.rescan)
  2007. def rescan(self):
  2008. self.deviceList.clear()
  2009. for foundDev in TOP.findDevices():
  2010. text = "%s (%s)" % (foundDev.toptype,
  2011. foundDev.devIdentifier)
  2012. item = QListWidgetItem(text, self.deviceList)
  2013. item.setData(Qt.UserRole, foundDev.devIdentifier)
  2014. self.deviceList.setCurrentRow(0)
  2015. def getIdentifier(self):
  2016. item = self.deviceList.currentItem()
  2017. if not item:
  2018. return None
  2019. return item.data(Qt.UserRole)
  2020. def selectionChanged(self, unused):
  2021. if self.deviceList.currentItem():
  2022. self.okButton.setEnabled(True)
  2023. else:
  2024. self.okButton.setEnabled(False)
  2025. class Operation(object):
  2026. OP_NONE = 0
  2027. OP_SHUTDOWN = 1
  2028. OP_INITCHIP = 2
  2029. OP_READALL = 3
  2030. OP_ERASE = 4
  2031. OP_WRITEPROG = 5
  2032. OP_WRITEEPROM = 6
  2033. OP_WRITEFUSE = 7
  2034. OP_WRITELOCK = 8
  2035. OP_WRITERAM = 9
  2036. OP_TEST = 10
  2037. OP_VERIFY = 11
  2038. OP_RAWCOMMAND = 12
  2039. OP_SYNCHRONOUS = 13
  2040. def __init__(self, op, hwTask, hwTaskParam=None):
  2041. self.op = op
  2042. self.hwTask = hwTask
  2043. self.hwTaskParam = hwTaskParam
  2044. self.returnValue = None
  2045. self.failed = False
  2046. self.finished = False
  2047. class MainWindow(QMainWindow):
  2048. def __init__(self, parent=None):
  2049. QMainWindow.__init__(self, parent)
  2050. self.setWindowTitle("TOPrammer v%s - Open Source programming suite" % VERSION)
  2051. self.guiDisable = 0
  2052. self.chip = None # Chip instance
  2053. self.currentChipDescription = None
  2054. self.previousRawCommand = ""
  2055. self.setStatusBar(StatusBar(self))
  2056. self.topToolBar = TopToolBar(self)
  2057. self.rightToolBar = RightToolBar(self)
  2058. self.addToolBar(Qt.TopToolBarArea, self.topToolBar)
  2059. self.addToolBar(Qt.RightToolBarArea, self.rightToolBar)
  2060. self.setMenuBar(QMenuBar(self))
  2061. menu = QMenu("&File", self)
  2062. menu.addAction("&Load buffer...", self.loadBuffer)
  2063. menu.addAction("&Save buffer...", self.saveBuffer)
  2064. menu.addSeparator()
  2065. menu.addAction("&Exit", self.close)
  2066. self.menuBar().addMenu(menu)
  2067. self.runMenu = QMenu("&Run", self)
  2068. self.setupRunMenu(0)
  2069. self.menuBar().addMenu(self.runMenu)
  2070. menu = QMenu("&Programmer", self)
  2071. menu.addAction("&Universal logic tester...", self.startUnitest)
  2072. menu.addSeparator()
  2073. menu.addAction("Select &programmer...", self.selectProgrammer)
  2074. menu.addAction("&Send raw command...", self.sendRawCommand)
  2075. self.menuBar().addMenu(menu)
  2076. menu = QMenu("&Help", self)
  2077. menu.addAction("&About", self.showAbout)
  2078. self.menuBar().addMenu(menu)
  2079. self.bufferTab = BufferTabWidget(self)
  2080. self.setCentralWidget(self.bufferTab)
  2081. self.console = Console(self)
  2082. self.addDockWidget(Qt.BottomDockWidgetArea, self.console)
  2083. self.autorun = AutorunWidget(self)
  2084. self.addDockWidget(Qt.LeftDockWidgetArea, self.autorun)
  2085. self.hwThread = HwThread(self)
  2086. self.threadRunning = False
  2087. self.queuedOps = []
  2088. self.runningOps = {}
  2089. def setupRunMenu(self, chipSupportFlags):
  2090. menu = self.runMenu
  2091. menu.clear()
  2092. menu.addAction("&Select chip", self.selectChip)
  2093. menu.addSeparator()
  2094. a = menu.addAction("&Read chip", self.readChip)
  2095. a.setEnabled(chipSupportFlags != 0)
  2096. a = menu.addAction("&Erase", self.eraseChip)
  2097. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_ERASE))
  2098. a = menu.addAction("Write &program memory", self.writeChipProgmem)
  2099. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_PROGMEMWRITE))
  2100. a = menu.addAction("Write (E)EP&ROM", self.writeChipEeprom)
  2101. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_EEPROMWRITE))
  2102. a = menu.addAction("Write &fuses", self.writeChipFuses)
  2103. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_FUSEWRITE))
  2104. a = menu.addAction("Write &lock bits", self.writeChipLockbits)
  2105. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_LOCKWRITE))
  2106. a = menu.addAction("Write R&AM", self.writeRam)
  2107. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_RAMWRITE))
  2108. a = menu.addAction("Run &Unit-test", self.runTest)
  2109. a.setEnabled(bool(chipSupportFlags & Chip.SUPPORT_TEST))
  2110. a = menu.addAction("&Verify whole chip", self.verifyChip)
  2111. a.setEnabled(chipSupportFlags != 0)
  2112. def event(self, e):
  2113. if e.type() == EVENT_HWTHREAD:
  2114. self.hwThread.handleMessageQueue()
  2115. e.accept()
  2116. return True
  2117. return QMainWindow.event(self, e)
  2118. def closeEvent(self, e):
  2119. if self.threadRunning:
  2120. res = QMessageBox.critical(self, "Task running",
  2121. "A hardware access task is running.\n\n"
  2122. "'Cancel' the close request and continue, or\n"
  2123. "'Abort' the task an quit the application?",
  2124. QMessageBox.Cancel | QMessageBox.Abort,
  2125. QMessageBox.Cancel)
  2126. if res == QMessageBox.Abort:
  2127. e.accept()
  2128. # Force quit
  2129. QApplication.exit(1)
  2130. return
  2131. e.ignore()
  2132. return
  2133. self.threadRunning = False
  2134. self.hwThread.killThread()
  2135. e.accept()
  2136. def showAbout(self):
  2137. QMessageBox.information(self, "About TOPrammer",
  2138. "Copyright (c) Michael Buesch <m@bues.ch>")
  2139. def startUnitest(self):
  2140. self.bufferTab.setupBuffers(0)
  2141. self.bufferTab.infoBuffer.clear()
  2142. self.autorun.setup(0)
  2143. self.guiDisable += 1
  2144. self.console.blockStatusUpdate()
  2145. try:
  2146. dlg = UnitestDialog(self)
  2147. dlg.exec_()
  2148. except (TOPException), e:
  2149. self.console.showMessage("Failed to start Unitest: %s\n" % str(e),
  2150. bold=True)
  2151. self.console.unblockStatusUpdate()
  2152. self.guiDisable -= 1
  2153. self.guiUpdateEnable()
  2154. self.runOperation(Operation(Operation.OP_SHUTDOWN,
  2155. HwThread.TASK_SHUTDOWN))
  2156. def selectProgrammer(self):
  2157. dlg = ProgrammerSelectDialog(self)
  2158. if dlg.exec_() != QDialog.Accepted:
  2159. return
  2160. devIdentifier = dlg.getIdentifier()
  2161. self.runOperationSync(HwThread.TASK_SHUTDOWN)
  2162. self.hwThread.setDevice(devIdentifier)
  2163. if self.currentChipDescription:
  2164. self.runOperation(Operation(Operation.OP_INITCHIP,
  2165. HwThread.TASK_INITCHIP,
  2166. self.currentChipDescription.chipID))
  2167. def sendRawCommand(self):
  2168. (string, ok) = QInputDialog.getText(self,
  2169. "Send raw command to programmer",
  2170. "Enter raw command to send, in " +\
  2171. "hex format (AABB1122...).\n" +\
  2172. "WARNING: The programmer will malfunction on invalid commands.",
  2173. QLineEdit.Normal,
  2174. self.previousRawCommand)
  2175. if not ok:
  2176. return
  2177. string = str(string).strip().upper()
  2178. string = stringRemoveChars(string, " \t\r\n")
  2179. if stringRemoveChars(string, "0123456789ABCDEF"):
  2180. QMessageBox.critical(self, "Invalid characters",
  2181. "Invalid characters in raw command string.\n" +\
  2182. "Only hex characters 0-9,a-f allowed.")
  2183. return
  2184. if len(string) % 2 != 0 or len(string) // 2 > 64:
  2185. QMessageBox.critical(self, "Invalid length",
  2186. "Invalid command length. Length must be even " +\
  2187. "and smaller or equal to 64 bytes.")
  2188. return
  2189. self.previousRawCommand = string
  2190. command = hex2bin(string)
  2191. if len(command) == 0:
  2192. return
  2193. self.runOperation(Operation(Operation.OP_RAWCOMMAND,
  2194. HwThread.TASK_GENERICTOPCALL,
  2195. GenericTopCall("top.hw.runCommandSync(...)", command)))
  2196. def loadBuffer(self):
  2197. bufWidget = self.bufferTab.getCurrentBuffer()
  2198. data = None
  2199. if not bufWidget:
  2200. return
  2201. if bufWidget.isReadOnly():
  2202. QMessageBox.critical(self, "Buffer is read only",
  2203. "Cannot load data into the %s buffer.\n"
  2204. "The buffer is read-only." %\
  2205. bufWidget.getName())
  2206. return
  2207. (fn, selectedFilter) = QFileDialog.getOpenFileName(self,
  2208. "%s - open file" % bufWidget.getName(),
  2209. "",
  2210. "Autodetect file format (*);;"
  2211. "Intel hex file (*.ihex *.hex);;"
  2212. "Hex file with ASCII dump (*.ahex);;"
  2213. "Binary file (*.bin)")
  2214. if not fn:
  2215. return
  2216. extensions = str(selectedFilter).split("(")[1].\
  2217. split(")")[0].replace("*", "").strip().split()
  2218. try:
  2219. dataIn = open(fn, "rb").read()
  2220. except (IOError), e:
  2221. QMessageBox.critical(self, "Failed to read file",
  2222. "Failed to read %s:\n%s" %\
  2223. (str(fn), str(e.strerror)))
  2224. return
  2225. try:
  2226. if ".bin" in extensions:
  2227. handler = IO_binary()
  2228. elif ".ahex" in extensions:
  2229. handler = IO_ahex()
  2230. elif ".ihex" in extensions:
  2231. handler = IO_ihex()
  2232. elif not extensions: # auto
  2233. handler = IO_autodetect(dataIn)()
  2234. else:
  2235. assert(0)
  2236. if isinstance(handler, IO_ihex):
  2237. interp = self.chip.getIHexInterpreter()
  2238. interp.interpret(dataIn)
  2239. if interp.cumulativeSupported():
  2240. res = QMessageBox.question(self,
  2241. "Parse IHEX sections?",
  2242. "This IHEX file might contain sections for "
  2243. "the different memory areas (progmem, eeprom, etc...).\n"
  2244. "\n"
  2245. "Should the sections be interpreted?\n"
  2246. "\n"
  2247. "If 'Yes' is selected, only the section corresponding "
  2248. "to the current buffer is extracted from the IHEX file.\n"
  2249. "If 'No' is selected, the IHEX file will be read "
  2250. "in raw mode and all of its data will be "
  2251. "put into the current buffer.",
  2252. QMessageBox.Yes | QMessageBox.No,
  2253. QMessageBox.Yes)
  2254. readRaw = (res != QMessageBox.Yes)
  2255. else:
  2256. readRaw = True
  2257. ok = bufWidget.setDataWithIHexInterpreter(interp, readRaw)
  2258. else:
  2259. ok = bufWidget.setRawData(handler.toBinary(dataIn))
  2260. if not ok:
  2261. QMessageBox.critical(self, "Failed to load data",
  2262. "Failed to load the file into the buffer")
  2263. except (TOPException), e:
  2264. QMessageBox.critical(self, "Failed to convert data",
  2265. "Failed to convert the input file data to binary\n%s" % str(e))
  2266. return
  2267. def saveBuffer(self):
  2268. bufWidget = self.bufferTab.getCurrentBuffer()
  2269. if not bufWidget:
  2270. return
  2271. data = bufWidget.getRawData()
  2272. if not data:
  2273. return
  2274. (fn, selectedFilter) = QFileDialog.getSaveFileName(self,
  2275. "%s - save file" % bufWidget.getName(),
  2276. "",
  2277. "Intel hex file (*.ihex *.hex);;"
  2278. "Hex file with ASCII dump (*.ahex);;"
  2279. "Binary file (*)")
  2280. if not fn:
  2281. return
  2282. extensions = str(selectedFilter).split("(")[1].\
  2283. split(")")[0].replace("*", "").strip().split()
  2284. if not extensions:
  2285. extensions = [ "" ]
  2286. if not '.' in fn or\
  2287. not '.' + fn.split('.')[-1] in extensions:
  2288. fn += extensions[0] # Default ext
  2289. if ".ihex" in extensions:
  2290. data = IO_ihex().fromBinary(data)
  2291. elif ".ahex" in extensions:
  2292. data = IO_ahex().fromBinary(data)
  2293. elif not extensions[0]:
  2294. data = IO_binary().fromBinary(data)
  2295. else:
  2296. assert(0)
  2297. try:
  2298. open(fn, "wb").write(data)
  2299. except (IOError), e:
  2300. QMessageBox.critical(self, "Failed to write file",
  2301. "Failed to write %s:\n%s" %\
  2302. (str(fn), str(e.strerror)))
  2303. return
  2304. def selectChip(self):
  2305. dlg = ChipSelectDialog(self)
  2306. if dlg.exec_() != QDialog.Accepted:
  2307. return
  2308. chipDescription = dlg.getSelectedChip()
  2309. if not chipDescription:
  2310. return
  2311. self.currentChipDescription = chipDescription
  2312. return self.runOperation(Operation(Operation.OP_INITCHIP,
  2313. HwThread.TASK_INITCHIP,
  2314. chipDescription.chipID))
  2315. def __makeReadCallChain(self, mayReadSig=True, mayReadProgmem=True,
  2316. mayReadEEPROM=True, mayReadFuse=True,
  2317. mayReadLockbits=True, mayReadRAM=True):
  2318. callChain = []
  2319. suppFlags = self.chip.getSupportFlags()
  2320. callChain.append(GenericTopCall("top.checkChip()",
  2321. name = "check"))
  2322. if mayReadSig and (suppFlags & Chip.SUPPORT_SIGREAD):
  2323. callChain.append(GenericTopCall("top.readSignature()",
  2324. name = "signature"))
  2325. if mayReadProgmem and (suppFlags & Chip.SUPPORT_PROGMEMREAD):
  2326. callChain.append(GenericTopCall("top.readProgmem()",
  2327. name = "progmem"))
  2328. if mayReadEEPROM and (suppFlags & Chip.SUPPORT_EEPROMREAD):
  2329. callChain.append(GenericTopCall("top.readEEPROM()",
  2330. name = "eeprom"))
  2331. if mayReadFuse and (suppFlags & Chip.SUPPORT_FUSEREAD):
  2332. callChain.append(GenericTopCall("top.readFuse()",
  2333. name = "fusebits"))
  2334. if mayReadLockbits and (suppFlags & Chip.SUPPORT_LOCKREAD):
  2335. callChain.append(GenericTopCall("top.readLockbits()",
  2336. name = "lockbits"))
  2337. if mayReadRAM and (suppFlags & Chip.SUPPORT_RAMREAD):
  2338. callChain.append(GenericTopCall("top.readRAM()",
  2339. name = "ram"))
  2340. return callChain
  2341. def __readCallChain_GetResultImages(self, callChain):
  2342. images = {}
  2343. for topCall in (callChain if callChain else []):
  2344. name = topCall.userData["name"]
  2345. if name in ("signature", "progmem", "eeprom",
  2346. "fusebits", "lockbits", "ram"):
  2347. images[name] = topCall.result
  2348. elif name == "check":
  2349. pass # Nothing to do
  2350. else:
  2351. assert(0)
  2352. return images
  2353. def readChip(self):
  2354. return self.runOperation(Operation(Operation.OP_READALL,
  2355. HwThread.TASK_GENERICTOPCALL,
  2356. self.__makeReadCallChain()))
  2357. def eraseChip(self):
  2358. return self.runOperation(Operation(Operation.OP_ERASE,
  2359. HwThread.TASK_GENERICTOPCALL,
  2360. GenericTopCall("top.eraseChip()")))
  2361. def writeChipProgmem(self):
  2362. bufferWidget = self.bufferTab.progmemBuffer
  2363. data = bufferWidget.getRawData()
  2364. if not bufferWidget.isAvailable() or not data:
  2365. QMessageBox.critical(self, "No program memory",
  2366. "No program memory available")
  2367. return False
  2368. return self.runOperation(Operation(Operation.OP_WRITEPROG,
  2369. HwThread.TASK_GENERICTOPCALL,
  2370. GenericTopCall("top.writeProgmem(...)", data)))
  2371. def writeChipEeprom(self):
  2372. bufferWidget = self.bufferTab.eepromBuffer
  2373. data = bufferWidget.getRawData()
  2374. if not bufferWidget.isAvailable() or not data:
  2375. QMessageBox.critical(self, "No (E)EPROM memory",
  2376. "No (E)EPROM memory available")
  2377. return False
  2378. return self.runOperation(Operation(Operation.OP_WRITEEPROM,
  2379. HwThread.TASK_GENERICTOPCALL,
  2380. GenericTopCall("top.writeEEPROM(...)", data)))
  2381. def writeChipFuses(self):
  2382. bufferWidget = self.bufferTab.fuseBuffer
  2383. data = bufferWidget.getRawData()
  2384. if not bufferWidget.isAvailable() or not data:
  2385. QMessageBox.critical(self, "No fuse bits",
  2386. "No fuse bits available")
  2387. return False
  2388. return self.runOperation(Operation(Operation.OP_WRITEFUSE,
  2389. HwThread.TASK_GENERICTOPCALL,
  2390. GenericTopCall("top.writeFuse(...)", data)))
  2391. def writeChipLockbits(self):
  2392. bufferWidget = self.bufferTab.lockBuffer
  2393. data = bufferWidget.getRawData()
  2394. if not bufferWidget.isAvailable() or not data:
  2395. QMessageBox.critical(self, "No lock bits",
  2396. "No lock bits available")
  2397. return False
  2398. return self.runOperation(Operation(Operation.OP_WRITELOCK,
  2399. HwThread.TASK_GENERICTOPCALL,
  2400. GenericTopCall("top.writeLockbits(...)", data)))
  2401. def writeRam(self):
  2402. bufferWidget = self.bufferTab.ramBuffer
  2403. data = bufferWidget.getRawData()
  2404. if not bufferWidget.isAvailable() or not data:
  2405. QMessageBox.critical(self, "No RAM memory",
  2406. "No RAM memory available")
  2407. return False
  2408. return self.runOperation(Operation(Operation.OP_WRITERAM,
  2409. HwThread.TASK_GENERICTOPCALL,
  2410. GenericTopCall("top.writeRAM(...)", data)))
  2411. def runTest(self):
  2412. return self.runOperation(Operation(Operation.OP_TEST,
  2413. HwThread.TASK_GENERICTOPCALL,
  2414. GenericTopCall("top.testChip()")))
  2415. def verifyChip(self):
  2416. return self.verifySelectedMemories() # defaults to "all".
  2417. def verifySelectedMemories(self, verifyProgmem=True,
  2418. verifyEEPROM=True,
  2419. verifyFuse=True,
  2420. verifyRAM=True):
  2421. callChain = self.__makeReadCallChain(
  2422. mayReadSig = False,
  2423. mayReadProgmem = verifyProgmem,
  2424. mayReadEEPROM = verifyEEPROM,
  2425. mayReadFuse = verifyFuse,
  2426. mayReadLockbits = False,
  2427. mayReadRAM = verifyRAM)
  2428. return self.runOperation(Operation(Operation.OP_VERIFY,
  2429. HwThread.TASK_GENERICTOPCALL,
  2430. callChain))
  2431. def guiUpdateEnable(self):
  2432. enable = not self.guiDisable and\
  2433. not self.threadRunning and\
  2434. not self.autorun.isRunning()
  2435. self.menuBar().setEnabled(enable)
  2436. self.topToolBar.setEnabled(enable)
  2437. self.rightToolBar.setEnabled(enable)
  2438. self.autorun.setEnabled(enable)
  2439. self.bufferTab.setEnabled(enable)
  2440. def cancelHardwareTask(self):
  2441. if self.autorun.isRunning():
  2442. self.autorun.abortRun()
  2443. if self.threadRunning:
  2444. self.hwThread.cancelTask()
  2445. def __triggerOperation(self, op, threadMutexIsLocked=False):
  2446. self.hwThread.triggerTask(op.hwTask, op.hwTaskParam,
  2447. id(op), threadMutexIsLocked)
  2448. self.threadRunning = True
  2449. self.runningOps[id(op)] = op
  2450. self.console.setTaskRunning(True)
  2451. self.guiUpdateEnable()
  2452. def __triggerNextOperation(self, threadMutexIsLocked=False):
  2453. assert(self.queuedOps)
  2454. op = self.queuedOps.pop(0)
  2455. self.__triggerOperation(op, threadMutexIsLocked)
  2456. def runOperation(self, op):
  2457. self.queuedOps.append(op)
  2458. if not self.threadRunning:
  2459. self.__triggerNextOperation()
  2460. return True
  2461. def runOperationSync(self, hwTask, taskParameter=None):
  2462. op = Operation(Operation.OP_SYNCHRONOUS,
  2463. hwTask, taskParameter)
  2464. self.runOperation(op)
  2465. while not op.finished:
  2466. QApplication.processEvents(QEventLoop.AllEvents, 50)
  2467. self.runningOps.pop(id(op))
  2468. return (op.failed, op.returnValue)
  2469. def setOperationFinished(self, failed):
  2470. self.console.setTaskRunning(running=False, success=not failed)
  2471. if self.autorun.isRunning():
  2472. if failed:
  2473. QTimer.singleShot(0, self.autorun.abortRunWithMessage)
  2474. else:
  2475. QTimer.singleShot(0, self.autorun.runNextAction)
  2476. def __hardwareTaskFinished(self, op):
  2477. if op.op == Operation.OP_SYNCHRONOUS:
  2478. self.console.setTaskRunning(running=False, success=True)
  2479. return
  2480. self.runningOps.pop(id(op))
  2481. if op.failed:
  2482. self.console.showMessage("[op %d task %d failed] %s\n" %\
  2483. (op.op, op.hwTask, str(op.returnValue)),
  2484. bold=True)
  2485. self.setOperationFinished(failed=True)
  2486. return
  2487. # Task succeed
  2488. if op.op == Operation.OP_INITCHIP:
  2489. assert(op.hwTask == HwThread.TASK_INITCHIP)
  2490. (self.chip, asciiArtLayout) = op.returnValue
  2491. self.bufferTab.setupBuffers(self.chip.getSupportFlags())
  2492. self.bufferTab.infoBuffer.clear()
  2493. self.bufferTab.infoBuffer.setupDescription(self.currentChipDescription)
  2494. self.bufferTab.infoBuffer.setChipLayout(asciiArtLayout)
  2495. self.autorun.setup(self.chip.getSupportFlags())
  2496. self.topToolBar.setup(self.chip.getSupportFlags())
  2497. self.rightToolBar.setup(self.chip.getSupportFlags())
  2498. self.setupRunMenu(self.chip.getSupportFlags())
  2499. elif op.op == Operation.OP_SHUTDOWN:
  2500. pass # Nothing to do
  2501. elif op.op == Operation.OP_READALL:
  2502. assert(op.hwTask == HwThread.TASK_GENERICTOPCALL)
  2503. topCallList = op.returnValue
  2504. images = self.__readCallChain_GetResultImages(topCallList)
  2505. self.bufferTab.setupBuffers(self.chip.getSupportFlags())
  2506. self.bufferTab.loadBuffers(images)
  2507. try:
  2508. self.bufferTab.infoBuffer.setChipSignature(images["signature"])
  2509. except KeyError:
  2510. pass
  2511. elif op.op == Operation.OP_ERASE:
  2512. pass # Nothing to do
  2513. elif op.op == Operation.OP_WRITEPROG:
  2514. pass # Nothing to do
  2515. elif op.op == Operation.OP_WRITEEPROM:
  2516. pass # Nothing to do
  2517. elif op.op == Operation.OP_WRITEFUSE:
  2518. pass # Nothing to do
  2519. elif op.op == Operation.OP_WRITELOCK:
  2520. pass # Nothing to do
  2521. elif op.op == Operation.OP_WRITERAM:
  2522. pass # Nothing to do
  2523. elif op.op == Operation.OP_TEST:
  2524. self.console.showMessage("Unit-test success. The chip seems to be OK.\n",
  2525. bold=True)
  2526. elif op.op == Operation.OP_VERIFY:
  2527. assert(op.hwTask == HwThread.TASK_GENERICTOPCALL)
  2528. topCallList = op.returnValue
  2529. images = self.__readCallChain_GetResultImages(topCallList)
  2530. op.failed = not self.bufferTab.verifyBuffers(images)
  2531. elif op.op == Operation.OP_RAWCOMMAND:
  2532. self.console.showMessage("Successfully sent raw command\n", bold=True)
  2533. else:
  2534. print "ERROR: No handler for op %d task %d" % (op.op, op.hwTask)
  2535. self.setOperationFinished(op.failed)
  2536. def hardwareTaskFinished(self, opaqueId, failed, returnValue):
  2537. if opaqueId is None:
  2538. return
  2539. op = self.runningOps[opaqueId]
  2540. op.returnValue = returnValue
  2541. op.failed = failed
  2542. self.threadRunning = False
  2543. self.__hardwareTaskFinished(op)
  2544. op.op = Operation.OP_NONE
  2545. op.finished = True
  2546. if self.queuedOps:
  2547. self.__triggerNextOperation(threadMutexIsLocked=True)
  2548. return
  2549. self.guiUpdateEnable()
  2550. def main():
  2551. app = QApplication(sys.argv)
  2552. mainwnd = MainWindow()
  2553. mainwnd.show()
  2554. mainwnd.resize(int(mainwnd.width() * 1.6),
  2555. int(mainwnd.height() * 1.2))
  2556. return app.exec_()
  2557. if __name__ == "__main__":
  2558. sys.exit(main())