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