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 GoodFETMSP430.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:
94 self.serialport = serial.Serial(
98 parity = serial.PARITY_NONE,
106 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
108 self.serialport.flushInput()
109 self.serialport.flushOutput()
110 #Explicitly set RTS and DTR to halt board.
111 self.serialport.setRTS(1);
112 self.serialport.setDTR(1);
113 #Drop DTR, which is !RST, low to begin the app.
114 self.serialport.setDTR(0);
115 self.serialport.flushInput()
116 self.serialport.flushOutput()
119 self.readcmd(); #Read the first command.
120 #Here we have a connection, but maybe not a good one.
122 olds=self.infostring();
123 clocking=self.monitorclocking();
124 for foo in range(1,30):
125 if not self.monitorecho():
126 if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
130 if self.verbose: print "Connected after %02i attempts." % attempts;
131 self.mon_connected();
133 def getbuffer(self,size=0x1c00):
134 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
135 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
136 def writecmd(self, app, verb, count=0, data=[]):
137 """Write a command and some data to the GoodFET."""
138 self.serialport.write(chr(app));
139 self.serialport.write(chr(verb));
142 # count=len(data); #Initial count ignored.
144 #print "TX %02x %02x %04x" % (app,verb,count);
146 #little endian 16-bit length
147 self.serialport.write(chr(count&0xFF));
148 self.serialport.write(chr(count>>8));
151 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
153 #print "count=%02x, len(data)=%04x" % (count,len(data));
156 if(isinstance(data,list)):
157 for i in range(0,count):
158 #print "Converting %02x at %i" % (data[i],i)
159 data[i]=chr(data[i]);
161 outstr=''.join(data);
162 self.serialport.write(outstr);
163 if not self.besilent:
164 return self.readcmd()
169 """Read a reply from the GoodFET."""
170 while 1:#self.serialport.inWaiting(): # Loop while input data is available
173 self.app=ord(self.serialport.read(1));
174 #print "APP=%2x" % self.app;
175 self.verb=ord(self.serialport.read(1));
176 #print "VERB=%02x" % self.verb;
178 ord(self.serialport.read(1))
179 +(ord(self.serialport.read(1))<<8)
183 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
185 #Debugging string; print, but wait.
188 print "# DEBUG %s" % self.serialport.read(self.count)
189 elif self.verb==0xFE:
190 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
193 self.data=self.serialport.read(self.count);
197 print "Error: waiting for serial read timed out (most likely).";
198 print "This shouldn't happen after syncing. Exiting for safety.";
202 def glitchApp(self,app):
203 """Glitch into a device by its application."""
204 self.data=[app&0xff];
205 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
206 #return ord(self.data[0]);
207 def glitchVerb(self,app,verb,data):
208 """Glitch during a transaction."""
209 if data==None: data=[];
210 self.data=[app&0xff, verb&0xFF]+data;
211 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
212 #return ord(self.data[0]);
213 def glitchstart(self):
214 """Glitch into the AVR application."""
215 self.glitchVerb(self.APP,0x20,None);
216 def glitchstarttime(self):
217 """Measure the timer of the START verb."""
218 return self.glitchTime(self.APP,0x20,None);
219 def glitchTime(self,app,verb,data):
220 """Time the execution of a verb."""
221 if data==None: data=[];
222 self.data=[app&0xff, verb&0xFF]+data;
223 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
224 return ord(self.data[0])+(ord(self.data[1])<<8);
225 def glitchVoltages(self,low=0x0880, high=0x0fff):
226 """Set glitching voltages. (0x0fff is max.)"""
227 self.data=[low&0xff, (low>>8)&0xff,
228 high&0xff, (high>>8)&0xff];
229 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
230 #return ord(self.data[0]);
231 def glitchRate(self,count=0x0800):
232 """Set glitching count period."""
233 self.data=[count&0xff, (count>>8)&0xff];
234 self.writecmd(self.GLITCHAPP,0x91,2,
236 #return ord(self.data[0]);
240 def silent(self,s=0):
241 """Transmissions halted when 1."""
243 print "besilent is %i" % self.besilent;
244 self.writecmd(0,0xB0,1,[s]);
246 def mon_connected(self):
247 """Announce to the monitor that the connection is good."""
249 self.writecmd(0,0xB1,0,[]);
251 """Write a byte to P5OUT."""
252 self.writecmd(0,0xA1,1,[byte]);
254 """Write a byte to P5DIR."""
255 self.writecmd(0,0xA0,1,[byte]);
257 """Call to an address."""
258 self.writecmd(0,0x30,2,
259 [adr&0xFF,(adr>>8)&0xFF]);
260 def execute(self,code):
261 """Execute supplied code."""
262 self.writecmd(0,0x31,2,#len(code),
264 def peekbyte(self,address):
265 """Read a byte of memory from the monitor."""
266 self.data=[address&0xff,address>>8];
267 self.writecmd(0,0x02,2,self.data);
269 return ord(self.data[0]);
270 def peekword(self,address):
271 """Read a word of memory from the monitor."""
272 return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
273 def pokebyte(self,address,value):
274 """Set a byte of memory by the monitor."""
275 self.data=[address&0xff,address>>8,value];
276 self.writecmd(0,0x03,3,self.data);
277 return ord(self.data[0]);
278 def dumpmem(self,begin,end):
281 print "%04x %04x" % (i, self.peekword(i));
283 def monitor_ram_pattern(self):
284 """Overwrite all of RAM with 0xBEEF."""
285 self.writecmd(0,0x90,0,self.data);
287 def monitor_ram_depth(self):
288 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
289 self.writecmd(0,0x91,0,self.data);
290 return ord(self.data[0])+(ord(self.data[1])<<8);
299 def setBaud(self,baud):
300 """Change the baud rate. TODO fix this."""
301 rates=self.baudrates;
303 print "Changing FET baud."
304 self.serialport.write(chr(0x00));
305 self.serialport.write(chr(0x80));
306 self.serialport.write(chr(1));
307 self.serialport.write(chr(baud));
309 print "Changed host baud."
310 self.serialport.setBaudrate(rates[baud]);
312 self.serialport.flushInput()
313 self.serialport.flushOutput()
315 print "Baud is now %i." % rates[baud];
318 return ord(self.serialport.read(1));
320 for r in self.baudrates:
321 print "\nTrying %i" % r;
322 self.serialport.setBaudrate(r);
324 self.serialport.flushInput()
325 self.serialport.flushOutput()
327 for i in range(1,10):
330 print "Read %02x %02x %02x %02x" % (
331 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
332 def monitortest(self):
333 """Self-test several functions through the monitor."""
334 print "Performing monitor self-test.";
335 self.monitorclocking();
336 for f in range(0,3000):
337 a=self.peekword(0x0c00);
338 b=self.peekword(0x0c02);
339 if a!=0x0c04 and a!=0x0c06:
340 print "ERROR Fetched %04x, %04x" % (a,b);
341 self.pokebyte(0x0021,0); #Drop LED
342 if self.peekbyte(0x0021)!=0:
343 print "ERROR, P1OUT not cleared.";
344 self.pokebyte(0x0021,1); #Light LED
345 if not self.monitorecho():
346 print "Echo test failed.";
347 print "Self-test complete.";
348 self.monitorclocking();
349 def monitorecho(self):
350 data="The quick brown fox jumped over the lazy dog.";
351 self.writecmd(self.MONITORAPP,0x81,len(data),data);
353 if self.verbose: print "Comm error recognized by monitorecho().";
356 def monitorclocking(self):
357 DCOCTL=self.peekbyte(0x0056);
358 BCSCTL1=self.peekbyte(0x0057);
359 return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
361 # The following functions ought to be implemented in
364 def infostring(self):
365 a=self.peekbyte(0xff0);
366 b=self.peekbyte(0xff1);
367 return "%02x%02x" % (a,b);
369 print "Locking Unsupported.";
371 print "Erasure Unsupported.";
377 print "Unimplemented.";
380 print "Unimplemented.";
383 print "Unimplemented.";
386 print "Unimplemented.";
389 print "Unimplemented.";
391 def flash(self,file):
392 """Flash an intel hex file to code memory."""
393 print "Flash not implemented.";
394 def dump(self,file,start=0,stop=0xffff):
395 """Dump an intel hex file from code memory."""
396 print "Dump not implemented.";
398 def peek32(self,address, memory="vn"):
399 return (self.peek16(address,memory)+
400 (self.peek16(address+2,memory)<<16));
401 def peek16(self,address, memory="vn"):
402 return (self.peek8(address,memory)+
403 (self.peek8(address+1,memory)<<8));
404 def peek8(self,address, memory="vn"):
405 return self.peekbyte(address); #monitor
406 def loadsymbols(self):