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