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, 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);
52 """py-bluez class for emulating py-serial."""
53 def __init__(self,btaddr):
55 if btaddr==None or btaddr=="none" or btaddr=="bluetooth":
56 print "performing inquiry..."
57 nearby_devices = bluetooth.discover_devices(lookup_names = True)
58 print "found %d devices" % len(nearby_devices)
59 for addr, name in nearby_devices:
60 print " %s - '%s'" % (addr, name)
61 #TODO switch to wildcards.
62 if name=='FireFly-A6BD':
67 print "Please set $GOODFET to the address of your device.";
69 print "Identified GoodFET at %s" % btaddr;
71 # Manually use the portnumber.
74 print "Connecting to %s on port %i." % (btaddr, port);
75 sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
77 sock.connect((btaddr,port));
78 sock.settimeout(10); #IMPORTANT Must be patient.
80 ##This is what we'd do for a normal reset.
82 #while not str.endswith("goodfet.sf.net/"):
86 # Instead, just return and hope for the best.
95 def read(self,length):
98 while len(data)<length:
99 data=data+self.sock.recv(length-len(data));
102 """GoodFET Client Library"""
113 symbols=SymbolTable();
115 def __init__(self, *args, **kargs):
117 def getConsole(self):
118 from GoodFETConsole import GoodFETConsole;
119 return GoodFETConsole(self);
120 def name2adr(self,name):
121 return self.symbols.get(name);
124 def serInit(self, port=None, timeout=2, attemptlimit=None):
125 """Open a serial port of some kind."""
129 port=os.environ.get("GOODFET");
130 if port=="bluetooth" or (port is not None and re.match("..:..:..:..:..:..",port)):
131 self.btInit(port,timeout,attemptlimit);
133 self.pyserInit(port,timeout,attemptlimit);
134 def btInit(self, port, timeout, attemptlimit):
135 """Open a bluetooth port.""";
136 #self.verbose=True; #For debugging BT.
137 self.serialport=GoodFETbtser(port);
139 def pyserInit(self, port, timeout, attemptlimit):
140 """Open the serial port"""
141 # Make timeout None to wait forever, 0 for non-blocking mode.
144 if os.name=='nt' and sys.version.find('64 bit')!=-1:
145 print "WARNING: PySerial requires a 32-bit Python build in Windows.";
147 if port is None and os.environ.get("GOODFET")!=None:
148 glob_list = glob.glob(os.environ.get("GOODFET"));
149 if len(glob_list) > 0:
152 port = os.environ.get("GOODFET");
154 glob_list = glob.glob("/dev/tty.usbserial*");
155 if len(glob_list) > 0:
158 glob_list = glob.glob("/dev/ttyUSB*");
159 if len(glob_list) > 0:
162 glob_list = glob.glob("/dev/ttyU0");
163 if len(glob_list) > 0:
165 if port is None and os.name=='nt':
166 from scanwin32 import winScan;
168 for order,comport,desc,hwid in sorted(scan.comports()):
170 if hwid.index('FTDI')==0:
172 #print "Using FTDI port %s" % port
178 if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
179 baud=19200; #Slower, for now.
180 self.serialport = serial.Serial(
184 parity = serial.PARITY_NONE,
192 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
193 #while self.data!="http://goodfet.sf.net/":
194 #print "'%s'!=\n'%s'" % (self.data,"http://goodfet.sf.net/");
195 if attemptlimit is not None and attempts >= attemptlimit:
199 self.serialport.flushInput()
200 self.serialport.flushOutput()
202 #TelosB reset, prefer software to I2C SPST Switch.
203 if(os.environ.get("platform")=='telosb' or os.environ.get("board")=='telosb'):
204 #print "TelosB Reset";
207 #Explicitly set RTS and DTR to halt board.
208 self.serialport.setRTS(1);
209 self.serialport.setDTR(1);
210 #Drop DTR, which is !RST, low to begin the app.
211 self.serialport.setDTR(0);
213 #self.serialport.write(chr(0x80));
214 #self.serialport.write(chr(0x80));
215 #self.serialport.write(chr(0x80));
216 #self.serialport.write(chr(0x80));
219 #self.serialport.flushInput()
220 #self.serialport.flushOutput()
223 self.readcmd(); #Read the first command.
224 #print "Got %02x,%02x:'%s'" % (self.app,self.verb,self.data);
225 #Here we have a connection, but maybe not a good one.
226 #print "We have a connection."
228 olds=self.infostring();
229 clocking=self.monitorclocking();
230 for foo in range(1,30):
231 if not self.monitorecho():
233 print "Comm error on %i try, resyncing out of %s." % (foo,
237 if self.verbose: print "Connected after %02i attempts." % attempts;
238 self.mon_connected();
239 self.serialport.setTimeout(12);
241 self.serialport.close();
242 def telosSetSCL(self, level):
243 self.serialport.setRTS(not level)
244 def telosSetSDA(self, level):
245 self.serialport.setDTR(not level)
247 def telosI2CStart(self):
252 def telosI2CStop(self):
257 def telosI2CWriteBit(self, bit):
259 self.telosSetSDA(bit)
265 def telosI2CWriteByte(self, byte):
266 self.telosI2CWriteBit( byte & 0x80 );
267 self.telosI2CWriteBit( byte & 0x40 );
268 self.telosI2CWriteBit( byte & 0x20 );
269 self.telosI2CWriteBit( byte & 0x10 );
270 self.telosI2CWriteBit( byte & 0x08 );
271 self.telosI2CWriteBit( byte & 0x04 );
272 self.telosI2CWriteBit( byte & 0x02 );
273 self.telosI2CWriteBit( byte & 0x01 );
274 self.telosI2CWriteBit( 0 ); # "acknowledge"
276 def telosI2CWriteCmd(self, addr, cmdbyte):
278 self.telosI2CWriteByte( 0x90 | (addr << 1) )
279 self.telosI2CWriteByte( cmdbyte )
282 def telosBReset(self,invokeBSL=0):
283 # "BSL entry sequence at dedicated JTAG pins"
284 # rst !s0: 0 0 0 0 1 1
285 # tck !s1: 1 0 1 0 0 1
288 # "BSL entry sequence at shared JTAG pins"
289 # rst !s0: 0 0 0 0 1 1
290 # tck !s1: 0 1 0 1 1 0
294 self.telosI2CWriteCmd(0,1)
295 self.telosI2CWriteCmd(0,3)
296 self.telosI2CWriteCmd(0,1)
297 self.telosI2CWriteCmd(0,3)
298 self.telosI2CWriteCmd(0,2)
299 self.telosI2CWriteCmd(0,0)
301 self.telosI2CWriteCmd(0,3)
302 self.telosI2CWriteCmd(0,2)
304 # This line was not defined inside the else: block, not sure where it
306 self.telosI2CWriteCmd(0,0)
307 time.sleep(0.250) #give MSP430's oscillator time to stabilize
308 self.serialport.flushInput() #clear buffers
311 def getbuffer(self,size=0x1c00):
312 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
313 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
314 def writecmd(self, app, verb, count=0, data=[]):
315 """Write a command and some data to the GoodFET."""
316 self.serialport.write(chr(app));
317 self.serialport.write(chr(verb));
320 # count=len(data); #Initial count ignored.
322 #print "TX %02x %02x %04x" % (app,verb,count);
324 #little endian 16-bit length
325 self.serialport.write(chr(count&0xFF));
326 self.serialport.write(chr(count>>8));
329 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
331 #print "count=%02x, len(data)=%04x" % (count,len(data));
334 if(isinstance(data,list)):
335 for i in range(0,count):
336 #print "Converting %02x at %i" % (data[i],i)
337 data[i]=chr(data[i]);
339 outstr=''.join(data);
340 self.serialport.write(outstr);
341 if not self.besilent:
342 return self.readcmd()
347 """Read a reply from the GoodFET."""
348 while 1:#self.serialport.inWaiting(): # Loop while input data is available
351 self.app=ord(self.serialport.read(1));
352 #print "APP=%02x" % self.app;
353 self.verb=ord(self.serialport.read(1));
355 #Fixes an obscure bug in the TelosB.
357 while self.verb==0x00:
358 self.verb=ord(self.serialport.read(1));
360 #print "VERB=%02x" % self.verb;
362 ord(self.serialport.read(1))
363 +(ord(self.serialport.read(1))<<8)
367 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
369 #Debugging string; print, but wait.
372 print "# DEBUG %s" % self.serialport.read(self.count)
373 elif self.verb==0xFE:
374 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
375 elif self.verb==0xFD:
376 #Do nothing, just wait so there's no timeout.
381 self.data=self.serialport.read(self.count);
385 print "Warning: waiting for serial read timed out (most likely).";
386 #print "This shouldn't happen after syncing. Exiting for safety.";
390 def glitchApp(self,app):
391 """Glitch into a device by its application."""
392 self.data=[app&0xff];
393 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
394 #return ord(self.data[0]);
395 def glitchVerb(self,app,verb,data):
396 """Glitch during a transaction."""
397 if data==None: data=[];
398 self.data=[app&0xff, verb&0xFF]+data;
399 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
400 #return ord(self.data[0]);
401 def glitchstart(self):
402 """Glitch into the AVR application."""
403 self.glitchVerb(self.APP,0x20,None);
404 def glitchstarttime(self):
405 """Measure the timer of the START verb."""
406 return self.glitchTime(self.APP,0x20,None);
407 def glitchTime(self,app,verb,data):
408 """Time the execution of a verb."""
409 if data==None: data=[];
410 self.data=[app&0xff, verb&0xFF]+data;
411 print "Timing app %02x verb %02x." % (app,verb);
412 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
413 time=ord(self.data[0])+(ord(self.data[1])<<8);
414 print "Timed to be %i." % time;
416 def glitchVoltages(self,low=0x0880, high=0x0fff):
417 """Set glitching voltages. (0x0fff is max.)"""
418 self.data=[low&0xff, (low>>8)&0xff,
419 high&0xff, (high>>8)&0xff];
420 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
421 #return ord(self.data[0]);
422 def glitchRate(self,count=0x0800):
423 """Set glitching count period."""
424 self.data=[count&0xff, (count>>8)&0xff];
425 self.writecmd(self.GLITCHAPP,0x91,2,
427 #return ord(self.data[0]);
431 def silent(self,s=0):
432 """Transmissions halted when 1."""
434 print "besilent is %i" % self.besilent;
435 self.writecmd(0,0xB0,1,[s]);
437 def mon_connected(self):
438 """Announce to the monitor that the connection is good."""
440 self.writecmd(0,0xB1,0,[]);
442 """Write a byte to P5OUT."""
443 self.writecmd(0,0xA1,1,[byte]);
445 """Write a byte to P5DIR."""
446 self.writecmd(0,0xA0,1,[byte]);
448 """Call to an address."""
449 self.writecmd(0,0x30,2,
450 [adr&0xFF,(adr>>8)&0xFF]);
451 def execute(self,code):
452 """Execute supplied code."""
453 self.writecmd(0,0x31,2,#len(code),
455 def MONpeek8(self,address):
456 """Read a byte of memory from the monitor."""
457 self.data=[address&0xff,address>>8];
458 self.writecmd(0,0x02,2,self.data);
460 return ord(self.data[0]);
461 def MONpeek16(self,address):
462 """Read a word of memory from the monitor."""
463 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
464 def peek(self,address):
465 """Read a word of memory from the monitor."""
466 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
467 def eeprompeek(self,address):
468 """Read a word of memory from the monitor."""
469 print "EEPROM peeking not supported for the monitor.";
470 #return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
471 def peekbysym(self,name):
472 """Read a value by its symbol name."""
473 #TODO include memory in symbol.
474 reg=self.symbols.get(name);
475 return self.peek8(reg,"data");
476 def pokebysym(self,name,val):
477 """Write a value by its symbol name."""
478 #TODO include memory in symbol.
479 reg=self.symbols.get(name);
480 return self.pokebyte(reg,val);
481 def pokebyte(self,address,value,memory="vn"):
482 """Set a byte of memory by the monitor."""
483 self.data=[address&0xff,address>>8,value];
484 self.writecmd(0,0x03,3,self.data);
485 return ord(self.data[0]);
486 def poke16(self,address,value):
487 """Set a word of memory by the monitor."""
488 self.pokebyte(address,value&0xFF);
489 self.pokebyte(address,(value>>8)&0xFF);
491 def setsecret(self,value):
492 """Set a secret word for later retreival. Used by glitcher."""
493 #self.eeprompoke(0,value);
494 #self.eeprompoke(1,value);
495 print "Secret setting is not yet suppored for this target.";
499 """Get a secret word. Used by glitcher."""
501 print "Secret getting is not yet suppored for this target.";
505 def dumpmem(self,begin,end):
508 print "%04x %04x" % (i, self.MONpeek16(i));
510 def monitor_ram_pattern(self):
511 """Overwrite all of RAM with 0xBEEF."""
512 self.writecmd(0,0x90,0,self.data);
514 def monitor_ram_depth(self):
515 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
516 self.writecmd(0,0x91,0,self.data);
517 return ord(self.data[0])+(ord(self.data[1])<<8);
526 def setBaud(self,baud):
527 """Change the baud rate. TODO fix this."""
528 rates=self.baudrates;
530 print "Changing FET baud."
531 self.serialport.write(chr(0x00));
532 self.serialport.write(chr(0x80));
533 self.serialport.write(chr(1));
534 self.serialport.write(chr(baud));
536 print "Changed host baud."
537 self.serialport.setBaudrate(rates[baud]);
539 self.serialport.flushInput()
540 self.serialport.flushOutput()
542 print "Baud is now %i." % rates[baud];
545 return ord(self.serialport.read(1));
547 for r in self.baudrates:
548 print "\nTrying %i" % r;
549 self.serialport.setBaudrate(r);
551 self.serialport.flushInput()
552 self.serialport.flushOutput()
554 for i in range(1,10):
557 print "Read %02x %02x %02x %02x" % (
558 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
559 def monitortest(self):
560 """Self-test several functions through the monitor."""
561 print "Performing monitor self-test.";
562 self.monitorclocking();
563 for f in range(0,3000):
564 a=self.MONpeek16(0x0c00);
565 b=self.MONpeek16(0x0c02);
566 if a!=0x0c04 and a!=0x0c06:
567 print "ERROR Fetched %04x, %04x" % (a,b);
568 self.pokebyte(0x0021,0); #Drop LED
569 if self.MONpeek8(0x0021)!=0:
570 print "ERROR, P1OUT not cleared.";
571 self.pokebyte(0x0021,1); #Light LED
572 if not self.monitorecho():
573 print "Echo test failed.";
574 print "Self-test complete.";
575 self.monitorclocking();
576 def monitorecho(self):
577 data="The quick brown fox jumped over the lazy dog.";
578 self.writecmd(self.MONITORAPP,0x81,len(data),data);
580 print "Comm error recognized by monitorecho(), got:\n%s" % self.data;
584 def monitor_info(self):
585 print "GoodFET with %s MCU" % self.infostring();
586 print "Clocked at %s" % self.monitorclocking();
589 def monitor_list_apps(self, full=False):
591 old_value = self.besilent
592 self.besilent = True # turn off automatic call to readcmd
593 self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
594 self.besilent = old_value
596 # read the build date string
598 print "Build Date: %s" % self.data
599 print "Firmware apps:"
607 def monitorclocking(self):
608 """Return the 16-bit clocking value."""
609 return "0x%04x" % self.monitorgetclock();
611 def monitorsetclock(self,clock):
612 """Set the clocking value."""
613 self.MONpoke16(0x56, clock);
614 def monitorgetclock(self):
615 """Get the clocking value."""
616 if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
618 #Check for MSP430 before peeking this.
619 return self.MONpeek16(0x56);
620 # The following functions ought to be implemented in
623 def infostring(self):
624 if(os.environ.get("platform")=='arduino' or os.environ.get("board")=='arduino'):
627 a=self.MONpeek8(0xff0);
628 b=self.MONpeek8(0xff1);
629 return "%02x%02x" % (a,b);
631 print "Locking Unsupported.";
633 print "Erasure Unsupported.";
639 print "Unimplemented.";
642 print "Unimplemented.";
645 print "Unimplemented.";
648 print "Unimplemented.";
651 print "Unimplemented.";
653 def flash(self,file):
654 """Flash an intel hex file to code memory."""
655 print "Flash not implemented.";
656 def dump(self,file,start=0,stop=0xffff):
657 """Dump an intel hex file from code memory."""
658 print "Dump not implemented.";
659 def peek32(self,address, memory="vn"):
661 return (self.peek16(address,memory)+
662 (self.peek16(address+2,memory)<<16));
663 def peek16(self,address, memory="vn"):
664 """Peek 16 bits of memory."""
665 return (self.peek8(address,memory)+
666 (self.peek8(address+1,memory)<<8));
667 def peek8(self,address, memory="vn"):
668 """Peek a byte of memory."""
669 return self.MONpeek8(address); #monitor
670 def peekblock(self,address,length,memory="vn"):
671 """Return a block of data."""
672 data=range(0,length);
673 for foo in range(0,length):
674 data[foo]=self.peek8(address+foo,memory);
676 def pokeblock(self,address,bytes,memory="vn"):
677 """Poke a block of a data into memory at an address."""
679 self.pokebyte(address,foo,memory);
682 def loadsymbols(self):
683 """Load symbols from a file."""