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]
198 elif self.verb==0xFD:
199 #Do nothing, just wait so there's no timeout.
204 self.data=self.serialport.read(self.count);
208 print "Error: waiting for serial read timed out (most likely).";
209 print "This shouldn't happen after syncing. Exiting for safety.";
213 def glitchApp(self,app):
214 """Glitch into a device by its application."""
215 self.data=[app&0xff];
216 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
217 #return ord(self.data[0]);
218 def glitchVerb(self,app,verb,data):
219 """Glitch during a transaction."""
220 if data==None: data=[];
221 self.data=[app&0xff, verb&0xFF]+data;
222 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
223 #return ord(self.data[0]);
224 def glitchstart(self):
225 """Glitch into the AVR application."""
226 self.glitchVerb(self.APP,0x20,None);
227 def glitchstarttime(self):
228 """Measure the timer of the START verb."""
229 return self.glitchTime(self.APP,0x20,None);
230 def glitchTime(self,app,verb,data):
231 """Time the execution of a verb."""
232 if data==None: data=[];
233 self.data=[app&0xff, verb&0xFF]+data;
234 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
235 return ord(self.data[0])+(ord(self.data[1])<<8);
236 def glitchVoltages(self,low=0x0880, high=0x0fff):
237 """Set glitching voltages. (0x0fff is max.)"""
238 self.data=[low&0xff, (low>>8)&0xff,
239 high&0xff, (high>>8)&0xff];
240 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
241 #return ord(self.data[0]);
242 def glitchRate(self,count=0x0800):
243 """Set glitching count period."""
244 self.data=[count&0xff, (count>>8)&0xff];
245 self.writecmd(self.GLITCHAPP,0x91,2,
247 #return ord(self.data[0]);
251 def silent(self,s=0):
252 """Transmissions halted when 1."""
254 print "besilent is %i" % self.besilent;
255 self.writecmd(0,0xB0,1,[s]);
257 def mon_connected(self):
258 """Announce to the monitor that the connection is good."""
260 self.writecmd(0,0xB1,0,[]);
262 """Write a byte to P5OUT."""
263 self.writecmd(0,0xA1,1,[byte]);
265 """Write a byte to P5DIR."""
266 self.writecmd(0,0xA0,1,[byte]);
268 """Call to an address."""
269 self.writecmd(0,0x30,2,
270 [adr&0xFF,(adr>>8)&0xFF]);
271 def execute(self,code):
272 """Execute supplied code."""
273 self.writecmd(0,0x31,2,#len(code),
275 def peekbyte(self,address):
276 """Read a byte of memory from the monitor."""
277 self.data=[address&0xff,address>>8];
278 self.writecmd(0,0x02,2,self.data);
280 return ord(self.data[0]);
281 def peekword(self,address):
282 """Read a word of memory from the monitor."""
283 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
284 def peek(self,address):
285 """Read a word of memory from the monitor."""
286 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
287 def pokebyte(self,address,value):
288 """Set a byte of memory by the monitor."""
289 self.data=[address&0xff,address>>8,value];
290 self.writecmd(0,0x03,3,self.data);
291 return ord(self.data[0]);
292 def dumpmem(self,begin,end):
295 print "%04x %04x" % (i, self.peekword(i));
297 def monitor_ram_pattern(self):
298 """Overwrite all of RAM with 0xBEEF."""
299 self.writecmd(0,0x90,0,self.data);
301 def monitor_ram_depth(self):
302 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
303 self.writecmd(0,0x91,0,self.data);
304 return ord(self.data[0])+(ord(self.data[1])<<8);
313 def setBaud(self,baud):
314 """Change the baud rate. TODO fix this."""
315 rates=self.baudrates;
317 print "Changing FET baud."
318 self.serialport.write(chr(0x00));
319 self.serialport.write(chr(0x80));
320 self.serialport.write(chr(1));
321 self.serialport.write(chr(baud));
323 print "Changed host baud."
324 self.serialport.setBaudrate(rates[baud]);
326 self.serialport.flushInput()
327 self.serialport.flushOutput()
329 print "Baud is now %i." % rates[baud];
332 return ord(self.serialport.read(1));
334 for r in self.baudrates:
335 print "\nTrying %i" % r;
336 self.serialport.setBaudrate(r);
338 self.serialport.flushInput()
339 self.serialport.flushOutput()
341 for i in range(1,10):
344 print "Read %02x %02x %02x %02x" % (
345 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
346 def monitortest(self):
347 """Self-test several functions through the monitor."""
348 print "Performing monitor self-test.";
349 self.monitorclocking();
350 for f in range(0,3000):
351 a=self.peekword(0x0c00);
352 b=self.peekword(0x0c02);
353 if a!=0x0c04 and a!=0x0c06:
354 print "ERROR Fetched %04x, %04x" % (a,b);
355 self.pokebyte(0x0021,0); #Drop LED
356 if self.peekbyte(0x0021)!=0:
357 print "ERROR, P1OUT not cleared.";
358 self.pokebyte(0x0021,1); #Light LED
359 if not self.monitorecho():
360 print "Echo test failed.";
361 print "Self-test complete.";
362 self.monitorclocking();
363 def monitorecho(self):
364 data="The quick brown fox jumped over the lazy dog.";
365 self.writecmd(self.MONITORAPP,0x81,len(data),data);
367 if self.verbose: print "Comm error recognized by monitorecho().";
370 def monitorclocking(self):
371 DCOCTL=self.peekbyte(0x0056);
372 BCSCTL1=self.peekbyte(0x0057);
373 return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
375 # The following functions ought to be implemented in
378 def infostring(self):
379 a=self.peekbyte(0xff0);
380 b=self.peekbyte(0xff1);
381 return "%02x%02x" % (a,b);
383 print "Locking Unsupported.";
385 print "Erasure Unsupported.";
391 print "Unimplemented.";
394 print "Unimplemented.";
397 print "Unimplemented.";
400 print "Unimplemented.";
403 print "Unimplemented.";
405 def flash(self,file):
406 """Flash an intel hex file to code memory."""
407 print "Flash not implemented.";
408 def dump(self,file,start=0,stop=0xffff):
409 """Dump an intel hex file from code memory."""
410 print "Dump not implemented.";
411 def peek32(self,address, memory="vn"):
412 return (self.peek16(address,memory)+
413 (self.peek16(address+2,memory)<<16));
414 def peek16(self,address, memory="vn"):
415 return (self.peek8(address,memory)+
416 (self.peek8(address+1,memory)<<8));
417 def peek8(self,address, memory="vn"):
418 return self.peekbyte(address); #monitor
419 def peekword(self,address, memory="vn"):
420 return self.peek(address); #monitor
422 def loadsymbols(self):