db192f961be5d8da226981c3303090d10b77f2e3
[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     symbols=SymbolTable();
62     
63     def __init__(self, *args, **kargs):
64         self.data=[0];
65     def getConsole(self):
66         from GoodFETConsole import GoodFETConsole;
67         return GoodFETConsole(self);
68     def name2adr(self,name):
69         return self.symbols.get(name);
70     def timeout(self):
71         print "timeout\n";
72     def serInit(self, port=None, timeout=1):
73         """Open the serial port"""
74         # Make timeout None to wait forever, 0 for non-blocking mode.
75         
76         if port is None and os.environ.get("GOODFET")!=None:
77             glob_list = glob.glob(os.environ.get("GOODFET"));
78             if len(glob_list) > 0:
79                 port = glob_list[0];
80         if port is None:
81             glob_list = glob.glob("/dev/tty.usbserial*");
82             if len(glob_list) > 0:
83                 port = glob_list[0];
84         if port is None:
85             glob_list = glob.glob("/dev/ttyUSB*");
86             if len(glob_list) > 0:
87                 port = glob_list[0];
88         
89         self.serialport = serial.Serial(
90             port,
91             #9600,
92             115200,
93             parity = serial.PARITY_NONE,
94             timeout=timeout
95             )
96         
97         self.verb=0;
98         while self.verb!=0x7F:
99             #Explicitly set RTS and DTR to halt board.
100             self.serialport.setRTS(1);
101             self.serialport.setDTR(1);
102             #Drop DTR, which is !RST, low to begin the app.
103             self.serialport.setDTR(0);
104             self.serialport.flushInput()
105             self.serialport.flushOutput()
106         
107             #Read and handle the initial command.
108             #time.sleep(1);
109             self.readcmd(); #Read the first command.
110             #if(self.verb!=0x7F):
111             #    print "Verb %02x is wrong.  Incorrect firmware or bad Info guess?" % self.verb;
112             #    print "http://goodfet.sf.net/faq/";
113         print "Connected."
114     def getbuffer(self,size=0x1c00):
115         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
116         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
117     def writecmd(self, app, verb, count=0, data=[]):
118         """Write a command and some data to the GoodFET."""
119         self.serialport.write(chr(app));
120         self.serialport.write(chr(verb));
121         
122         #if data!=None:
123         #    count=len(data); #Initial count ignored.
124         
125         #print "TX %02x %02x %04x" % (app,verb,count);
126         
127         #little endian 16-bit length
128         self.serialport.write(chr(count&0xFF));
129         self.serialport.write(chr(count>>8));
130
131         if self.verbose:
132             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
133         
134         #print "count=%02x, len(data)=%04x" % (count,len(data));
135         
136         if count!=0:
137             if(isinstance(data,list)):
138                 for i in range(0,count):
139                 #print "Converting %02x at %i" % (data[i],i)
140                     data[i]=chr(data[i]);
141             #print type(data);
142             outstr=''.join(data);
143             self.serialport.write(outstr);
144         if not self.besilent:
145             return self.readcmd()
146         else:
147             return []
148
149     def readcmd(self):
150         """Read a reply from the GoodFET."""
151         while 1:#self.serialport.inWaiting(): # Loop while input data is available
152             try:
153                 #print "Reading...";
154                 self.app=ord(self.serialport.read(1));
155                 #print "APP=%2x" % self.app;
156                 self.verb=ord(self.serialport.read(1));
157                 #print "VERB=%02x" % self.verb;
158                 self.count=(
159                     ord(self.serialport.read(1))
160                     +(ord(self.serialport.read(1))<<8)
161                     );
162
163                 if self.verbose:
164                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
165             
166                 #Debugging string; print, but wait.
167                 if self.app==0xFF:
168                     if self.verb==0xFF:
169                         print "# DEBUG %s" % self.serialport.read(self.count)
170                     elif self.verb==0xFE:
171                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
172                     sys.stdout.flush();
173                 else:
174                     self.data=self.serialport.read(self.count);
175                     return self.data;
176             except TypeError:
177                 print "Error: waiting for serial read timed out (most likely)."
178                 sys.exit(-1)
179
180     #Glitching stuff.
181     def glitchApp(self,app):
182         """Glitch into a device by its application."""
183         self.data=[app&0xff];
184         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
185         #return ord(self.data[0]);
186     def glitchVerb(self,app,verb,data):
187         """Glitch during a transaction."""
188         if data==None: data=[];
189         self.data=[app&0xff, verb&0xFF]+data;
190         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
191         #return ord(self.data[0]);
192     def glitchstart(self):
193         """Glitch into the AVR application."""
194         self.glitchVerb(self.APP,0x20,None);
195     def glitchstarttime(self):
196         """Measure the timer of the START verb."""
197         return self.glitchTime(self.APP,0x20,None);
198     def glitchTime(self,app,verb,data):
199         """Time the execution of a verb."""
200         if data==None: data=[];
201         self.data=[app&0xff, verb&0xFF]+data;
202         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
203         return ord(self.data[0])+(ord(self.data[1])<<8);
204     def glitchVoltages(self,low=0x0880, high=0x0fff):
205         """Set glitching voltages. (0x0fff is max.)"""
206         self.data=[low&0xff, (low>>8)&0xff,
207                    high&0xff, (high>>8)&0xff];
208         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
209         #return ord(self.data[0]);
210     def glitchRate(self,count=0x0800):
211         """Set glitching count period."""
212         self.data=[count&0xff, (count>>8)&0xff];
213         self.writecmd(self.GLITCHAPP,0x91,2,
214                       self.data);
215         #return ord(self.data[0]);
216     
217     
218     #Monitor stuff
219     def silent(self,s=0):
220         """Transmissions halted when 1."""
221         self.besilent=s;
222         print "besilent is %i" % self.besilent;
223         self.writecmd(0,0xB0,1,[s]);
224         
225     def out(self,byte):
226         """Write a byte to P5OUT."""
227         self.writecmd(0,0xA1,1,[byte]);
228     def dir(self,byte):
229         """Write a byte to P5DIR."""
230         self.writecmd(0,0xA0,1,[byte]);
231     def call(self,adr):
232         """Call to an address."""
233         self.writecmd(0,0x30,2,
234                       [adr&0xFF,(adr>>8)&0xFF]);
235     def execute(self,code):
236         """Execute supplied code."""
237         self.writecmd(0,0x31,2,#len(code),
238                       code);
239     def peekbyte(self,address):
240         """Read a byte of memory from the monitor."""
241         self.data=[address&0xff,address>>8];
242         self.writecmd(0,0x02,2,self.data);
243         #self.readcmd();
244         return ord(self.data[0]);
245     def peekword(self,address):
246         """Read a word of memory from the monitor."""
247         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
248     def pokebyte(self,address,value):
249         """Set a byte of memory by the monitor."""
250         self.data=[address&0xff,address>>8,value];
251         self.writecmd(0,0x03,3,self.data);
252         return ord(self.data[0]);
253     def dumpmem(self,begin,end):
254         i=begin;
255         while i<end:
256             print "%04x %04x" % (i, self.peekword(i));
257             i+=2;
258     def monitor_ram_pattern(self):
259         """Overwrite all of RAM with 0xBEEF."""
260         self.writecmd(0,0x90,0,self.data);
261         return;
262     def monitor_ram_depth(self):
263         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
264         self.writecmd(0,0x91,0,self.data);
265         return ord(self.data[0])+(ord(self.data[1])<<8);
266     
267     #Baud rates.
268     baudrates=[115200, 
269                9600,
270                19200,
271                38400,
272                57600,
273                115200];
274     def setBaud(self,baud):
275         """Change the baud rate.  TODO fix this."""
276         rates=self.baudrates;
277         self.data=[baud];
278         print "Changing FET baud."
279         self.serialport.write(chr(0x00));
280         self.serialport.write(chr(0x80));
281         self.serialport.write(chr(1));
282         self.serialport.write(chr(baud));
283         
284         print "Changed host baud."
285         self.serialport.setBaudrate(rates[baud]);
286         time.sleep(1);
287         self.serialport.flushInput()
288         self.serialport.flushOutput()
289         
290         print "Baud is now %i." % rates[baud];
291         return;
292     def readbyte(self):
293         return ord(self.serialport.read(1));
294     def findbaud(self):
295         for r in self.baudrates:
296             print "\nTrying %i" % r;
297             self.serialport.setBaudrate(r);
298             #time.sleep(1);
299             self.serialport.flushInput()
300             self.serialport.flushOutput()
301             
302             for i in range(1,10):
303                 self.readbyte();
304             
305             print "Read %02x %02x %02x %02x" % (
306                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
307     def monitortest(self):
308         """Self-test several functions through the monitor."""
309         print "Performing monitor self-test.";
310         
311         if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
312             print "ERROR Fetched wrong value from 0x0c04.";
313         self.pokebyte(0x0021,0); #Drop LED
314         if self.peekbyte(0x0021)!=0:
315             print "ERROR, P1OUT not cleared.";
316         self.pokebyte(0x0021,1); #Light LED
317         
318         print "Self-test complete.";
319     
320     
321     # The following functions ought to be implemented in
322     # every client.
323
324     def infostring(self):
325         a=self.peekbyte(0xff0);
326         b=self.peekbyte(0xff1);
327         return "%02x%02x" % (a,b);
328     def lock(self):
329         print "Locking Unsupported.";
330     def erase(self):
331         print "Erasure Unsupported.";
332     def setup(self):
333         return;
334     def start(self):
335         return;
336     def test(self):
337         print "Unimplemented.";
338         return;
339     def status(self):
340         print "Unimplemented.";
341         return;
342     def halt(self):
343         print "Unimplemented.";
344         return;
345     def resume(self):
346         print "Unimplemented.";
347         return;
348     def getpc(self):
349         print "Unimplemented.";
350         return 0xdead;
351     def flash(self,file):
352         """Flash an intel hex file to code memory."""
353         print "Flash not implemented.";
354     def dump(self,file,start=0,stop=0xffff):
355         """Dump an intel hex file from code memory."""
356         print "Dump not implemented.";
357
358     def peek32(self,address, memory="vn"):
359         return (self.peek16(address,memory)+
360                 (self.peek16(address+2,memory)<<16));
361     def peek16(self,address, memory="vn"):
362         return (self.peek8(address,memory)+
363                 (self.peek8(address+1,memory)<<8));
364     def peek8(self,address, memory="vn"):
365         return self.peekbyte(address); #monitor
366     def loadsymbols(self):
367         return;