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/":
106 self.serialport.flushInput()
107 self.serialport.flushOutput()
108 #Explicitly set RTS and DTR to halt board.
109 self.serialport.setRTS(1);
110 self.serialport.setDTR(1);
111 #Drop DTR, which is !RST, low to begin the app.
112 self.serialport.setDTR(0);
113 self.serialport.flushInput()
114 self.serialport.flushOutput()
117 self.readcmd(); #Read the first command.
118 #Here we have a connection, but maybe not a good one.
120 olds=self.infostring();
121 self.monitorclocking();
122 for foo in range(1,30):
123 if not self.monitorecho():
124 print "Comm error, resyncing.";
127 if self.verbose: print "Connected after %02i attempts." % attempts;
128 self.mon_connected();
130 def getbuffer(self,size=0x1c00):
131 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
132 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
133 def writecmd(self, app, verb, count=0, data=[]):
134 """Write a command and some data to the GoodFET."""
135 self.serialport.write(chr(app));
136 self.serialport.write(chr(verb));
139 # count=len(data); #Initial count ignored.
141 #print "TX %02x %02x %04x" % (app,verb,count);
143 #little endian 16-bit length
144 self.serialport.write(chr(count&0xFF));
145 self.serialport.write(chr(count>>8));
148 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
150 #print "count=%02x, len(data)=%04x" % (count,len(data));
153 if(isinstance(data,list)):
154 for i in range(0,count):
155 #print "Converting %02x at %i" % (data[i],i)
156 data[i]=chr(data[i]);
158 outstr=''.join(data);
159 self.serialport.write(outstr);
160 if not self.besilent:
161 return self.readcmd()
166 """Read a reply from the GoodFET."""
167 while 1:#self.serialport.inWaiting(): # Loop while input data is available
170 self.app=ord(self.serialport.read(1));
171 #print "APP=%2x" % self.app;
172 self.verb=ord(self.serialport.read(1));
173 #print "VERB=%02x" % self.verb;
175 ord(self.serialport.read(1))
176 +(ord(self.serialport.read(1))<<8)
180 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
182 #Debugging string; print, but wait.
185 print "# DEBUG %s" % self.serialport.read(self.count)
186 elif self.verb==0xFE:
187 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
190 self.data=self.serialport.read(self.count);
194 print "Error: waiting for serial read timed out (most likely).";
195 print "This shouldn't happen after syncing. Exiting for safety.";
199 def glitchApp(self,app):
200 """Glitch into a device by its application."""
201 self.data=[app&0xff];
202 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
203 #return ord(self.data[0]);
204 def glitchVerb(self,app,verb,data):
205 """Glitch during a transaction."""
206 if data==None: data=[];
207 self.data=[app&0xff, verb&0xFF]+data;
208 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
209 #return ord(self.data[0]);
210 def glitchstart(self):
211 """Glitch into the AVR application."""
212 self.glitchVerb(self.APP,0x20,None);
213 def glitchstarttime(self):
214 """Measure the timer of the START verb."""
215 return self.glitchTime(self.APP,0x20,None);
216 def glitchTime(self,app,verb,data):
217 """Time the execution of a verb."""
218 if data==None: data=[];
219 self.data=[app&0xff, verb&0xFF]+data;
220 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
221 return ord(self.data[0])+(ord(self.data[1])<<8);
222 def glitchVoltages(self,low=0x0880, high=0x0fff):
223 """Set glitching voltages. (0x0fff is max.)"""
224 self.data=[low&0xff, (low>>8)&0xff,
225 high&0xff, (high>>8)&0xff];
226 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
227 #return ord(self.data[0]);
228 def glitchRate(self,count=0x0800):
229 """Set glitching count period."""
230 self.data=[count&0xff, (count>>8)&0xff];
231 self.writecmd(self.GLITCHAPP,0x91,2,
233 #return ord(self.data[0]);
237 def silent(self,s=0):
238 """Transmissions halted when 1."""
240 print "besilent is %i" % self.besilent;
241 self.writecmd(0,0xB0,1,[s]);
243 def mon_connected(self):
244 """Announce to the monitor that the connection is good."""
246 self.writecmd(0,0xB1,0,[]);
248 """Write a byte to P5OUT."""
249 self.writecmd(0,0xA1,1,[byte]);
251 """Write a byte to P5DIR."""
252 self.writecmd(0,0xA0,1,[byte]);
254 """Call to an address."""
255 self.writecmd(0,0x30,2,
256 [adr&0xFF,(adr>>8)&0xFF]);
257 def execute(self,code):
258 """Execute supplied code."""
259 self.writecmd(0,0x31,2,#len(code),
261 def peekbyte(self,address):
262 """Read a byte of memory from the monitor."""
263 self.data=[address&0xff,address>>8];
264 self.writecmd(0,0x02,2,self.data);
266 return ord(self.data[0]);
267 def peekword(self,address):
268 """Read a word of memory from the monitor."""
269 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
270 def pokebyte(self,address,value):
271 """Set a byte of memory by the monitor."""
272 self.data=[address&0xff,address>>8,value];
273 self.writecmd(0,0x03,3,self.data);
274 return ord(self.data[0]);
275 def dumpmem(self,begin,end):
278 print "%04x %04x" % (i, self.peekword(i));
280 def monitor_ram_pattern(self):
281 """Overwrite all of RAM with 0xBEEF."""
282 self.writecmd(0,0x90,0,self.data);
284 def monitor_ram_depth(self):
285 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
286 self.writecmd(0,0x91,0,self.data);
287 return ord(self.data[0])+(ord(self.data[1])<<8);
296 def setBaud(self,baud):
297 """Change the baud rate. TODO fix this."""
298 rates=self.baudrates;
300 print "Changing FET baud."
301 self.serialport.write(chr(0x00));
302 self.serialport.write(chr(0x80));
303 self.serialport.write(chr(1));
304 self.serialport.write(chr(baud));
306 print "Changed host baud."
307 self.serialport.setBaudrate(rates[baud]);
309 self.serialport.flushInput()
310 self.serialport.flushOutput()
312 print "Baud is now %i." % rates[baud];
315 return ord(self.serialport.read(1));
317 for r in self.baudrates:
318 print "\nTrying %i" % r;
319 self.serialport.setBaudrate(r);
321 self.serialport.flushInput()
322 self.serialport.flushOutput()
324 for i in range(1,10):
327 print "Read %02x %02x %02x %02x" % (
328 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
329 def monitortest(self):
330 """Self-test several functions through the monitor."""
331 print "Performing monitor self-test.";
332 self.monitorclocking();
333 for f in range(0,3000):
334 a=self.peekword(0x0c00);
335 b=self.peekword(0x0c02);
336 if a!=0x0c04 and a!=0x0c06:
337 print "ERROR Fetched %04x, %04x" % (a,b);
338 self.pokebyte(0x0021,0); #Drop LED
339 if self.peekbyte(0x0021)!=0:
340 print "ERROR, P1OUT not cleared.";
341 self.pokebyte(0x0021,1); #Light LED
342 if not self.monitorecho():
343 print "Echo test failed.";
344 print "Self-test complete.";
345 self.monitorclocking();
346 def monitorecho(self):
347 data="The quick brown fox jumped over the lazy dog.";
348 self.writecmd(self.MONITORAPP,0x81,len(data),data);
350 if verbose: print "Comm error recognized.";
353 def monitorclocking(self):
354 DCOCTL=self.peekbyte(0x0056);
355 BCSCTL1=self.peekbyte(0x0057);
356 return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
358 # The following functions ought to be implemented in
361 def infostring(self):
362 a=self.peekbyte(0xff0);
363 b=self.peekbyte(0xff1);
364 return "%02x%02x" % (a,b);
366 print "Locking Unsupported.";
368 print "Erasure Unsupported.";
374 print "Unimplemented.";
377 print "Unimplemented.";
380 print "Unimplemented.";
383 print "Unimplemented.";
386 print "Unimplemented.";
388 def flash(self,file):
389 """Flash an intel hex file to code memory."""
390 print "Flash not implemented.";
391 def dump(self,file,start=0,stop=0xffff):
392 """Dump an intel hex file from code memory."""
393 print "Dump not implemented.";
395 def peek32(self,address, memory="vn"):
396 return (self.peek16(address,memory)+
397 (self.peek16(address+2,memory)<<16));
398 def peek16(self,address, memory="vn"):
399 return (self.peek8(address,memory)+
400 (self.peek8(address+1,memory)<<8));
401 def peek8(self,address, memory="vn"):
402 return self.peekbyte(address); #monitor
403 def loadsymbols(self):