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, GoodFETCCSPI;
15 if(name=="GoodFET" or name=="monitor"): return GoodFET.GoodFET();
16 elif name=="cc" or name=="cc51": return GoodFETCC.GoodFETCC();
17 elif name=="cc2420" or name=="ccspi": return GoodFETCCSPI.GoodFETCCSPI();
18 elif name=="avr": return GoodFETAVR.GoodFETAVR();
19 elif name=="spi": return GoodFETSPI.GoodFETSPI();
20 elif name=="msp430": return GoodFETMSP430.GoodFETMSP430();
21 elif name=="nrf": return GoodFETNRF.GoodFETNRF();
23 print "Unsupported target: %s" % name;
27 """GoodFET Symbol Table"""
28 db=sqlite3.connect(":memory:");
30 def __init__(self, *args, **kargs):
31 self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
36 c.execute("select adr,memory from symbols where name=?",(name,));
42 except:# sqlite3.OperationalError:
46 def define(self,adr,name,comment="",memory="vn",size=16):
47 self.db.execute("insert into symbols(adr,name,memory,size,comment)"
48 "values(?,?,?,?,?);", (
49 adr,name,memory,size,comment));
50 #print "Set %s=%s." % (name,adr);
53 """GoodFET Client Library"""
64 symbols=SymbolTable();
66 def __init__(self, *args, **kargs):
69 from GoodFETConsole import GoodFETConsole;
70 return GoodFETConsole(self);
71 def name2adr(self,name):
72 return self.symbols.get(name);
75 def serInit(self, port=None, timeout=2, attemptlimit=None):
76 """Open the serial port"""
77 # Make timeout None to wait forever, 0 for non-blocking mode.
79 if os.name=='nt' and sys.version.find('64 bit')!=-1:
80 print "WARNING: PySerial requires a 32-bit Python build in Windows.";
82 if port is None and os.environ.get("GOODFET")!=None:
83 glob_list = glob.glob(os.environ.get("GOODFET"));
84 if len(glob_list) > 0:
87 port = os.environ.get("GOODFET");
89 glob_list = glob.glob("/dev/tty.usbserial*");
90 if len(glob_list) > 0:
93 glob_list = glob.glob("/dev/ttyUSB*");
94 if len(glob_list) > 0:
97 glob_list = glob.glob("/dev/ttyU0");
98 if len(glob_list) > 0:
100 if port is None and os.name=='nt':
101 from scanwin32 import winScan;
103 for order,comport,desc,hwid in sorted(scan.comports()):
105 if hwid.index('FTDI')==0:
107 #print "Using FTDI port %s" % port
113 if(os.environ.get("platform")=='arduino'):
114 baud=19200; #Slower, for now.
115 self.serialport = serial.Serial(
119 parity = serial.PARITY_NONE,
127 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
128 #while self.data!="http://goodfet.sf.net/":
129 #print "'%s'!=\n'%s'" % (self.data,"http://goodfet.sf.net/");
130 if attemptlimit is not None and attempts >= attemptlimit:
134 self.serialport.flushInput()
135 self.serialport.flushOutput()
137 #TelosB reset, prefer software to I2C SPST Switch.
138 if(os.environ.get("platform")=='telosb'):
139 #print "TelosB Reset";
142 #Explicitly set RTS and DTR to halt board.
143 self.serialport.setRTS(1);
144 self.serialport.setDTR(1);
145 #Drop DTR, which is !RST, low to begin the app.
146 self.serialport.setDTR(0);
148 #self.serialport.write(chr(0x80));
149 #self.serialport.write(chr(0x80));
150 #self.serialport.write(chr(0x80));
151 #self.serialport.write(chr(0x80));
154 #self.serialport.flushInput()
155 #self.serialport.flushOutput()
158 self.readcmd(); #Read the first command.
159 #print "Got %02x,%02x:'%s'" % (self.app,self.verb,self.data);
160 #Here we have a connection, but maybe not a good one.
161 #print "We have a connection."
163 olds=self.infostring();
164 clocking=self.monitorclocking();
165 #if(os.environ.get("platform")!='arduino'):
166 for foo in range(1,30):
167 if not self.monitorecho():
169 print "Comm error on %i try, resyncing out of %s." % (foo,
173 if self.verbose: print "Connected after %02i attempts." % attempts;
174 self.mon_connected();
175 self.serialport.setTimeout(12);
177 self.serialport.close();
178 def telosSetSCL(self, level):
179 self.serialport.setRTS(not level)
180 def telosSetSDA(self, level):
181 self.serialport.setDTR(not level)
183 def telosI2CStart(self):
188 def telosI2CStop(self):
193 def telosI2CWriteBit(self, bit):
195 self.telosSetSDA(bit)
201 def telosI2CWriteByte(self, byte):
202 self.telosI2CWriteBit( byte & 0x80 );
203 self.telosI2CWriteBit( byte & 0x40 );
204 self.telosI2CWriteBit( byte & 0x20 );
205 self.telosI2CWriteBit( byte & 0x10 );
206 self.telosI2CWriteBit( byte & 0x08 );
207 self.telosI2CWriteBit( byte & 0x04 );
208 self.telosI2CWriteBit( byte & 0x02 );
209 self.telosI2CWriteBit( byte & 0x01 );
210 self.telosI2CWriteBit( 0 ); # "acknowledge"
212 def telosI2CWriteCmd(self, addr, cmdbyte):
214 self.telosI2CWriteByte( 0x90 | (addr << 1) )
215 self.telosI2CWriteByte( cmdbyte )
218 def telosBReset(self,invokeBSL=0):
219 # "BSL entry sequence at dedicated JTAG pins"
220 # rst !s0: 0 0 0 0 1 1
221 # tck !s1: 1 0 1 0 0 1
224 # "BSL entry sequence at shared JTAG pins"
225 # rst !s0: 0 0 0 0 1 1
226 # tck !s1: 0 1 0 1 1 0
230 self.telosI2CWriteCmd(0,1)
231 self.telosI2CWriteCmd(0,3)
232 self.telosI2CWriteCmd(0,1)
233 self.telosI2CWriteCmd(0,3)
234 self.telosI2CWriteCmd(0,2)
235 self.telosI2CWriteCmd(0,0)
237 self.telosI2CWriteCmd(0,3)
238 self.telosI2CWriteCmd(0,2)
240 # This line was not defined inside the else: block, not sure where it
242 self.telosI2CWriteCmd(0,0)
243 time.sleep(0.250) #give MSP430's oscillator time to stabilize
244 self.serialport.flushInput() #clear buffers
247 def getbuffer(self,size=0x1c00):
248 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
249 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
250 def writecmd(self, app, verb, count=0, data=[]):
251 """Write a command and some data to the GoodFET."""
252 self.serialport.write(chr(app));
253 self.serialport.write(chr(verb));
256 # count=len(data); #Initial count ignored.
258 #print "TX %02x %02x %04x" % (app,verb,count);
260 #little endian 16-bit length
261 self.serialport.write(chr(count&0xFF));
262 self.serialport.write(chr(count>>8));
265 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
267 #print "count=%02x, len(data)=%04x" % (count,len(data));
270 if(isinstance(data,list)):
271 for i in range(0,count):
272 #print "Converting %02x at %i" % (data[i],i)
273 data[i]=chr(data[i]);
275 outstr=''.join(data);
276 self.serialport.write(outstr);
277 if not self.besilent:
278 return self.readcmd()
283 """Read a reply from the GoodFET."""
284 while 1:#self.serialport.inWaiting(): # Loop while input data is available
287 self.app=ord(self.serialport.read(1));
288 #print "APP=%02x" % self.app;
289 self.verb=ord(self.serialport.read(1));
291 #Fixes an obscure bug in the TelosB.
293 while self.verb==0x00:
294 self.verb=ord(self.serialport.read(1));
296 #print "VERB=%02x" % self.verb;
298 ord(self.serialport.read(1))
299 +(ord(self.serialport.read(1))<<8)
303 #print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
305 #Debugging string; print, but wait.
308 print "# DEBUG %s" % self.serialport.read(self.count)
309 elif self.verb==0xFE:
310 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
311 elif self.verb==0xFD:
312 #Do nothing, just wait so there's no timeout.
317 self.data=self.serialport.read(self.count);
321 print "Warning: waiting for serial read timed out (most likely).";
322 #print "This shouldn't happen after syncing. Exiting for safety.";
326 def glitchApp(self,app):
327 """Glitch into a device by its application."""
328 self.data=[app&0xff];
329 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
330 #return ord(self.data[0]);
331 def glitchVerb(self,app,verb,data):
332 """Glitch during a transaction."""
333 if data==None: data=[];
334 self.data=[app&0xff, verb&0xFF]+data;
335 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
336 #return ord(self.data[0]);
337 def glitchstart(self):
338 """Glitch into the AVR application."""
339 self.glitchVerb(self.APP,0x20,None);
340 def glitchstarttime(self):
341 """Measure the timer of the START verb."""
342 return self.glitchTime(self.APP,0x20,None);
343 def glitchTime(self,app,verb,data):
344 """Time the execution of a verb."""
345 if data==None: data=[];
346 self.data=[app&0xff, verb&0xFF]+data;
347 print "Timing app %02x verb %02x." % (app,verb);
348 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
349 time=ord(self.data[0])+(ord(self.data[1])<<8);
350 print "Timed to be %i." % time;
352 def glitchVoltages(self,low=0x0880, high=0x0fff):
353 """Set glitching voltages. (0x0fff is max.)"""
354 self.data=[low&0xff, (low>>8)&0xff,
355 high&0xff, (high>>8)&0xff];
356 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
357 #return ord(self.data[0]);
358 def glitchRate(self,count=0x0800):
359 """Set glitching count period."""
360 self.data=[count&0xff, (count>>8)&0xff];
361 self.writecmd(self.GLITCHAPP,0x91,2,
363 #return ord(self.data[0]);
367 def silent(self,s=0):
368 """Transmissions halted when 1."""
370 print "besilent is %i" % self.besilent;
371 self.writecmd(0,0xB0,1,[s]);
373 def mon_connected(self):
374 """Announce to the monitor that the connection is good."""
376 self.writecmd(0,0xB1,0,[]);
378 """Write a byte to P5OUT."""
379 self.writecmd(0,0xA1,1,[byte]);
381 """Write a byte to P5DIR."""
382 self.writecmd(0,0xA0,1,[byte]);
384 """Call to an address."""
385 self.writecmd(0,0x30,2,
386 [adr&0xFF,(adr>>8)&0xFF]);
387 def execute(self,code):
388 """Execute supplied code."""
389 self.writecmd(0,0x31,2,#len(code),
391 def MONpeek8(self,address):
392 """Read a byte of memory from the monitor."""
393 self.data=[address&0xff,address>>8];
394 self.writecmd(0,0x02,2,self.data);
396 return ord(self.data[0]);
397 def MONpeek16(self,address):
398 """Read a word of memory from the monitor."""
399 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
400 def peek(self,address):
401 """Read a word of memory from the monitor."""
402 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
403 def eeprompeek(self,address):
404 """Read a word of memory from the monitor."""
405 print "EEPROM peeking not supported for the monitor.";
406 #return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
407 def peekbysym(self,name):
408 """Read a value by its symbol name."""
409 #TODO include memory in symbol.
410 reg=self.symbols.get(name);
411 return self.peek8(reg,"data");
412 def pokebysym(self,name,val):
413 """Write a value by its symbol name."""
414 #TODO include memory in symbol.
415 reg=self.symbols.get(name);
416 return self.pokebyte(reg,val);
417 def pokebyte(self,address,value,memory="vn"):
418 """Set a byte of memory by the monitor."""
419 self.data=[address&0xff,address>>8,value];
420 self.writecmd(0,0x03,3,self.data);
421 return ord(self.data[0]);
422 def poke16(self,address,value):
423 """Set a word of memory by the monitor."""
424 self.pokebyte(address,value&0xFF);
425 self.pokebyte(address,(value>>8)&0xFF);
427 def setsecret(self,value):
428 """Set a secret word for later retreival. Used by glitcher."""
429 #self.eeprompoke(0,value);
430 #self.eeprompoke(1,value);
431 print "Secret setting is not yet suppored for this target.";
435 """Get a secret word. Used by glitcher."""
437 print "Secret getting is not yet suppored for this target.";
441 def dumpmem(self,begin,end):
444 print "%04x %04x" % (i, self.MONpeek16(i));
446 def monitor_ram_pattern(self):
447 """Overwrite all of RAM with 0xBEEF."""
448 self.writecmd(0,0x90,0,self.data);
450 def monitor_ram_depth(self):
451 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
452 self.writecmd(0,0x91,0,self.data);
453 return ord(self.data[0])+(ord(self.data[1])<<8);
462 def setBaud(self,baud):
463 """Change the baud rate. TODO fix this."""
464 rates=self.baudrates;
466 print "Changing FET baud."
467 self.serialport.write(chr(0x00));
468 self.serialport.write(chr(0x80));
469 self.serialport.write(chr(1));
470 self.serialport.write(chr(baud));
472 print "Changed host baud."
473 self.serialport.setBaudrate(rates[baud]);
475 self.serialport.flushInput()
476 self.serialport.flushOutput()
478 print "Baud is now %i." % rates[baud];
481 return ord(self.serialport.read(1));
483 for r in self.baudrates:
484 print "\nTrying %i" % r;
485 self.serialport.setBaudrate(r);
487 self.serialport.flushInput()
488 self.serialport.flushOutput()
490 for i in range(1,10):
493 print "Read %02x %02x %02x %02x" % (
494 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
495 def monitortest(self):
496 """Self-test several functions through the monitor."""
497 print "Performing monitor self-test.";
498 self.monitorclocking();
499 for f in range(0,3000):
500 a=self.MONpeek16(0x0c00);
501 b=self.MONpeek16(0x0c02);
502 if a!=0x0c04 and a!=0x0c06:
503 print "ERROR Fetched %04x, %04x" % (a,b);
504 self.pokebyte(0x0021,0); #Drop LED
505 if self.MONpeek8(0x0021)!=0:
506 print "ERROR, P1OUT not cleared.";
507 self.pokebyte(0x0021,1); #Light LED
508 if not self.monitorecho():
509 print "Echo test failed.";
510 print "Self-test complete.";
511 self.monitorclocking();
512 def monitorecho(self):
513 data="The quick brown fox jumped over the lazy dog.";
514 self.writecmd(self.MONITORAPP,0x81,len(data),data);
516 print "Comm error recognized by monitorecho(), got:\n%s" % self.data;
520 def monitor_info(self):
521 print "GoodFET with %s MCU" % self.infostring();
522 print "Clocked at %s" % self.monitorclocking();
525 def monitor_list_apps(self, full=False):
527 old_value = self.besilent
528 self.besilent = True # turn off automatic call to readcmd
529 self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
530 self.besilent = old_value
532 # read the build date string
534 print "Build Date: %s" % self.data
535 print "Firmware apps:"
543 def monitorclocking(self):
544 """Return the 16-bit clocking value."""
545 return "0x%04x" % self.monitorgetclock();
547 def monitorsetclock(self,clock):
548 """Set the clocking value."""
549 self.MONpoke16(0x56, clock);
550 def monitorgetclock(self):
551 """Get the clocking value."""
552 if(os.environ.get("platform")=='arduino'):
554 #Check for MSP430 before peeking this.
555 return self.MONpeek16(0x56);
556 # The following functions ought to be implemented in
559 def infostring(self):
560 if(os.environ.get("platform")=='arduino'):
563 a=self.MONpeek8(0xff0);
564 b=self.MONpeek8(0xff1);
565 return "%02x%02x" % (a,b);
567 print "Locking Unsupported.";
569 print "Erasure Unsupported.";
575 print "Unimplemented.";
578 print "Unimplemented.";
581 print "Unimplemented.";
584 print "Unimplemented.";
587 print "Unimplemented.";
589 def flash(self,file):
590 """Flash an intel hex file to code memory."""
591 print "Flash not implemented.";
592 def dump(self,file,start=0,stop=0xffff):
593 """Dump an intel hex file from code memory."""
594 print "Dump not implemented.";
595 def peek32(self,address, memory="vn"):
597 return (self.peek16(address,memory)+
598 (self.peek16(address+2,memory)<<16));
599 def peek16(self,address, memory="vn"):
600 """Peek 16 bits of memory."""
601 return (self.peek8(address,memory)+
602 (self.peek8(address+1,memory)<<8));
603 def peek8(self,address, memory="vn"):
604 """Peek a byte of memory."""
605 return self.MONpeek8(address); #monitor
606 def peekblock(self,address,length,memory="vn"):
607 """Return a block of data."""
608 data=range(0,length);
609 for foo in range(0,length):
610 data[foo]=self.peek8(address+foo,memory);
612 def pokeblock(self,address,bytes,memory="vn"):
613 """Poke a block of a data into memory at an address."""
615 self.pokebyte(address,foo,memory);
618 def loadsymbols(self):
619 """Load symbols from a file."""