Moved board definition from apimote to apimote1 for versioning support.
[goodfet] / client / GoodFET.py
1 #!/usr/bin/env python
2 # GoodFET Client Library
3
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is being rewritten and refactored.  You've been warned!
7
8 import sys, time, string, cStringIO, struct, glob, os;
9 import sqlite3;
10
11 fmt = ("B", "<H", None, "<L")
12
13 def getClient(name="GoodFET"):
14     import GoodFET, GoodFETCC, GoodFETAVR, GoodFETSPI, GoodFETMSP430, GoodFETNRF, GoodFETCCSPI;
15     if(name=="GoodFET" or name=="monitor"): return GoodFET.GoodFET();
16     elif name=="cc" or name=="cc51": return GoodFETCC.GoodFETCC();
17     elif name=="cc2420" or name=="ccspi": return GoodFETCCSPI.GoodFETCCSPI();
18     elif name=="avr": return GoodFETAVR.GoodFETAVR();
19     elif name=="spi": return GoodFETSPI.GoodFETSPI();
20     elif name=="msp430": return GoodFETMSP430.GoodFETMSP430();
21     elif name=="nrf": return GoodFETNRF.GoodFETNRF();
22     
23     print "Unsupported target: %s" % name;
24     sys.exit(0);
25
26 class SymbolTable:
27     """GoodFET Symbol Table"""
28     db=sqlite3.connect(":memory:");
29     
30     def __init__(self, *args, **kargs):
31         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
32     def get(self,name):
33         self.db.commit();
34         c=self.db.cursor();
35         try:
36             c.execute("select adr,memory from symbols where name=?",(name,));
37             for row in c:
38                 #print "Found it.";
39                 sys.stdout.flush();
40                 return row[0];
41             #print "No dice.";
42         except:# sqlite3.OperationalError:
43             #print "SQL error.";
44             return eval(name);
45         return eval(name);
46     def define(self,adr,name,comment="",memory="vn",size=16):
47         self.db.execute("insert into symbols(adr,name,memory,size,comment)"
48                         "values(?,?,?,?,?);", (
49                 adr,name,memory,size,comment));
50         #print "Set %s=%s." % (name,adr);
51 class GoodFETbtser:
52     """py-bluez class for emulating py-serial."""
53     def __init__(self,btaddr):
54         import bluetooth;
55         if btaddr==None or btaddr=="none" or btaddr=="bluetooth":
56             print "performing inquiry..."
57             nearby_devices = bluetooth.discover_devices(lookup_names = True)
58             print "found %d devices" % len(nearby_devices)
59             for addr, name in nearby_devices:
60                 print "  %s - '%s'" % (addr, name)
61                 #TODO switch to wildcards.
62                 if name=='FireFly-A6BD':
63                     btaddr=addr;
64                 if name=='RN42-A94A':
65                     btaddr=addr;
66                 
67             print "Please set $GOODFET to the address of your device.";
68             sys.exit();
69         print "Identified GoodFET at %s" % btaddr;
70
71         # Manually use the portnumber.
72         port=1;
73         
74         print "Connecting to %s on port %i." % (btaddr, port);
75         sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
76         self.sock=sock;
77         sock.connect((btaddr,port));
78         sock.settimeout(10);  #IMPORTANT Must be patient.
79         
80         ##This is what we'd do for a normal reset.
81         #str="";
82         #while not str.endswith("goodfet.sf.net/"):
83         #    str=self.read(64);
84         #    print str;
85         
86         # Instead, just return and hope for the best.
87         return;
88         
89     def write(self,msg):
90         """Send traffic."""
91         import time;
92         self.sock.send(msg);
93         #time.sleep(0.1);
94         return;
95     def read(self,length):
96         """Read traffic."""
97         data="";
98         while len(data)<length:
99             data=data+self.sock.recv(length-len(data));
100         return data;
101 class GoodFET:
102     """GoodFET Client Library"""
103
104     besilent=0;
105     app=0;
106     verb=0;
107     count=0;
108     data="";
109     verbose=False
110     
111     GLITCHAPP=0x71;
112     MONITORAPP=0x00;
113     symbols=SymbolTable();
114     
115     def __init__(self, *args, **kargs):
116         self.data=[0];
117     def getConsole(self):
118         from GoodFETConsole import GoodFETConsole;
119         return GoodFETConsole(self);
120     def name2adr(self,name):
121         return self.symbols.get(name);
122     def timeout(self):
123         print "timeout\n";
124     def serInit(self, port=None, timeout=2, attemptlimit=None):
125         """Open a serial port of some kind."""
126         import re;
127         
128         if port==None:
129             port=os.environ.get("GOODFET");
130         if port=="bluetooth" or (port is not None and re.match("..:..:..:..:..:..",port)):
131             self.btInit(port,timeout,attemptlimit);
132         else:
133             self.pyserInit(port,timeout,attemptlimit);
134     def btInit(self, port, timeout, attemptlimit):
135         """Open a bluetooth port.""";
136         #self.verbose=True;  #For debugging BT.
137         self.serialport=GoodFETbtser(port);
138         
139     def pyserInit(self, port, timeout, attemptlimit):
140         """Open the serial port"""
141         # Make timeout None to wait forever, 0 for non-blocking mode.
142         import serial;
143         
144         if os.name=='nt' and sys.version.find('64 bit')!=-1:
145             print "WARNING: PySerial requires a 32-bit Python build in Windows.";
146         
147         if port is None and os.environ.get("GOODFET")!=None:
148             glob_list = glob.glob(os.environ.get("GOODFET"));
149             if len(glob_list) > 0:
150                 port = glob_list[0];
151             else:
152                 port = os.environ.get("GOODFET");
153         if port is None:
154             glob_list = glob.glob("/dev/tty.usbserial*");
155             if len(glob_list) > 0:
156                 port = glob_list[0];
157         if port is None:
158             glob_list = glob.glob("/dev/ttyUSB*");
159             if len(glob_list) > 0:
160                 port = glob_list[0];
161         if port is None:
162             glob_list = glob.glob("/dev/ttyU0");
163             if len(glob_list) > 0:
164                 port = glob_list[0];
165         if port is None and os.name=='nt':
166             from scanwin32 import winScan;
167             scan=winScan();
168             for order,comport,desc,hwid in sorted(scan.comports()):
169                 try:
170                     if hwid.index('FTDI')==0:
171                         port=comport;
172                         #print "Using FTDI port %s" % port
173                 except:
174                     #Do nothing.
175                     a=1;
176         
177         baud=115200;
178         if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
179             baud=19200; #Slower, for now.
180         self.serialport = serial.Serial(
181             port,
182             #9600,
183             baud,
184             parity = serial.PARITY_NONE,
185             timeout=timeout
186             )
187         
188         self.verb=0;
189         attempts=0;
190         connected=0;
191         while connected==0:
192             while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
193             #while self.data!="http://goodfet.sf.net/":
194                 #print "'%s'!=\n'%s'" % (self.data,"http://goodfet.sf.net/");
195                 if attemptlimit is not None and attempts >= attemptlimit:
196                     return
197                 elif attempts>2:
198                     print "Resyncing.";
199                 self.serialport.flushInput()
200                 self.serialport.flushOutput()
201                 
202                 #TelosB reset, prefer software to I2C SPST Switch.
203                 if (os.environ.get("platform")=='telosb' or  os.environ.get("board")=='telosb'):
204                     #print "TelosB Reset";
205                     self.telosBReset();
206                 elif (os.environ.get("board")=='zolertiaz1' or  os.environ.get("board")=='z1'):
207                     self.bslResetZ1();
208                 elif (os.environ.get("board")=='apimote1'):
209                     #Explicitly set RTS and DTR to halt board.
210                     self.serialport.setRTS(1);
211                     self.serialport.setDTR(1);
212                     #RTS pin, not DTR is used for reset.
213                     self.serialport.setRTS(0);
214                     #print "Resetting Apimote not yet tested.";
215                 else:
216                     #Explicitly set RTS and DTR to halt board.
217                     self.serialport.setRTS(1);
218                     self.serialport.setDTR(1);
219                     #Drop DTR, which is !RST, low to begin the app.
220                     self.serialport.setDTR(0);
221                 
222                 #self.serialport.write(chr(0x80));
223                 #self.serialport.write(chr(0x80));
224                 #self.serialport.write(chr(0x80));
225                 #self.serialport.write(chr(0x80));
226                 
227                 
228                 #self.serialport.flushInput()
229                 #self.serialport.flushOutput()
230                 #time.sleep(60);
231                 attempts=attempts+1;
232                 self.readcmd(); #Read the first command.
233                 #print "Got %02x,%02x:'%s'" % (self.app,self.verb,self.data);
234             #Here we have a connection, but maybe not a good one.
235             #print "We have a connection."
236             connected=1;
237             olds=self.infostring();
238             clocking=self.monitorclocking();
239             for foo in range(1,30):
240                 if not self.monitorecho():
241                     if self.verbose:
242                         print "Comm error on %i try, resyncing out of %s." % (foo,
243                                                                               clocking);
244                         connected=0;
245                         break;
246         if self.verbose: print "Connected after %02i attempts." % attempts;
247         self.mon_connected();
248         self.serialport.setTimeout(12);
249     def serClose(self):
250         self.serialport.close();
251     def telosSetSCL(self, level):
252         self.serialport.setRTS(not level)
253     def telosSetSDA(self, level):
254         self.serialport.setDTR(not level)
255
256     def telosI2CStart(self):
257         self.telosSetSDA(1)
258         self.telosSetSCL(1)
259         self.telosSetSDA(0)
260
261     def telosI2CStop(self):
262         self.telosSetSDA(0)
263         self.telosSetSCL(1)
264         self.telosSetSDA(1)
265
266     def telosI2CWriteBit(self, bit):
267         self.telosSetSCL(0)
268         self.telosSetSDA(bit)
269         time.sleep(2e-6)
270         self.telosSetSCL(1)
271         time.sleep(1e-6)
272         self.telosSetSCL(0)
273
274     def telosI2CWriteByte(self, byte):
275         self.telosI2CWriteBit( byte & 0x80 );
276         self.telosI2CWriteBit( byte & 0x40 );
277         self.telosI2CWriteBit( byte & 0x20 );
278         self.telosI2CWriteBit( byte & 0x10 );
279         self.telosI2CWriteBit( byte & 0x08 );
280         self.telosI2CWriteBit( byte & 0x04 );
281         self.telosI2CWriteBit( byte & 0x02 );
282         self.telosI2CWriteBit( byte & 0x01 );
283         self.telosI2CWriteBit( 0 );  # "acknowledge"
284
285     def telosI2CWriteCmd(self, addr, cmdbyte):
286         self.telosI2CStart()
287         self.telosI2CWriteByte( 0x90 | (addr << 1) )
288         self.telosI2CWriteByte( cmdbyte )
289         self.telosI2CStop()
290     def bslResetZ1(self, invokeBSL=0):
291         '''
292         Applies BSL entry sequence on RST/NMI and TEST/VPP pins
293         Parameters:
294             invokeBSL = 1: complete sequence
295             invokeBSL = 0: only RST/NMI pin accessed
296             
297         By now only BSL mode is accessed
298         '''
299         
300         #if DEBUG > 1: sys.stderr.write("* bslReset(invokeBSL=%s)\n" % invokeBSL)
301         if invokeBSL:
302             #sys.stderr.write("in Z1 bsl reset...\n")
303             time.sleep(0.1)
304             self.writepicROM(0xFF, 0xFF)
305             time.sleep(0.1)
306             #sys.stderr.write("z1 bsl reset done...\n")
307         else:
308             #sys.stderr.write("in Z1 reset...\n")
309             time.sleep(0.1)
310             self.writepicROM(0xFF, 0xFE)
311             time.sleep(0.1)
312             #sys.stderr.write("z1 reset done...\n")
313     def writepicROM(self, address, data):
314         ''' Writes data to @address'''
315         for i in range(7,-1,-1):
316             self.picROMclock((address >> i) & 0x01)
317         self.picROMclock(0)
318         recbuf = 0
319         for i in range(7,-1,-1):
320             s = ((data >> i) & 0x01)
321             #print s
322             if i < 1:
323                 r = not self.picROMclock(s, True)
324             else:
325                 r = not self.picROMclock(s)
326             recbuf = (recbuf << 1) + r
327
328         self.picROMclock(0, True)
329         #k = 1
330         #while not self.serial.getCTS():
331         #    pass 
332         #time.sleep(0.1)
333         return recbuf
334     def readpicROM(self, address):
335         ''' reads a byte from @address'''
336         for i in range(7,-1,-1):
337             self.picROMclock((address >> i) & 0x01)
338         self.picROMclock(1)
339         recbuf = 0
340         r = 0
341         for i in range(7,-1,-1):
342             r = self.picROMclock(0)
343             recbuf = (recbuf << 1) + r
344         self.picROMclock(r)
345         #time.sleep(0.1)
346         return recbuf
347         
348     def picROMclock(self, masterout, slow = False):
349         #print "setting masterout to "+str(masterout)
350         self.serialport.setRTS(masterout)
351         self.serialport.setDTR(1)
352         #time.sleep(0.02)
353         self.serialport.setDTR(0)
354         if slow:
355             time.sleep(0.02)
356         return self.serialport.getCTS()
357
358     def picROMfastclock(self, masterout):
359         #print "setting masterout to "+str(masterout)
360         self.serialport.setRTS(masterout)
361         self.serialport.setDTR(1)
362         self.serialport.setDTR(0)
363         time.sleep(0.02)
364         return self.serialport.getCTS()
365
366     def telosBReset(self,invokeBSL=0):
367         # "BSL entry sequence at dedicated JTAG pins"
368         # rst !s0: 0 0 0 0 1 1
369         # tck !s1: 1 0 1 0 0 1
370         #   s0|s1: 1 3 1 3 2 0
371
372         # "BSL entry sequence at shared JTAG pins"
373         # rst !s0: 0 0 0 0 1 1
374         # tck !s1: 0 1 0 1 1 0
375         #   s0|s1: 3 1 3 1 0 2
376
377         if invokeBSL:
378             self.telosI2CWriteCmd(0,1)
379             self.telosI2CWriteCmd(0,3)
380             self.telosI2CWriteCmd(0,1)
381             self.telosI2CWriteCmd(0,3)
382             self.telosI2CWriteCmd(0,2)
383             self.telosI2CWriteCmd(0,0)
384         else:
385             self.telosI2CWriteCmd(0,3)
386             self.telosI2CWriteCmd(0,2)
387
388         # This line was not defined inside the else: block, not sure where it
389         # should be however
390         self.telosI2CWriteCmd(0,0)
391         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
392         self.serialport.flushInput()  #clear buffers
393
394
395     def getbuffer(self,size=0x1c00):
396         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
397         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
398     def writecmd(self, app, verb, count=0, data=[]):
399         """Write a command and some data to the GoodFET."""
400         self.serialport.write(chr(app));
401         self.serialport.write(chr(verb));
402         
403         #if data!=None:
404         #    count=len(data); #Initial count ignored.
405         
406         #print "TX %02x %02x %04x" % (app,verb,count);
407         
408         #little endian 16-bit length
409         self.serialport.write(chr(count&0xFF));
410         self.serialport.write(chr(count>>8));
411
412         if self.verbose:
413             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
414         
415         #print "count=%02x, len(data)=%04x" % (count,len(data));
416         
417         if count!=0:
418             if(isinstance(data,list)):
419                 for i in range(0,count):
420                 #print "Converting %02x at %i" % (data[i],i)
421                     data[i]=chr(data[i]);
422             #print type(data);
423             outstr=''.join(data);
424             self.serialport.write(outstr);
425         if not self.besilent:
426             return self.readcmd()
427         else:
428             return []
429
430     def readcmd(self):
431         """Read a reply from the GoodFET."""
432         while 1:#self.serialport.inWaiting(): # Loop while input data is available
433             try:
434                 #print "Reading...";
435                 self.app=ord(self.serialport.read(1));
436                 #print "APP=%02x" % self.app;
437                 self.verb=ord(self.serialport.read(1));
438                 
439                 #Fixes an obscure bug in the TelosB.
440                 if self.app==0x00:
441                     while self.verb==0x00:
442                         self.verb=ord(self.serialport.read(1));
443                 
444                 #print "VERB=%02x" % self.verb;
445                 self.count=(
446                     ord(self.serialport.read(1))
447                     +(ord(self.serialport.read(1))<<8)
448                     );
449
450                 if self.verbose:
451                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
452             
453                 #Debugging string; print, but wait.
454                 if self.app==0xFF:
455                     if self.verb==0xFF:
456                         print "# DEBUG %s" % self.serialport.read(self.count)
457                     elif self.verb==0xFE:
458                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
459                     elif self.verb==0xFD:
460                         #Do nothing, just wait so there's no timeout.
461                         print "# NOP.";
462                         
463                     sys.stdout.flush();
464                 else:
465                     self.data=self.serialport.read(self.count);
466                     return self.data;
467             except TypeError:
468                 if self.connected:
469                     print "Warning: waiting for serial read timed out (most likely).";
470                     #print "This shouldn't happen after syncing.  Exiting for safety.";                    
471                     #sys.exit(-1)
472                 return self.data;
473     #Glitching stuff.
474     def glitchApp(self,app):
475         """Glitch into a device by its application."""
476         self.data=[app&0xff];
477         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
478         #return ord(self.data[0]);
479     def glitchVerb(self,app,verb,data):
480         """Glitch during a transaction."""
481         if data==None: data=[];
482         self.data=[app&0xff, verb&0xFF]+data;
483         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
484         #return ord(self.data[0]);
485     def glitchstart(self):
486         """Glitch into the AVR application."""
487         self.glitchVerb(self.APP,0x20,None);
488     def glitchstarttime(self):
489         """Measure the timer of the START verb."""
490         return self.glitchTime(self.APP,0x20,None);
491     def glitchTime(self,app,verb,data):
492         """Time the execution of a verb."""
493         if data==None: data=[];
494         self.data=[app&0xff, verb&0xFF]+data;
495         print "Timing app %02x verb %02x." % (app,verb);
496         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
497         time=ord(self.data[0])+(ord(self.data[1])<<8);
498         print "Timed to be %i." % time;
499         return time;
500     def glitchVoltages(self,low=0x0880, high=0x0fff):
501         """Set glitching voltages. (0x0fff is max.)"""
502         self.data=[low&0xff, (low>>8)&0xff,
503                    high&0xff, (high>>8)&0xff];
504         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
505         #return ord(self.data[0]);
506     def glitchRate(self,count=0x0800):
507         """Set glitching count period."""
508         self.data=[count&0xff, (count>>8)&0xff];
509         self.writecmd(self.GLITCHAPP,0x91,2,
510                       self.data);
511         #return ord(self.data[0]);
512     
513     
514     #Monitor stuff
515     def silent(self,s=0):
516         """Transmissions halted when 1."""
517         self.besilent=s;
518         print "besilent is %i" % self.besilent;
519         self.writecmd(0,0xB0,1,[s]);
520     connected=0;
521     def mon_connected(self):
522         """Announce to the monitor that the connection is good."""
523         self.connected=1;
524         self.writecmd(0,0xB1,0,[]);
525     def out(self,byte):
526         """Write a byte to P5OUT."""
527         self.writecmd(0,0xA1,1,[byte]);
528     def dir(self,byte):
529         """Write a byte to P5DIR."""
530         self.writecmd(0,0xA0,1,[byte]);
531     def call(self,adr):
532         """Call to an address."""
533         self.writecmd(0,0x30,2,
534                       [adr&0xFF,(adr>>8)&0xFF]);
535     def execute(self,code):
536         """Execute supplied code."""
537         self.writecmd(0,0x31,2,#len(code),
538                       code);
539     def MONpeek8(self,address):
540         """Read a byte of memory from the monitor."""
541         self.data=[address&0xff,address>>8];
542         self.writecmd(0,0x02,2,self.data);
543         #self.readcmd();
544         return ord(self.data[0]);
545     def MONpeek16(self,address):
546         """Read a word of memory from the monitor."""
547         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
548     def peek(self,address):
549         """Read a word of memory from the monitor."""
550         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
551     def eeprompeek(self,address):
552         """Read a word of memory from the monitor."""
553         print "EEPROM peeking not supported for the monitor.";
554         #return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
555     def peekbysym(self,name):
556         """Read a value by its symbol name."""
557         #TODO include memory in symbol.
558         reg=self.symbols.get(name);
559         return self.peek8(reg,"data");
560     def pokebysym(self,name,val):
561         """Write a value by its symbol name."""
562         #TODO include memory in symbol.
563         reg=self.symbols.get(name);
564         return self.pokebyte(reg,val);
565     def pokebyte(self,address,value,memory="vn"):
566         """Set a byte of memory by the monitor."""
567         self.data=[address&0xff,address>>8,value];
568         self.writecmd(0,0x03,3,self.data);
569         return ord(self.data[0]);
570     def poke16(self,address,value):
571         """Set a word of memory by the monitor."""
572         self.pokebyte(address,value&0xFF);
573         self.pokebyte(address,(value>>8)&0xFF);
574         return value;
575     def setsecret(self,value):
576         """Set a secret word for later retreival.  Used by glitcher."""
577         #self.eeprompoke(0,value);
578         #self.eeprompoke(1,value);
579         print "Secret setting is not yet suppored for this target.";
580         print "Aborting.";
581         
582     def getsecret(self):
583         """Get a secret word.  Used by glitcher."""
584         #self.eeprompeek(0);
585         print "Secret getting is not yet suppored for this target.";
586         print "Aborting.";
587         sys.exit();
588     
589     def dumpmem(self,begin,end):
590         i=begin;
591         while i<end:
592             print "%04x %04x" % (i, self.MONpeek16(i));
593             i+=2;
594     def monitor_ram_pattern(self):
595         """Overwrite all of RAM with 0xBEEF."""
596         self.writecmd(0,0x90,0,self.data);
597         return;
598     def monitor_ram_depth(self):
599         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
600         self.writecmd(0,0x91,0,self.data);
601         return ord(self.data[0])+(ord(self.data[1])<<8);
602     
603     #Baud rates.
604     baudrates=[115200, 
605                9600,
606                19200,
607                38400,
608                57600,
609                115200];
610     def setBaud(self,baud):
611         """Change the baud rate.  TODO fix this."""
612         rates=self.baudrates;
613         self.data=[baud];
614         print "Changing FET baud."
615         self.serialport.write(chr(0x00));
616         self.serialport.write(chr(0x80));
617         self.serialport.write(chr(1));
618         self.serialport.write(chr(baud));
619         
620         print "Changed host baud."
621         self.serialport.setBaudrate(rates[baud]);
622         time.sleep(1);
623         self.serialport.flushInput()
624         self.serialport.flushOutput()
625         
626         print "Baud is now %i." % rates[baud];
627         return;
628     def readbyte(self):
629         return ord(self.serialport.read(1));
630     def findbaud(self):
631         for r in self.baudrates:
632             print "\nTrying %i" % r;
633             self.serialport.setBaudrate(r);
634             #time.sleep(1);
635             self.serialport.flushInput()
636             self.serialport.flushOutput()
637             
638             for i in range(1,10):
639                 self.readbyte();
640             
641             print "Read %02x %02x %02x %02x" % (
642                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
643     def monitortest(self):
644         """Self-test several functions through the monitor."""
645         print "Performing monitor self-test.";
646         self.monitorclocking();
647         for f in range(0,3000):
648             a=self.MONpeek16(0x0c00);
649             b=self.MONpeek16(0x0c02);
650             if a!=0x0c04 and a!=0x0c06:
651                 print "ERROR Fetched %04x, %04x" % (a,b);
652             self.pokebyte(0x0021,0); #Drop LED
653             if self.MONpeek8(0x0021)!=0:
654                 print "ERROR, P1OUT not cleared.";
655             self.pokebyte(0x0021,1); #Light LED
656             if not self.monitorecho():
657                 print "Echo test failed.";
658         print "Self-test complete.";
659         self.monitorclocking();
660     def monitorecho(self):
661         data="The quick brown fox jumped over the lazy dog.";
662         self.writecmd(self.MONITORAPP,0x81,len(data),data);
663         if self.data!=data:
664             print "Comm error recognized by monitorecho(), got:\n%s" % self.data;
665             return 0;
666         return 1;
667
668     def monitor_info(self):
669         print "GoodFET with %s MCU" % self.infostring();
670         print "Clocked at %s" % self.monitorclocking();
671         return 1;
672
673     def testleds(self):
674         print "Flashing LEDs"
675         self.writecmd(self.MONITORAPP,0xD0,0,"");
676         try:
677             print "Flashed %d LED." % ord(self.data)
678         except:
679             print "Unable to process response:", self.data
680
681     def monitor_list_apps(self, full=False): 
682         self.monitor_info()
683         old_value = self.besilent
684         self.besilent = True    # turn off automatic call to readcmd
685         self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
686         self.besilent = old_value
687         
688         # read the build date string 
689         self.readcmd()
690         print "Build Date: %s" % self.data
691         print "Firmware apps:"
692         while True:
693             self.readcmd()
694             if self.count == 0:
695                 break
696             print self.data
697         return 1;
698
699     def monitorclocking(self):
700         """Return the 16-bit clocking value."""
701         return "0x%04x" % self.monitorgetclock();
702     
703     def monitorsetclock(self,clock):
704         """Set the clocking value."""
705         self.MONpoke16(0x56, clock);
706     def monitorgetclock(self):
707         """Get the clocking value."""
708         if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
709             return 0xDEAD;
710         #Check for MSP430 before peeking this.
711         return self.MONpeek16(0x56);
712     # The following functions ought to be implemented in
713     # every client.
714     
715     def infostring(self):
716         if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
717             return "Arduino";
718         else:
719             a=self.MONpeek8(0xff0);
720             b=self.MONpeek8(0xff1);
721             return "%02x%02x" % (a,b);
722     def lock(self):
723         print "Locking Unsupported.";
724     def erase(self):
725         print "Erasure Unsupported.";
726     def setup(self):
727         return;
728     def start(self):
729         return;
730     def test(self):
731         print "Unimplemented.";
732         return;
733     def status(self):
734         print "Unimplemented.";
735         return;
736     def halt(self):
737         print "Unimplemented.";
738         return;
739     def resume(self):
740         print "Unimplemented.";
741         return;
742     def getpc(self):
743         print "Unimplemented.";
744         return 0xdead;
745     def flash(self,file):
746         """Flash an intel hex file to code memory."""
747         print "Flash not implemented.";
748     def dump(self,file,start=0,stop=0xffff):
749         """Dump an intel hex file from code memory."""
750         print "Dump not implemented.";
751     def peek32(self,address, memory="vn"):
752         """Peek 32 bits."""
753         return (self.peek16(address,memory)+
754                 (self.peek16(address+2,memory)<<16));
755     def peek16(self,address, memory="vn"):
756         """Peek 16 bits of memory."""
757         return (self.peek8(address,memory)+
758                 (self.peek8(address+1,memory)<<8));
759     def peek8(self,address, memory="vn"):
760         """Peek a byte of memory."""
761         return self.MONpeek8(address); #monitor
762     def peekblock(self,address,length,memory="vn"):
763         """Return a block of data."""
764         data=range(0,length);
765         for foo in range(0,length):
766             data[foo]=self.peek8(address+foo,memory);
767         return data;
768     def pokeblock(self,address,bytes,memory="vn"):
769         """Poke a block of a data into memory at an address."""
770         for foo in bytes:
771             self.pokebyte(address,foo,memory);
772             address=address+1;
773         return;
774     def loadsymbols(self):
775         """Load symbols from a file."""
776         return;