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