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()):
96 if hwid.index('FTDI')==0:
98 #print "Using FTDI port %s" % port
101 self.serialport = serial.Serial(
105 parity = serial.PARITY_NONE,
113 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
115 self.serialport.flushInput()
116 self.serialport.flushOutput()
117 #Explicitly set RTS and DTR to halt board.
118 self.serialport.setRTS(1);
119 self.serialport.setDTR(1);
120 #Drop DTR, which is !RST, low to begin the app.
121 self.serialport.setDTR(0);
122 self.serialport.flushInput()
123 self.serialport.flushOutput()
126 self.readcmd(); #Read the first command.
127 #Here we have a connection, but maybe not a good one.
129 olds=self.infostring();
130 clocking=self.monitorclocking();
131 for foo in range(1,30):
132 if not self.monitorecho():
133 if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
137 if self.verbose: print "Connected after %02i attempts." % attempts;
138 self.mon_connected();
140 def getbuffer(self,size=0x1c00):
141 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
142 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
143 def writecmd(self, app, verb, count=0, data=[]):
144 """Write a command and some data to the GoodFET."""
145 self.serialport.write(chr(app));
146 self.serialport.write(chr(verb));
149 # count=len(data); #Initial count ignored.
151 #print "TX %02x %02x %04x" % (app,verb,count);
153 #little endian 16-bit length
154 self.serialport.write(chr(count&0xFF));
155 self.serialport.write(chr(count>>8));
158 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
160 #print "count=%02x, len(data)=%04x" % (count,len(data));
163 if(isinstance(data,list)):
164 for i in range(0,count):
165 #print "Converting %02x at %i" % (data[i],i)
166 data[i]=chr(data[i]);
168 outstr=''.join(data);
169 self.serialport.write(outstr);
170 if not self.besilent:
171 return self.readcmd()
176 """Read a reply from the GoodFET."""
177 while 1:#self.serialport.inWaiting(): # Loop while input data is available
180 self.app=ord(self.serialport.read(1));
181 #print "APP=%2x" % self.app;
182 self.verb=ord(self.serialport.read(1));
183 #print "VERB=%02x" % self.verb;
185 ord(self.serialport.read(1))
186 +(ord(self.serialport.read(1))<<8)
190 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
192 #Debugging string; print, but wait.
195 print "# DEBUG %s" % self.serialport.read(self.count)
196 elif self.verb==0xFE:
197 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
200 self.data=self.serialport.read(self.count);
204 print "Error: waiting for serial read timed out (most likely).";
205 print "This shouldn't happen after syncing. Exiting for safety.";
209 def glitchApp(self,app):
210 """Glitch into a device by its application."""
211 self.data=[app&0xff];
212 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
213 #return ord(self.data[0]);
214 def glitchVerb(self,app,verb,data):
215 """Glitch during a transaction."""
216 if data==None: data=[];
217 self.data=[app&0xff, verb&0xFF]+data;
218 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
219 #return ord(self.data[0]);
220 def glitchstart(self):
221 """Glitch into the AVR application."""
222 self.glitchVerb(self.APP,0x20,None);
223 def glitchstarttime(self):
224 """Measure the timer of the START verb."""
225 return self.glitchTime(self.APP,0x20,None);
226 def glitchTime(self,app,verb,data):
227 """Time the execution of a verb."""
228 if data==None: data=[];
229 self.data=[app&0xff, verb&0xFF]+data;
230 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
231 return ord(self.data[0])+(ord(self.data[1])<<8);
232 def glitchVoltages(self,low=0x0880, high=0x0fff):
233 """Set glitching voltages. (0x0fff is max.)"""
234 self.data=[low&0xff, (low>>8)&0xff,
235 high&0xff, (high>>8)&0xff];
236 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
237 #return ord(self.data[0]);
238 def glitchRate(self,count=0x0800):
239 """Set glitching count period."""
240 self.data=[count&0xff, (count>>8)&0xff];
241 self.writecmd(self.GLITCHAPP,0x91,2,
243 #return ord(self.data[0]);
247 def silent(self,s=0):
248 """Transmissions halted when 1."""
250 print "besilent is %i" % self.besilent;
251 self.writecmd(0,0xB0,1,[s]);
253 def mon_connected(self):
254 """Announce to the monitor that the connection is good."""
256 self.writecmd(0,0xB1,0,[]);
258 """Write a byte to P5OUT."""
259 self.writecmd(0,0xA1,1,[byte]);
261 """Write a byte to P5DIR."""
262 self.writecmd(0,0xA0,1,[byte]);
264 """Call to an address."""
265 self.writecmd(0,0x30,2,
266 [adr&0xFF,(adr>>8)&0xFF]);
267 def execute(self,code):
268 """Execute supplied code."""
269 self.writecmd(0,0x31,2,#len(code),
271 def peekbyte(self,address):
272 """Read a byte of memory from the monitor."""
273 self.data=[address&0xff,address>>8];
274 self.writecmd(0,0x02,2,self.data);
276 return ord(self.data[0]);
277 def peekword(self,address):
278 """Read a word of memory from the monitor."""
279 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
280 def peek(self,address):
281 """Read a word of memory from the monitor."""
282 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
283 def pokebyte(self,address,value):
284 """Set a byte of memory by the monitor."""
285 self.data=[address&0xff,address>>8,value];
286 self.writecmd(0,0x03,3,self.data);
287 return ord(self.data[0]);
288 def dumpmem(self,begin,end):
291 print "%04x %04x" % (i, self.peekword(i));
293 def monitor_ram_pattern(self):
294 """Overwrite all of RAM with 0xBEEF."""
295 self.writecmd(0,0x90,0,self.data);
297 def monitor_ram_depth(self):
298 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
299 self.writecmd(0,0x91,0,self.data);
300 return ord(self.data[0])+(ord(self.data[1])<<8);
309 def setBaud(self,baud):
310 """Change the baud rate. TODO fix this."""
311 rates=self.baudrates;
313 print "Changing FET baud."
314 self.serialport.write(chr(0x00));
315 self.serialport.write(chr(0x80));
316 self.serialport.write(chr(1));
317 self.serialport.write(chr(baud));
319 print "Changed host baud."
320 self.serialport.setBaudrate(rates[baud]);
322 self.serialport.flushInput()
323 self.serialport.flushOutput()
325 print "Baud is now %i." % rates[baud];
328 return ord(self.serialport.read(1));
330 for r in self.baudrates:
331 print "\nTrying %i" % r;
332 self.serialport.setBaudrate(r);
334 self.serialport.flushInput()
335 self.serialport.flushOutput()
337 for i in range(1,10):
340 print "Read %02x %02x %02x %02x" % (
341 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
342 def monitortest(self):
343 """Self-test several functions through the monitor."""
344 print "Performing monitor self-test.";
345 self.monitorclocking();
346 for f in range(0,3000):
347 a=self.peekword(0x0c00);
348 b=self.peekword(0x0c02);
349 if a!=0x0c04 and a!=0x0c06:
350 print "ERROR Fetched %04x, %04x" % (a,b);
351 self.pokebyte(0x0021,0); #Drop LED
352 if self.peekbyte(0x0021)!=0:
353 print "ERROR, P1OUT not cleared.";
354 self.pokebyte(0x0021,1); #Light LED
355 if not self.monitorecho():
356 print "Echo test failed.";
357 print "Self-test complete.";
358 self.monitorclocking();
359 def monitorecho(self):
360 data="The quick brown fox jumped over the lazy dog.";
361 self.writecmd(self.MONITORAPP,0x81,len(data),data);
363 if self.verbose: print "Comm error recognized by monitorecho().";
366 def monitorclocking(self):
367 DCOCTL=self.peekbyte(0x0056);
368 BCSCTL1=self.peekbyte(0x0057);
369 return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
371 # The following functions ought to be implemented in
374 def infostring(self):
375 a=self.peekbyte(0xff0);
376 b=self.peekbyte(0xff1);
377 return "%02x%02x" % (a,b);
379 print "Locking Unsupported.";
381 print "Erasure Unsupported.";
387 print "Unimplemented.";
390 print "Unimplemented.";
393 print "Unimplemented.";
396 print "Unimplemented.";
399 print "Unimplemented.";
401 def flash(self,file):
402 """Flash an intel hex file to code memory."""
403 print "Flash not implemented.";
404 def dump(self,file,start=0,stop=0xffff):
405 """Dump an intel hex file from code memory."""
406 print "Dump not implemented.";
407 def peek32(self,address, memory="vn"):
408 return (self.peek16(address,memory)+
409 (self.peek16(address+2,memory)<<16));
410 def peek16(self,address, memory="vn"):
411 return (self.peek8(address,memory)+
412 (self.peek8(address+1,memory)<<8));
413 def peek8(self,address, memory="vn"):
414 return self.peekbyte(address); #monitor
415 def peekword(self,address, memory="vn"):
416 return self.peek(address); #monitor
418 def loadsymbols(self):