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, 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();
22 print "Unsupported target: %s" % name;
26 """GoodFET Symbol Table"""
27 db=sqlite3.connect(":memory:");
29 def __init__(self, *args, **kargs):
30 self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
35 c.execute("select adr,memory from symbols where name=?",(name,));
41 except:# sqlite3.OperationalError:
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);
52 """GoodFET Client Library"""
63 symbols=SymbolTable();
65 def __init__(self, *args, **kargs):
68 from GoodFETConsole import GoodFETConsole;
69 return GoodFETConsole(self);
70 def name2adr(self,name):
71 return self.symbols.get(name);
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.
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:
83 port = os.environ.get("GOODFET");
85 glob_list = glob.glob("/dev/tty.usbserial*");
86 if len(glob_list) > 0:
89 glob_list = glob.glob("/dev/ttyUSB*");
90 if len(glob_list) > 0:
93 from scanwin32 import winScan;
95 for order,comport,desc,hwid in sorted(scan.comports()):
97 if hwid.index('FTDI')==0:
99 #print "Using FTDI port %s" % port
104 self.serialport = serial.Serial(
108 parity = serial.PARITY_NONE,
116 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
118 self.serialport.flushInput()
119 self.serialport.flushOutput()
120 #Explicitly set RTS and DTR to halt board.
121 self.serialport.setRTS(1);
122 self.serialport.setDTR(1);
123 #Drop DTR, which is !RST, low to begin the app.
124 self.serialport.setDTR(0);
125 self.serialport.flushInput()
126 self.serialport.flushOutput()
129 self.readcmd(); #Read the first command.
130 #Here we have a connection, but maybe not a good one.
132 olds=self.infostring();
133 clocking=self.monitorclocking();
134 for foo in range(1,30):
135 if not self.monitorecho():
136 if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
140 if self.verbose: print "Connected after %02i attempts." % attempts;
141 self.mon_connected();
143 def getbuffer(self,size=0x1c00):
144 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
145 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
146 def writecmd(self, app, verb, count=0, data=[]):
147 """Write a command and some data to the GoodFET."""
148 self.serialport.write(chr(app));
149 self.serialport.write(chr(verb));
152 # count=len(data); #Initial count ignored.
154 #print "TX %02x %02x %04x" % (app,verb,count);
156 #little endian 16-bit length
157 self.serialport.write(chr(count&0xFF));
158 self.serialport.write(chr(count>>8));
161 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
163 #print "count=%02x, len(data)=%04x" % (count,len(data));
166 if(isinstance(data,list)):
167 for i in range(0,count):
168 #print "Converting %02x at %i" % (data[i],i)
169 data[i]=chr(data[i]);
171 outstr=''.join(data);
172 self.serialport.write(outstr);
173 if not self.besilent:
174 return self.readcmd()
179 """Read a reply from the GoodFET."""
180 while 1:#self.serialport.inWaiting(): # Loop while input data is available
183 self.app=ord(self.serialport.read(1));
184 #print "APP=%2x" % self.app;
185 self.verb=ord(self.serialport.read(1));
186 #print "VERB=%02x" % self.verb;
188 ord(self.serialport.read(1))
189 +(ord(self.serialport.read(1))<<8)
193 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
195 #Debugging string; print, but wait.
198 print "# DEBUG %s" % self.serialport.read(self.count)
199 elif self.verb==0xFE:
200 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
201 elif self.verb==0xFD:
202 #Do nothing, just wait so there's no timeout.
207 self.data=self.serialport.read(self.count);
211 print "Error: waiting for serial read timed out (most likely).";
212 print "This shouldn't happen after syncing. Exiting for safety.";
216 def glitchApp(self,app):
217 """Glitch into a device by its application."""
218 self.data=[app&0xff];
219 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
220 #return ord(self.data[0]);
221 def glitchVerb(self,app,verb,data):
222 """Glitch during a transaction."""
223 if data==None: data=[];
224 self.data=[app&0xff, verb&0xFF]+data;
225 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
226 #return ord(self.data[0]);
227 def glitchstart(self):
228 """Glitch into the AVR application."""
229 self.glitchVerb(self.APP,0x20,None);
230 def glitchstarttime(self):
231 """Measure the timer of the START verb."""
232 return self.glitchTime(self.APP,0x20,None);
233 def glitchTime(self,app,verb,data):
234 """Time the execution of a verb."""
235 if data==None: data=[];
236 self.data=[app&0xff, verb&0xFF]+data;
237 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
238 return ord(self.data[0])+(ord(self.data[1])<<8);
239 def glitchVoltages(self,low=0x0880, high=0x0fff):
240 """Set glitching voltages. (0x0fff is max.)"""
241 self.data=[low&0xff, (low>>8)&0xff,
242 high&0xff, (high>>8)&0xff];
243 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
244 #return ord(self.data[0]);
245 def glitchRate(self,count=0x0800):
246 """Set glitching count period."""
247 self.data=[count&0xff, (count>>8)&0xff];
248 self.writecmd(self.GLITCHAPP,0x91,2,
250 #return ord(self.data[0]);
254 def silent(self,s=0):
255 """Transmissions halted when 1."""
257 print "besilent is %i" % self.besilent;
258 self.writecmd(0,0xB0,1,[s]);
260 def mon_connected(self):
261 """Announce to the monitor that the connection is good."""
263 self.writecmd(0,0xB1,0,[]);
265 """Write a byte to P5OUT."""
266 self.writecmd(0,0xA1,1,[byte]);
268 """Write a byte to P5DIR."""
269 self.writecmd(0,0xA0,1,[byte]);
271 """Call to an address."""
272 self.writecmd(0,0x30,2,
273 [adr&0xFF,(adr>>8)&0xFF]);
274 def execute(self,code):
275 """Execute supplied code."""
276 self.writecmd(0,0x31,2,#len(code),
278 def peekbyte(self,address):
279 """Read a byte of memory from the monitor."""
280 self.data=[address&0xff,address>>8];
281 self.writecmd(0,0x02,2,self.data);
283 return ord(self.data[0]);
284 def peekword(self,address):
285 """Read a word of memory from the monitor."""
286 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
287 def peek(self,address):
288 """Read a word of memory from the monitor."""
289 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
290 def pokebyte(self,address,value):
291 """Set a byte of memory by the monitor."""
292 self.data=[address&0xff,address>>8,value];
293 self.writecmd(0,0x03,3,self.data);
294 return ord(self.data[0]);
295 def dumpmem(self,begin,end):
298 print "%04x %04x" % (i, self.peekword(i));
300 def monitor_ram_pattern(self):
301 """Overwrite all of RAM with 0xBEEF."""
302 self.writecmd(0,0x90,0,self.data);
304 def monitor_ram_depth(self):
305 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
306 self.writecmd(0,0x91,0,self.data);
307 return ord(self.data[0])+(ord(self.data[1])<<8);
316 def setBaud(self,baud):
317 """Change the baud rate. TODO fix this."""
318 rates=self.baudrates;
320 print "Changing FET baud."
321 self.serialport.write(chr(0x00));
322 self.serialport.write(chr(0x80));
323 self.serialport.write(chr(1));
324 self.serialport.write(chr(baud));
326 print "Changed host baud."
327 self.serialport.setBaudrate(rates[baud]);
329 self.serialport.flushInput()
330 self.serialport.flushOutput()
332 print "Baud is now %i." % rates[baud];
335 return ord(self.serialport.read(1));
337 for r in self.baudrates:
338 print "\nTrying %i" % r;
339 self.serialport.setBaudrate(r);
341 self.serialport.flushInput()
342 self.serialport.flushOutput()
344 for i in range(1,10):
347 print "Read %02x %02x %02x %02x" % (
348 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
349 def monitortest(self):
350 """Self-test several functions through the monitor."""
351 print "Performing monitor self-test.";
352 self.monitorclocking();
353 for f in range(0,3000):
354 a=self.peekword(0x0c00);
355 b=self.peekword(0x0c02);
356 if a!=0x0c04 and a!=0x0c06:
357 print "ERROR Fetched %04x, %04x" % (a,b);
358 self.pokebyte(0x0021,0); #Drop LED
359 if self.peekbyte(0x0021)!=0:
360 print "ERROR, P1OUT not cleared.";
361 self.pokebyte(0x0021,1); #Light LED
362 if not self.monitorecho():
363 print "Echo test failed.";
364 print "Self-test complete.";
365 self.monitorclocking();
366 def monitorecho(self):
367 data="The quick brown fox jumped over the lazy dog.";
368 self.writecmd(self.MONITORAPP,0x81,len(data),data);
370 if self.verbose: print "Comm error recognized by monitorecho().";
373 def monitorclocking(self):
374 DCOCTL=self.peekbyte(0x0056);
375 BCSCTL1=self.peekbyte(0x0057);
376 return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
378 # The following functions ought to be implemented in
381 def infostring(self):
382 a=self.peekbyte(0xff0);
383 b=self.peekbyte(0xff1);
384 return "%02x%02x" % (a,b);
386 print "Locking Unsupported.";
388 print "Erasure Unsupported.";
394 print "Unimplemented.";
397 print "Unimplemented.";
400 print "Unimplemented.";
403 print "Unimplemented.";
406 print "Unimplemented.";
408 def flash(self,file):
409 """Flash an intel hex file to code memory."""
410 print "Flash not implemented.";
411 def dump(self,file,start=0,stop=0xffff):
412 """Dump an intel hex file from code memory."""
413 print "Dump not implemented.";
414 def peek32(self,address, memory="vn"):
415 return (self.peek16(address,memory)+
416 (self.peek16(address+2,memory)<<16));
417 def peek16(self,address, memory="vn"):
418 return (self.peek8(address,memory)+
419 (self.peek8(address+1,memory)<<8));
420 def peek8(self,address, memory="vn"):
421 return self.peekbyte(address); #monitor
422 def peekword(self,address, memory="vn"):
423 return self.peek(address); #monitor
425 def loadsymbols(self):