goodfet.msp430 selftest is working!
[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, serial, 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;
15     if(name=="GoodFET" or name=="monitor"): return GoodFET.GoodFET();
16     elif name=="cc" or name=="chipcon": return GoodFETCC.GoodFETCC();
17     elif name=="avr": return GoodFETAVR.GoodFETAVR();
18     elif name=="spi": return GoodFETSPI.GoodFETSPI();
19     elif name=="msp430": return GoodFETMSP430.GoodFETMSP430();
20     elif name=="nrf": return GoodFETNRF.GoodFETNRF();
21     
22     print "Unsupported target: %s" % name;
23     sys.exit(0);
24
25 class SymbolTable:
26     """GoodFET Symbol Table"""
27     db=sqlite3.connect(":memory:");
28     
29     def __init__(self, *args, **kargs):
30         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
31     def get(self,name):
32         self.db.commit();
33         c=self.db.cursor();
34         try:
35             c.execute("select adr,memory from symbols where name=?",(name,));
36             for row in c:
37                 #print "Found it.";
38                 sys.stdout.flush();
39                 return row[0];
40             #print "No dice.";
41         except:# sqlite3.OperationalError:
42             #print "SQL error.";
43             return eval(name);
44         return eval(name);
45     def define(self,adr,name,comment="",memory="vn",size=16):
46         self.db.execute("insert into symbols(adr,name,memory,size,comment)"
47                         "values(?,?,?,?,?);", (
48                 adr,name,memory,size,comment));
49         #print "Set %s=%s." % (name,adr);
50
51 class GoodFET:
52     """GoodFET Client Library"""
53
54     besilent=0;
55     app=0;
56     verb=0;
57     count=0;
58     data="";
59     verbose=False
60     
61     GLITCHAPP=0x71;
62     MONITORAPP=0x00;
63     symbols=SymbolTable();
64     
65     def __init__(self, *args, **kargs):
66         self.data=[0];
67     def getConsole(self):
68         from GoodFETConsole import GoodFETConsole;
69         return GoodFETConsole(self);
70     def name2adr(self,name):
71         return self.symbols.get(name);
72     def timeout(self):
73         print "timeout\n";
74     def serInit(self, port=None, timeout=2):
75         """Open the serial port"""
76         # Make timeout None to wait forever, 0 for non-blocking mode.
77         
78         if port is None and os.environ.get("GOODFET")!=None:
79             glob_list = glob.glob(os.environ.get("GOODFET"));
80             if len(glob_list) > 0:
81                 port = glob_list[0];
82             else:
83                 port = os.environ.get("GOODFET");
84         if port is None:
85             glob_list = glob.glob("/dev/tty.usbserial*");
86             if len(glob_list) > 0:
87                 port = glob_list[0];
88         if port is None:
89             glob_list = glob.glob("/dev/ttyUSB*");
90             if len(glob_list) > 0:
91                 port = glob_list[0];
92         if os.name=='nt':
93             from scanwin32 import winScan;
94             scan=winScan();
95             for order,comport,desc,hwid in sorted(scan.comports()):
96                 if hwid.index('FTDI')==0:
97                     port=comport;
98                     #print "Using FTDI port %s" % port
99         
100         
101         self.serialport = serial.Serial(
102             port,
103             #9600,
104             115200,
105             parity = serial.PARITY_NONE,
106             timeout=timeout
107             )
108         
109         self.verb=0;
110         attempts=0;
111         connected=0;
112         while connected==0:
113             while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
114                 #print "Resyncing.";
115                 self.serialport.flushInput()
116                 self.serialport.flushOutput()
117                 #Explicitly set RTS and DTR to halt board.
118                 self.serialport.setRTS(1);
119                 self.serialport.setDTR(1);
120                 #Drop DTR, which is !RST, low to begin the app.
121                 self.serialport.setDTR(0);
122                 self.serialport.flushInput()
123                 self.serialport.flushOutput()
124                 #time.sleep(60);
125                 attempts=attempts+1;
126                 self.readcmd(); #Read the first command.
127             #Here we have a connection, but maybe not a good one.
128             connected=1;
129             olds=self.infostring();
130             clocking=self.monitorclocking();
131             for foo in range(1,30):
132                 if not self.monitorecho():
133                     if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
134                                                   clocking);
135                     connected=0;
136                     break;
137         if self.verbose: print "Connected after %02i attempts." % attempts;
138         self.mon_connected();
139         
140     def getbuffer(self,size=0x1c00):
141         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
142         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
143     def writecmd(self, app, verb, count=0, data=[]):
144         """Write a command and some data to the GoodFET."""
145         self.serialport.write(chr(app));
146         self.serialport.write(chr(verb));
147         
148         #if data!=None:
149         #    count=len(data); #Initial count ignored.
150         
151         #print "TX %02x %02x %04x" % (app,verb,count);
152         
153         #little endian 16-bit length
154         self.serialport.write(chr(count&0xFF));
155         self.serialport.write(chr(count>>8));
156
157         if self.verbose:
158             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
159         
160         #print "count=%02x, len(data)=%04x" % (count,len(data));
161         
162         if count!=0:
163             if(isinstance(data,list)):
164                 for i in range(0,count):
165                 #print "Converting %02x at %i" % (data[i],i)
166                     data[i]=chr(data[i]);
167             #print type(data);
168             outstr=''.join(data);
169             self.serialport.write(outstr);
170         if not self.besilent:
171             return self.readcmd()
172         else:
173             return []
174
175     def readcmd(self):
176         """Read a reply from the GoodFET."""
177         while 1:#self.serialport.inWaiting(): # Loop while input data is available
178             try:
179                 #print "Reading...";
180                 self.app=ord(self.serialport.read(1));
181                 #print "APP=%2x" % self.app;
182                 self.verb=ord(self.serialport.read(1));
183                 #print "VERB=%02x" % self.verb;
184                 self.count=(
185                     ord(self.serialport.read(1))
186                     +(ord(self.serialport.read(1))<<8)
187                     );
188
189                 if self.verbose:
190                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
191             
192                 #Debugging string; print, but wait.
193                 if self.app==0xFF:
194                     if self.verb==0xFF:
195                         print "# DEBUG %s" % self.serialport.read(self.count)
196                     elif self.verb==0xFE:
197                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
198                     elif self.verb==0xFD:
199                         #Do nothing, just wait so there's no timeout.
200                         print "# NOP.";
201                         
202                     sys.stdout.flush();
203                 else:
204                     self.data=self.serialport.read(self.count);
205                     return self.data;
206             except TypeError:
207                 if self.connected:
208                     print "Error: waiting for serial read timed out (most likely).";
209                     print "This shouldn't happen after syncing.  Exiting for safety.";
210                     sys.exit(-1)
211                 return self.data;
212     #Glitching stuff.
213     def glitchApp(self,app):
214         """Glitch into a device by its application."""
215         self.data=[app&0xff];
216         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
217         #return ord(self.data[0]);
218     def glitchVerb(self,app,verb,data):
219         """Glitch during a transaction."""
220         if data==None: data=[];
221         self.data=[app&0xff, verb&0xFF]+data;
222         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
223         #return ord(self.data[0]);
224     def glitchstart(self):
225         """Glitch into the AVR application."""
226         self.glitchVerb(self.APP,0x20,None);
227     def glitchstarttime(self):
228         """Measure the timer of the START verb."""
229         return self.glitchTime(self.APP,0x20,None);
230     def glitchTime(self,app,verb,data):
231         """Time the execution of a verb."""
232         if data==None: data=[];
233         self.data=[app&0xff, verb&0xFF]+data;
234         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
235         return ord(self.data[0])+(ord(self.data[1])<<8);
236     def glitchVoltages(self,low=0x0880, high=0x0fff):
237         """Set glitching voltages. (0x0fff is max.)"""
238         self.data=[low&0xff, (low>>8)&0xff,
239                    high&0xff, (high>>8)&0xff];
240         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
241         #return ord(self.data[0]);
242     def glitchRate(self,count=0x0800):
243         """Set glitching count period."""
244         self.data=[count&0xff, (count>>8)&0xff];
245         self.writecmd(self.GLITCHAPP,0x91,2,
246                       self.data);
247         #return ord(self.data[0]);
248     
249     
250     #Monitor stuff
251     def silent(self,s=0):
252         """Transmissions halted when 1."""
253         self.besilent=s;
254         print "besilent is %i" % self.besilent;
255         self.writecmd(0,0xB0,1,[s]);
256     connected=0;
257     def mon_connected(self):
258         """Announce to the monitor that the connection is good."""
259         self.connected=1;
260         self.writecmd(0,0xB1,0,[]);
261     def out(self,byte):
262         """Write a byte to P5OUT."""
263         self.writecmd(0,0xA1,1,[byte]);
264     def dir(self,byte):
265         """Write a byte to P5DIR."""
266         self.writecmd(0,0xA0,1,[byte]);
267     def call(self,adr):
268         """Call to an address."""
269         self.writecmd(0,0x30,2,
270                       [adr&0xFF,(adr>>8)&0xFF]);
271     def execute(self,code):
272         """Execute supplied code."""
273         self.writecmd(0,0x31,2,#len(code),
274                       code);
275     def peekbyte(self,address):
276         """Read a byte of memory from the monitor."""
277         self.data=[address&0xff,address>>8];
278         self.writecmd(0,0x02,2,self.data);
279         #self.readcmd();
280         return ord(self.data[0]);
281     def peekword(self,address):
282         """Read a word of memory from the monitor."""
283         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
284     def peek(self,address):
285         """Read a word of memory from the monitor."""
286         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
287     def pokebyte(self,address,value):
288         """Set a byte of memory by the monitor."""
289         self.data=[address&0xff,address>>8,value];
290         self.writecmd(0,0x03,3,self.data);
291         return ord(self.data[0]);
292     def dumpmem(self,begin,end):
293         i=begin;
294         while i<end:
295             print "%04x %04x" % (i, self.peekword(i));
296             i+=2;
297     def monitor_ram_pattern(self):
298         """Overwrite all of RAM with 0xBEEF."""
299         self.writecmd(0,0x90,0,self.data);
300         return;
301     def monitor_ram_depth(self):
302         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
303         self.writecmd(0,0x91,0,self.data);
304         return ord(self.data[0])+(ord(self.data[1])<<8);
305     
306     #Baud rates.
307     baudrates=[115200, 
308                9600,
309                19200,
310                38400,
311                57600,
312                115200];
313     def setBaud(self,baud):
314         """Change the baud rate.  TODO fix this."""
315         rates=self.baudrates;
316         self.data=[baud];
317         print "Changing FET baud."
318         self.serialport.write(chr(0x00));
319         self.serialport.write(chr(0x80));
320         self.serialport.write(chr(1));
321         self.serialport.write(chr(baud));
322         
323         print "Changed host baud."
324         self.serialport.setBaudrate(rates[baud]);
325         time.sleep(1);
326         self.serialport.flushInput()
327         self.serialport.flushOutput()
328         
329         print "Baud is now %i." % rates[baud];
330         return;
331     def readbyte(self):
332         return ord(self.serialport.read(1));
333     def findbaud(self):
334         for r in self.baudrates:
335             print "\nTrying %i" % r;
336             self.serialport.setBaudrate(r);
337             #time.sleep(1);
338             self.serialport.flushInput()
339             self.serialport.flushOutput()
340             
341             for i in range(1,10):
342                 self.readbyte();
343             
344             print "Read %02x %02x %02x %02x" % (
345                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
346     def monitortest(self):
347         """Self-test several functions through the monitor."""
348         print "Performing monitor self-test.";
349         self.monitorclocking();
350         for f in range(0,3000):
351             a=self.peekword(0x0c00);
352             b=self.peekword(0x0c02);
353             if a!=0x0c04 and a!=0x0c06:
354                 print "ERROR Fetched %04x, %04x" % (a,b);
355             self.pokebyte(0x0021,0); #Drop LED
356             if self.peekbyte(0x0021)!=0:
357                 print "ERROR, P1OUT not cleared.";
358             self.pokebyte(0x0021,1); #Light LED
359             if not self.monitorecho():
360                 print "Echo test failed.";
361         print "Self-test complete.";
362         self.monitorclocking();
363     def monitorecho(self):
364         data="The quick brown fox jumped over the lazy dog.";
365         self.writecmd(self.MONITORAPP,0x81,len(data),data);
366         if self.data!=data:
367             if self.verbose: print "Comm error recognized by monitorecho().";
368             return 0;
369         return 1;
370     def monitorclocking(self):
371         DCOCTL=self.peekbyte(0x0056);
372         BCSCTL1=self.peekbyte(0x0057);
373         return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
374
375     # The following functions ought to be implemented in
376     # every client.
377
378     def infostring(self):
379         a=self.peekbyte(0xff0);
380         b=self.peekbyte(0xff1);
381         return "%02x%02x" % (a,b);
382     def lock(self):
383         print "Locking Unsupported.";
384     def erase(self):
385         print "Erasure Unsupported.";
386     def setup(self):
387         return;
388     def start(self):
389         return;
390     def test(self):
391         print "Unimplemented.";
392         return;
393     def status(self):
394         print "Unimplemented.";
395         return;
396     def halt(self):
397         print "Unimplemented.";
398         return;
399     def resume(self):
400         print "Unimplemented.";
401         return;
402     def getpc(self):
403         print "Unimplemented.";
404         return 0xdead;
405     def flash(self,file):
406         """Flash an intel hex file to code memory."""
407         print "Flash not implemented.";
408     def dump(self,file,start=0,stop=0xffff):
409         """Dump an intel hex file from code memory."""
410         print "Dump not implemented.";
411     def peek32(self,address, memory="vn"):
412         return (self.peek16(address,memory)+
413                 (self.peek16(address+2,memory)<<16));
414     def peek16(self,address, memory="vn"):
415         return (self.peek8(address,memory)+
416                 (self.peek8(address+1,memory)<<8));
417     def peek8(self,address, memory="vn"):
418         return self.peekbyte(address); #monitor
419     def peekword(self,address, memory="vn"):
420         return self.peek(address); #monitor
421     
422     def loadsymbols(self):
423         return;