Now either apimote1 or apimote works as apimote name.
[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,2,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.  See the GoodFET FAQ about missing info flash.";
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(invokeBSL=0);
208                 elif (os.environ.get("board")=='apimote1') or (os.environ.get("board")=='apimote'):
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                 if self.verb!=0x7f:
235                     #Retry again. This usually times out, but helps connect.
236                     self.readcmd();
237                     #print "Retry got %02x,%02x:'%s'" % (self.app,self.verb,self.data);
238             #Here we have a connection, but maybe not a good one.
239             #print "We have a connection."
240             connected=1;
241             olds=self.infostring();
242             clocking=self.monitorclocking();
243             for foo in range(1,30):
244                 if not self.monitorecho():
245                     if self.verbose:
246                         print "Comm error on %i try, resyncing out of %s." % (foo,
247                                                                               clocking);
248                         connected=0;
249                         break;
250         if self.verbose: print "Connected after %02i attempts." % attempts;
251         self.mon_connected();
252         self.serialport.setTimeout(12);
253     def serClose(self):
254         self.serialport.close();
255     def telosSetSCL(self, level):
256         self.serialport.setRTS(not level)
257     def telosSetSDA(self, level):
258         self.serialport.setDTR(not level)
259
260     def telosI2CStart(self):
261         self.telosSetSDA(1)
262         self.telosSetSCL(1)
263         self.telosSetSDA(0)
264
265     def telosI2CStop(self):
266         self.telosSetSDA(0)
267         self.telosSetSCL(1)
268         self.telosSetSDA(1)
269
270     def telosI2CWriteBit(self, bit):
271         self.telosSetSCL(0)
272         self.telosSetSDA(bit)
273         time.sleep(2e-6)
274         self.telosSetSCL(1)
275         time.sleep(1e-6)
276         self.telosSetSCL(0)
277
278     def telosI2CWriteByte(self, byte):
279         self.telosI2CWriteBit( byte & 0x80 );
280         self.telosI2CWriteBit( byte & 0x40 );
281         self.telosI2CWriteBit( byte & 0x20 );
282         self.telosI2CWriteBit( byte & 0x10 );
283         self.telosI2CWriteBit( byte & 0x08 );
284         self.telosI2CWriteBit( byte & 0x04 );
285         self.telosI2CWriteBit( byte & 0x02 );
286         self.telosI2CWriteBit( byte & 0x01 );
287         self.telosI2CWriteBit( 0 );  # "acknowledge"
288
289     def telosI2CWriteCmd(self, addr, cmdbyte):
290         self.telosI2CStart()
291         self.telosI2CWriteByte( 0x90 | (addr << 1) )
292         self.telosI2CWriteByte( cmdbyte )
293         self.telosI2CStop()
294     def bslResetZ1(self, invokeBSL=0):
295         '''
296         Applies BSL entry sequence on RST/NMI and TEST/VPP pins
297         Parameters:
298             invokeBSL = 1: complete sequence
299             invokeBSL = 0: only RST/NMI pin accessed
300             
301         By now only BSL mode is accessed
302         '''
303         
304         #if DEBUG > 1: sys.stderr.write("* bslReset(invokeBSL=%s)\n" % invokeBSL)
305         if invokeBSL:
306             #sys.stderr.write("in Z1 bsl reset...\n")
307             time.sleep(0.1)
308             self.writepicROM(0xFF, 0xFF)
309             time.sleep(0.1)
310             #sys.stderr.write("z1 bsl reset done...\n")
311         else:
312             #sys.stderr.write("in Z1 reset...\n")
313             time.sleep(0.1)
314             self.writepicROM(0xFF, 0xFE)
315             time.sleep(0.1)
316             #sys.stderr.write("z1 reset done...\n")
317     def writepicROM(self, address, data):
318         ''' Writes data to @address'''
319         for i in range(7,-1,-1):
320             self.picROMclock((address >> i) & 0x01)
321         self.picROMclock(0)
322         recbuf = 0
323         for i in range(7,-1,-1):
324             s = ((data >> i) & 0x01)
325             #print s
326             if i < 1:
327                 r = not self.picROMclock(s, True)
328             else:
329                 r = not self.picROMclock(s)
330             recbuf = (recbuf << 1) + r
331
332         self.picROMclock(0, True)
333         #k = 1
334         #while not self.serial.getCTS():
335         #    pass 
336         #time.sleep(0.1)
337         return recbuf
338     def readpicROM(self, address):
339         ''' reads a byte from @address'''
340         for i in range(7,-1,-1):
341             self.picROMclock((address >> i) & 0x01)
342         self.picROMclock(1)
343         recbuf = 0
344         r = 0
345         for i in range(7,-1,-1):
346             r = self.picROMclock(0)
347             recbuf = (recbuf << 1) + r
348         self.picROMclock(r)
349         #time.sleep(0.1)
350         return recbuf
351         
352     #This seems more reliable when slowed.
353     def picROMclock(self, masterout, slow = True):
354         #print "setting masterout to "+str(masterout)
355         self.serialport.setRTS(masterout)
356         self.serialport.setDTR(1)
357         #time.sleep(0.02)
358         self.serialport.setDTR(0)
359         if slow:
360             time.sleep(0.02)
361         return self.serialport.getCTS()
362
363     def picROMfastclock(self, masterout):
364         #print "setting masterout to "+str(masterout)
365         self.serialport.setRTS(masterout)
366         self.serialport.setDTR(1)
367         self.serialport.setDTR(0)
368         time.sleep(0.02)
369         return self.serialport.getCTS()
370
371     def telosBReset(self,invokeBSL=0):
372         # "BSL entry sequence at dedicated JTAG pins"
373         # rst !s0: 0 0 0 0 1 1
374         # tck !s1: 1 0 1 0 0 1
375         #   s0|s1: 1 3 1 3 2 0
376
377         # "BSL entry sequence at shared JTAG pins"
378         # rst !s0: 0 0 0 0 1 1
379         # tck !s1: 0 1 0 1 1 0
380         #   s0|s1: 3 1 3 1 0 2
381
382         if invokeBSL:
383             self.telosI2CWriteCmd(0,1)
384             self.telosI2CWriteCmd(0,3)
385             self.telosI2CWriteCmd(0,1)
386             self.telosI2CWriteCmd(0,3)
387             self.telosI2CWriteCmd(0,2)
388             self.telosI2CWriteCmd(0,0)
389         else:
390             self.telosI2CWriteCmd(0,3)
391             self.telosI2CWriteCmd(0,2)
392
393         # This line was not defined inside the else: block, not sure where it
394         # should be however
395         self.telosI2CWriteCmd(0,0)
396         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
397         self.serialport.flushInput()  #clear buffers
398
399
400     def getbuffer(self,size=0x1c00):
401         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
402         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
403     def writecmd(self, app, verb, count=0, data=[]):
404         """Write a command and some data to the GoodFET."""
405         self.serialport.write(chr(app));
406         self.serialport.write(chr(verb));
407         
408         #if data!=None:
409         #    count=len(data); #Initial count ignored.
410         
411         #print "TX %02x %02x %04x" % (app,verb,count);
412         
413         #little endian 16-bit length
414         self.serialport.write(chr(count&0xFF));
415         self.serialport.write(chr(count>>8));
416
417         if self.verbose:
418             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
419         
420         #print "count=%02x, len(data)=%04x" % (count,len(data));
421         
422         if count!=0:
423             if(isinstance(data,list)):
424                 for i in range(0,count):
425                 #print "Converting %02x at %i" % (data[i],i)
426                     data[i]=chr(data[i]);
427             #print type(data);
428             outstr=''.join(data);
429             self.serialport.write(outstr);
430         if not self.besilent:
431             return self.readcmd()
432         else:
433             return []
434
435     def readcmd(self):
436         """Read a reply from the GoodFET."""
437         while 1:#self.serialport.inWaiting(): # Loop while input data is available
438             try:
439                 #print "Reading...";
440                 self.app=ord(self.serialport.read(1));
441                 #print "APP=%02x" % self.app;
442                 self.verb=ord(self.serialport.read(1));
443                 
444                 #Fixes an obscure bug in the TelosB.
445                 if self.app==0x00:
446                     while self.verb==0x00:
447                         self.verb=ord(self.serialport.read(1));
448                 
449                 #print "VERB=%02x" % self.verb;
450                 self.count=(
451                     ord(self.serialport.read(1))
452                     +(ord(self.serialport.read(1))<<8)
453                     );
454
455                 if self.verbose:
456                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
457             
458                 #Debugging string; print, but wait.
459                 if self.app==0xFF:
460                     if self.verb==0xFF:
461                         print "# DEBUG %s" % self.serialport.read(self.count)
462                     elif self.verb==0xFE:
463                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
464                     elif self.verb==0xFD:
465                         #Do nothing, just wait so there's no timeout.
466                         print "# NOP.";
467                         
468                     sys.stdout.flush();
469                 else:
470                     self.data=self.serialport.read(self.count);
471                     return self.data;
472             except TypeError:
473                 if self.connected:
474                     print "Warning: waiting for serial read timed out (most likely).";
475                     #print "This shouldn't happen after syncing.  Exiting for safety.";                    
476                     #sys.exit(-1)
477                 return self.data;
478     #Glitching stuff.
479     def glitchApp(self,app):
480         """Glitch into a device by its application."""
481         self.data=[app&0xff];
482         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
483         #return ord(self.data[0]);
484     def glitchVerb(self,app,verb,data):
485         """Glitch during a transaction."""
486         if data==None: data=[];
487         self.data=[app&0xff, verb&0xFF]+data;
488         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
489         #return ord(self.data[0]);
490     def glitchstart(self):
491         """Glitch into the AVR application."""
492         self.glitchVerb(self.APP,0x20,None);
493     def glitchstarttime(self):
494         """Measure the timer of the START verb."""
495         return self.glitchTime(self.APP,0x20,None);
496     def glitchTime(self,app,verb,data):
497         """Time the execution of a verb."""
498         if data==None: data=[];
499         self.data=[app&0xff, verb&0xFF]+data;
500         print "Timing app %02x verb %02x." % (app,verb);
501         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
502         time=ord(self.data[0])+(ord(self.data[1])<<8);
503         print "Timed to be %i." % time;
504         return time;
505     def glitchVoltages(self,low=0x0880, high=0x0fff):
506         """Set glitching voltages. (0x0fff is max.)"""
507         self.data=[low&0xff, (low>>8)&0xff,
508                    high&0xff, (high>>8)&0xff];
509         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
510         #return ord(self.data[0]);
511     def glitchRate(self,count=0x0800):
512         """Set glitching count period."""
513         self.data=[count&0xff, (count>>8)&0xff];
514         self.writecmd(self.GLITCHAPP,0x91,2,
515                       self.data);
516         #return ord(self.data[0]);
517     
518     
519     #Monitor stuff
520     def silent(self,s=0):
521         """Transmissions halted when 1."""
522         self.besilent=s;
523         print "besilent is %i" % self.besilent;
524         self.writecmd(0,0xB0,1,[s]);
525     connected=0;
526     def mon_connected(self):
527         """Announce to the monitor that the connection is good."""
528         self.connected=1;
529         self.writecmd(0,0xB1,0,[]);
530     def out(self,byte):
531         """Write a byte to P5OUT."""
532         self.writecmd(0,0xA1,1,[byte]);
533     def dir(self,byte):
534         """Write a byte to P5DIR."""
535         self.writecmd(0,0xA0,1,[byte]);
536     def call(self,adr):
537         """Call to an address."""
538         self.writecmd(0,0x30,2,
539                       [adr&0xFF,(adr>>8)&0xFF]);
540     def execute(self,code):
541         """Execute supplied code."""
542         self.writecmd(0,0x31,2,#len(code),
543                       code);
544     def MONpeek8(self,address):
545         """Read a byte of memory from the monitor."""
546         self.data=[address&0xff,address>>8];
547         self.writecmd(0,0x02,2,self.data);
548         #self.readcmd();
549         return ord(self.data[0]);
550     def MONpeek16(self,address):
551         """Read a word of memory from the monitor."""
552         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
553     def peek(self,address):
554         """Read a word of memory from the monitor."""
555         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
556     def eeprompeek(self,address):
557         """Read a word of memory from the monitor."""
558         print "EEPROM peeking not supported for the monitor.";
559         #return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
560     def peekbysym(self,name):
561         """Read a value by its symbol name."""
562         #TODO include memory in symbol.
563         reg=self.symbols.get(name);
564         return self.peek8(reg,"data");
565     def pokebysym(self,name,val):
566         """Write a value by its symbol name."""
567         #TODO include memory in symbol.
568         reg=self.symbols.get(name);
569         return self.pokebyte(reg,val);
570     def pokebyte(self,address,value,memory="vn"):
571         """Set a byte of memory by the monitor."""
572         self.data=[address&0xff,address>>8,value];
573         self.writecmd(0,0x03,3,self.data);
574         return ord(self.data[0]);
575     def poke16(self,address,value):
576         """Set a word of memory by the monitor."""
577         self.pokebyte(address,value&0xFF);
578         self.pokebyte(address,(value>>8)&0xFF);
579         return value;
580     def setsecret(self,value):
581         """Set a secret word for later retreival.  Used by glitcher."""
582         #self.eeprompoke(0,value);
583         #self.eeprompoke(1,value);
584         print "Secret setting is not yet suppored for this target.";
585         print "Aborting.";
586         
587     def getsecret(self):
588         """Get a secret word.  Used by glitcher."""
589         #self.eeprompeek(0);
590         print "Secret getting is not yet suppored for this target.";
591         print "Aborting.";
592         sys.exit();
593     
594     def dumpmem(self,begin,end):
595         i=begin;
596         while i<end:
597             print "%04x %04x" % (i, self.MONpeek16(i));
598             i+=2;
599     def monitor_ram_pattern(self):
600         """Overwrite all of RAM with 0xBEEF."""
601         self.writecmd(0,0x90,0,self.data);
602         return;
603     def monitor_ram_depth(self):
604         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
605         self.writecmd(0,0x91,0,self.data);
606         return ord(self.data[0])+(ord(self.data[1])<<8);
607     
608     #Baud rates.
609     baudrates=[115200, 
610                9600,
611                19200,
612                38400,
613                57600,
614                115200];
615     def setBaud(self,baud):
616         """Change the baud rate.  TODO fix this."""
617         rates=self.baudrates;
618         self.data=[baud];
619         print "Changing FET baud."
620         self.serialport.write(chr(0x00));
621         self.serialport.write(chr(0x80));
622         self.serialport.write(chr(1));
623         self.serialport.write(chr(baud));
624         
625         print "Changed host baud."
626         self.serialport.setBaudrate(rates[baud]);
627         time.sleep(1);
628         self.serialport.flushInput()
629         self.serialport.flushOutput()
630         
631         print "Baud is now %i." % rates[baud];
632         return;
633     def readbyte(self):
634         return ord(self.serialport.read(1));
635     def findbaud(self):
636         for r in self.baudrates:
637             print "\nTrying %i" % r;
638             self.serialport.setBaudrate(r);
639             #time.sleep(1);
640             self.serialport.flushInput()
641             self.serialport.flushOutput()
642             
643             for i in range(1,10):
644                 self.readbyte();
645             
646             print "Read %02x %02x %02x %02x" % (
647                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
648     def monitortest(self):
649         """Self-test several functions through the monitor."""
650         print "Performing monitor self-test.";
651         self.monitorclocking();
652         for f in range(0,3000):
653             a=self.MONpeek16(0x0c00);
654             b=self.MONpeek16(0x0c02);
655             if a!=0x0c04 and a!=0x0c06:
656                 print "ERROR Fetched %04x, %04x" % (a,b);
657             self.pokebyte(0x0021,0); #Drop LED
658             if self.MONpeek8(0x0021)!=0:
659                 print "ERROR, P1OUT not cleared.";
660             self.pokebyte(0x0021,1); #Light LED
661             if not self.monitorecho():
662                 print "Echo test failed.";
663         print "Self-test complete.";
664         self.monitorclocking();
665     def monitorecho(self):
666         data="The quick brown fox jumped over the lazy dog.";
667         self.writecmd(self.MONITORAPP,0x81,len(data),data);
668         if self.data!=data:
669             print "Comm error recognized by monitorecho(), got:\n%s" % self.data;
670             return 0;
671         return 1;
672
673     def monitor_info(self):
674         print "GoodFET with %s MCU" % self.infostring();
675         print "Clocked at %s" % self.monitorclocking();
676         return 1;
677
678     def testleds(self):
679         print "Flashing LEDs"
680         self.writecmd(self.MONITORAPP,0xD0,0,"")
681         try:
682             print "Flashed %d LED." % ord(self.data)
683         except:
684             print "Unable to process response:", self.data
685         return 1
686
687     def monitor_list_apps(self, full=False): 
688         self.monitor_info()
689         old_value = self.besilent
690         self.besilent = True    # turn off automatic call to readcmd
691         self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
692         self.besilent = old_value
693         
694         # read the build date string 
695         self.readcmd()
696         print "Build Date: %s" % self.data
697         print "Firmware apps:"
698         while True:
699             self.readcmd()
700             if self.count == 0:
701                 break
702             print self.data
703         return 1;
704
705     def monitorclocking(self):
706         """Return the 16-bit clocking value."""
707         return "0x%04x" % self.monitorgetclock();
708     
709     def monitorsetclock(self,clock):
710         """Set the clocking value."""
711         self.MONpoke16(0x56, clock);
712     def monitorgetclock(self):
713         """Get the clocking value."""
714         if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
715             return 0xDEAD;
716         #Check for MSP430 before peeking this.
717         return self.MONpeek16(0x56);
718     # The following functions ought to be implemented in
719     # every client.
720     
721     def infostring(self):
722         if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
723             return "Arduino";
724         else:
725             a=self.MONpeek8(0xff0);
726             b=self.MONpeek8(0xff1);
727             return "%02x%02x" % (a,b);
728     def lock(self):
729         print "Locking Unsupported.";
730     def erase(self):
731         print "Erasure Unsupported.";
732     def setup(self):
733         return;
734     def start(self):
735         return;
736     def test(self):
737         print "Unimplemented.";
738         return;
739     def status(self):
740         print "Unimplemented.";
741         return;
742     def halt(self):
743         print "Unimplemented.";
744         return;
745     def resume(self):
746         print "Unimplemented.";
747         return;
748     def getpc(self):
749         print "Unimplemented.";
750         return 0xdead;
751     def flash(self,file):
752         """Flash an intel hex file to code memory."""
753         print "Flash not implemented.";
754     def dump(self,file,start=0,stop=0xffff):
755         """Dump an intel hex file from code memory."""
756         print "Dump not implemented.";
757     def peek32(self,address, memory="vn"):
758         """Peek 32 bits."""
759         return (self.peek16(address,memory)+
760                 (self.peek16(address+2,memory)<<16));
761     def peek16(self,address, memory="vn"):
762         """Peek 16 bits of memory."""
763         return (self.peek8(address,memory)+
764                 (self.peek8(address+1,memory)<<8));
765     def peek8(self,address, memory="vn"):
766         """Peek a byte of memory."""
767         return self.MONpeek8(address); #monitor
768     def peekblock(self,address,length,memory="vn"):
769         """Return a block of data."""
770         data=range(0,length);
771         for foo in range(0,length):
772             data[foo]=self.peek8(address+foo,memory);
773         return data;
774     def pokeblock(self,address,bytes,memory="vn"):
775         """Poke a block of a data into memory at an address."""
776         for foo in bytes:
777             self.pokebyte(address,foo,memory);
778             address=address+1;
779         return;
780     def loadsymbols(self):
781         """Load symbols from a file."""
782         return;