2 # GoodFET Client Library
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
6 # This code is being rewritten and refactored. You've been warned!
8 import sys, time, string, cStringIO, struct, glob, serial, os;
11 fmt = ("B", "<H", None, "<L")
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();
21 print "Unsupported target: %s" % name;
25 """GoodFET Symbol Table"""
26 db=sqlite3.connect(":memory:");
28 def __init__(self, *args, **kargs):
29 self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
34 c.execute("select adr,memory from symbols where name=?",(name,));
40 except:# sqlite3.OperationalError:
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);
51 """GoodFET Client Library"""
62 symbols=SymbolTable();
64 def __init__(self, *args, **kargs):
67 from GoodFETConsole import GoodFETConsole;
68 return GoodFETConsole(self);
69 def name2adr(self,name):
70 return self.symbols.get(name);
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.
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:
82 port = os.environ.get("GOODFET");
84 glob_list = glob.glob("/dev/tty.usbserial*");
85 if len(glob_list) > 0:
88 glob_list = glob.glob("/dev/ttyUSB*");
89 if len(glob_list) > 0:
93 self.serialport = serial.Serial(
97 parity = serial.PARITY_NONE,
105 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
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()
118 self.readcmd(); #Read the first command.
119 #Here we have a connection, but maybe not a good one.
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,
129 if self.verbose: print "Connected after %02i attempts." % attempts;
130 self.mon_connected();
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));
141 # count=len(data); #Initial count ignored.
143 #print "TX %02x %02x %04x" % (app,verb,count);
145 #little endian 16-bit length
146 self.serialport.write(chr(count&0xFF));
147 self.serialport.write(chr(count>>8));
150 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
152 #print "count=%02x, len(data)=%04x" % (count,len(data));
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]);
160 outstr=''.join(data);
161 self.serialport.write(outstr);
162 if not self.besilent:
163 return self.readcmd()
168 """Read a reply from the GoodFET."""
169 while 1:#self.serialport.inWaiting(): # Loop while input data is available
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;
177 ord(self.serialport.read(1))
178 +(ord(self.serialport.read(1))<<8)
182 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
184 #Debugging string; print, but wait.
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]
192 self.data=self.serialport.read(self.count);
196 print "Error: waiting for serial read timed out (most likely).";
197 print "This shouldn't happen after syncing. Exiting for safety.";
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,
235 #return ord(self.data[0]);
239 def silent(self,s=0):
240 """Transmissions halted when 1."""
242 print "besilent is %i" % self.besilent;
243 self.writecmd(0,0xB0,1,[s]);
245 def mon_connected(self):
246 """Announce to the monitor that the connection is good."""
248 self.writecmd(0,0xB1,0,[]);
250 """Write a byte to P5OUT."""
251 self.writecmd(0,0xA1,1,[byte]);
253 """Write a byte to P5DIR."""
254 self.writecmd(0,0xA0,1,[byte]);
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),
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);
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):
280 print "%04x %04x" % (i, self.peekword(i));
282 def monitor_ram_pattern(self):
283 """Overwrite all of RAM with 0xBEEF."""
284 self.writecmd(0,0x90,0,self.data);
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);
298 def setBaud(self,baud):
299 """Change the baud rate. TODO fix this."""
300 rates=self.baudrates;
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));
308 print "Changed host baud."
309 self.serialport.setBaudrate(rates[baud]);
311 self.serialport.flushInput()
312 self.serialport.flushOutput()
314 print "Baud is now %i." % rates[baud];
317 return ord(self.serialport.read(1));
319 for r in self.baudrates:
320 print "\nTrying %i" % r;
321 self.serialport.setBaudrate(r);
323 self.serialport.flushInput()
324 self.serialport.flushOutput()
326 for i in range(1,10):
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);
352 if self.verbose: print "Comm error recognized by monitorecho().";
355 def monitorclocking(self):
356 DCOCTL=self.peekbyte(0x0056);
357 BCSCTL1=self.peekbyte(0x0057);
358 return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
360 # The following functions ought to be implemented in
363 def infostring(self):
364 a=self.peekbyte(0xff0);
365 b=self.peekbyte(0xff1);
366 return "%02x%02x" % (a,b);
368 print "Locking Unsupported.";
370 print "Erasure Unsupported.";
376 print "Unimplemented.";
379 print "Unimplemented.";
382 print "Unimplemented.";
385 print "Unimplemented.";
388 print "Unimplemented.";
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.";
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):