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 if name=='FireFly-A6BD':
63 print "Please set $GOODFET to the address of your device.";
65 print "Identified GoodFET at %s" % btaddr;
67 # Manually use the portnumber.
70 print "Connecting to %s on port %i." % (btaddr, port);
71 sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
73 sock.connect((btaddr,port));
74 sock.settimeout(10); #IMPORTANT Must be patient.
76 ##This is what we'd do for a normal reset.
78 #while not str.endswith("goodfet.sf.net/"):
82 # Instead, just return and hope for the best.
91 def read(self,length):
94 while len(data)<length:
95 data=data+self.sock.recv(length-len(data));
98 """GoodFET Client Library"""
109 symbols=SymbolTable();
111 def __init__(self, *args, **kargs):
113 def getConsole(self):
114 from GoodFETConsole import GoodFETConsole;
115 return GoodFETConsole(self);
116 def name2adr(self,name):
117 return self.symbols.get(name);
120 def serInit(self, port=None, timeout=2, attemptlimit=None):
121 """Open a serial port of some kind."""
125 port=os.environ.get("GOODFET");
126 if port=="bluetooth" or (port is not None and re.match("..:..:..:..:..:..",port)):
127 self.btInit(port,timeout,attemptlimit);
129 self.pyserInit(port,timeout,attemptlimit);
130 def btInit(self, port, timeout, attemptlimit):
131 """Open a bluetooth port.""";
132 #self.verbose=True; #For debugging BT.
133 self.serialport=GoodFETbtser(port);
135 def pyserInit(self, port, timeout, attemptlimit):
136 """Open the serial port"""
137 # Make timeout None to wait forever, 0 for non-blocking mode.
140 if os.name=='nt' and sys.version.find('64 bit')!=-1:
141 print "WARNING: PySerial requires a 32-bit Python build in Windows.";
143 if port is None and os.environ.get("GOODFET")!=None:
144 glob_list = glob.glob(os.environ.get("GOODFET"));
145 if len(glob_list) > 0:
148 port = os.environ.get("GOODFET");
150 glob_list = glob.glob("/dev/tty.usbserial*");
151 if len(glob_list) > 0:
154 glob_list = glob.glob("/dev/ttyUSB*");
155 if len(glob_list) > 0:
158 glob_list = glob.glob("/dev/ttyU0");
159 if len(glob_list) > 0:
161 if port is None and os.name=='nt':
162 from scanwin32 import winScan;
164 for order,comport,desc,hwid in sorted(scan.comports()):
166 if hwid.index('FTDI')==0:
168 #print "Using FTDI port %s" % port
174 if(os.environ.get("platform")=='arduino'):
175 baud=19200; #Slower, for now.
176 self.serialport = serial.Serial(
180 parity = serial.PARITY_NONE,
188 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
189 #while self.data!="http://goodfet.sf.net/":
190 #print "'%s'!=\n'%s'" % (self.data,"http://goodfet.sf.net/");
191 if attemptlimit is not None and attempts >= attemptlimit:
195 self.serialport.flushInput()
196 self.serialport.flushOutput()
198 #TelosB reset, prefer software to I2C SPST Switch.
199 if(os.environ.get("platform")=='telosb'):
200 #print "TelosB Reset";
203 #Explicitly set RTS and DTR to halt board.
204 self.serialport.setRTS(1);
205 self.serialport.setDTR(1);
206 #Drop DTR, which is !RST, low to begin the app.
207 self.serialport.setDTR(0);
209 #self.serialport.write(chr(0x80));
210 #self.serialport.write(chr(0x80));
211 #self.serialport.write(chr(0x80));
212 #self.serialport.write(chr(0x80));
215 #self.serialport.flushInput()
216 #self.serialport.flushOutput()
219 self.readcmd(); #Read the first command.
220 #print "Got %02x,%02x:'%s'" % (self.app,self.verb,self.data);
221 #Here we have a connection, but maybe not a good one.
222 #print "We have a connection."
224 olds=self.infostring();
225 clocking=self.monitorclocking();
226 #if(os.environ.get("platform")!='arduino'):
227 for foo in range(1,30):
228 if not self.monitorecho():
230 print "Comm error on %i try, resyncing out of %s." % (foo,
234 if self.verbose: print "Connected after %02i attempts." % attempts;
235 self.mon_connected();
236 self.serialport.setTimeout(12);
238 self.serialport.close();
239 def telosSetSCL(self, level):
240 self.serialport.setRTS(not level)
241 def telosSetSDA(self, level):
242 self.serialport.setDTR(not level)
244 def telosI2CStart(self):
249 def telosI2CStop(self):
254 def telosI2CWriteBit(self, bit):
256 self.telosSetSDA(bit)
262 def telosI2CWriteByte(self, byte):
263 self.telosI2CWriteBit( byte & 0x80 );
264 self.telosI2CWriteBit( byte & 0x40 );
265 self.telosI2CWriteBit( byte & 0x20 );
266 self.telosI2CWriteBit( byte & 0x10 );
267 self.telosI2CWriteBit( byte & 0x08 );
268 self.telosI2CWriteBit( byte & 0x04 );
269 self.telosI2CWriteBit( byte & 0x02 );
270 self.telosI2CWriteBit( byte & 0x01 );
271 self.telosI2CWriteBit( 0 ); # "acknowledge"
273 def telosI2CWriteCmd(self, addr, cmdbyte):
275 self.telosI2CWriteByte( 0x90 | (addr << 1) )
276 self.telosI2CWriteByte( cmdbyte )
279 def telosBReset(self,invokeBSL=0):
280 # "BSL entry sequence at dedicated JTAG pins"
281 # rst !s0: 0 0 0 0 1 1
282 # tck !s1: 1 0 1 0 0 1
285 # "BSL entry sequence at shared JTAG pins"
286 # rst !s0: 0 0 0 0 1 1
287 # tck !s1: 0 1 0 1 1 0
291 self.telosI2CWriteCmd(0,1)
292 self.telosI2CWriteCmd(0,3)
293 self.telosI2CWriteCmd(0,1)
294 self.telosI2CWriteCmd(0,3)
295 self.telosI2CWriteCmd(0,2)
296 self.telosI2CWriteCmd(0,0)
298 self.telosI2CWriteCmd(0,3)
299 self.telosI2CWriteCmd(0,2)
301 # This line was not defined inside the else: block, not sure where it
303 self.telosI2CWriteCmd(0,0)
304 time.sleep(0.250) #give MSP430's oscillator time to stabilize
305 self.serialport.flushInput() #clear buffers
308 def getbuffer(self,size=0x1c00):
309 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
310 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
311 def writecmd(self, app, verb, count=0, data=[]):
312 """Write a command and some data to the GoodFET."""
313 self.serialport.write(chr(app));
314 self.serialport.write(chr(verb));
317 # count=len(data); #Initial count ignored.
319 #print "TX %02x %02x %04x" % (app,verb,count);
321 #little endian 16-bit length
322 self.serialport.write(chr(count&0xFF));
323 self.serialport.write(chr(count>>8));
326 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
328 #print "count=%02x, len(data)=%04x" % (count,len(data));
331 if(isinstance(data,list)):
332 for i in range(0,count):
333 #print "Converting %02x at %i" % (data[i],i)
334 data[i]=chr(data[i]);
336 outstr=''.join(data);
337 self.serialport.write(outstr);
338 if not self.besilent:
339 return self.readcmd()
344 """Read a reply from the GoodFET."""
345 while 1:#self.serialport.inWaiting(): # Loop while input data is available
348 self.app=ord(self.serialport.read(1));
349 #print "APP=%02x" % self.app;
350 self.verb=ord(self.serialport.read(1));
352 #Fixes an obscure bug in the TelosB.
354 while self.verb==0x00:
355 self.verb=ord(self.serialport.read(1));
357 #print "VERB=%02x" % self.verb;
359 ord(self.serialport.read(1))
360 +(ord(self.serialport.read(1))<<8)
364 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
366 #Debugging string; print, but wait.
369 print "# DEBUG %s" % self.serialport.read(self.count)
370 elif self.verb==0xFE:
371 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
372 elif self.verb==0xFD:
373 #Do nothing, just wait so there's no timeout.
378 self.data=self.serialport.read(self.count);
382 print "Warning: waiting for serial read timed out (most likely).";
383 #print "This shouldn't happen after syncing. Exiting for safety.";
387 def glitchApp(self,app):
388 """Glitch into a device by its application."""
389 self.data=[app&0xff];
390 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
391 #return ord(self.data[0]);
392 def glitchVerb(self,app,verb,data):
393 """Glitch during a transaction."""
394 if data==None: data=[];
395 self.data=[app&0xff, verb&0xFF]+data;
396 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
397 #return ord(self.data[0]);
398 def glitchstart(self):
399 """Glitch into the AVR application."""
400 self.glitchVerb(self.APP,0x20,None);
401 def glitchstarttime(self):
402 """Measure the timer of the START verb."""
403 return self.glitchTime(self.APP,0x20,None);
404 def glitchTime(self,app,verb,data):
405 """Time the execution of a verb."""
406 if data==None: data=[];
407 self.data=[app&0xff, verb&0xFF]+data;
408 print "Timing app %02x verb %02x." % (app,verb);
409 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
410 time=ord(self.data[0])+(ord(self.data[1])<<8);
411 print "Timed to be %i." % time;
413 def glitchVoltages(self,low=0x0880, high=0x0fff):
414 """Set glitching voltages. (0x0fff is max.)"""
415 self.data=[low&0xff, (low>>8)&0xff,
416 high&0xff, (high>>8)&0xff];
417 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
418 #return ord(self.data[0]);
419 def glitchRate(self,count=0x0800):
420 """Set glitching count period."""
421 self.data=[count&0xff, (count>>8)&0xff];
422 self.writecmd(self.GLITCHAPP,0x91,2,
424 #return ord(self.data[0]);
428 def silent(self,s=0):
429 """Transmissions halted when 1."""
431 print "besilent is %i" % self.besilent;
432 self.writecmd(0,0xB0,1,[s]);
434 def mon_connected(self):
435 """Announce to the monitor that the connection is good."""
437 self.writecmd(0,0xB1,0,[]);
439 """Write a byte to P5OUT."""
440 self.writecmd(0,0xA1,1,[byte]);
442 """Write a byte to P5DIR."""
443 self.writecmd(0,0xA0,1,[byte]);
445 """Call to an address."""
446 self.writecmd(0,0x30,2,
447 [adr&0xFF,(adr>>8)&0xFF]);
448 def execute(self,code):
449 """Execute supplied code."""
450 self.writecmd(0,0x31,2,#len(code),
452 def MONpeek8(self,address):
453 """Read a byte of memory from the monitor."""
454 self.data=[address&0xff,address>>8];
455 self.writecmd(0,0x02,2,self.data);
457 return ord(self.data[0]);
458 def MONpeek16(self,address):
459 """Read a word of memory from the monitor."""
460 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
461 def peek(self,address):
462 """Read a word of memory from the monitor."""
463 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
464 def eeprompeek(self,address):
465 """Read a word of memory from the monitor."""
466 print "EEPROM peeking not supported for the monitor.";
467 #return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
468 def peekbysym(self,name):
469 """Read a value by its symbol name."""
470 #TODO include memory in symbol.
471 reg=self.symbols.get(name);
472 return self.peek8(reg,"data");
473 def pokebysym(self,name,val):
474 """Write a value by its symbol name."""
475 #TODO include memory in symbol.
476 reg=self.symbols.get(name);
477 return self.pokebyte(reg,val);
478 def pokebyte(self,address,value,memory="vn"):
479 """Set a byte of memory by the monitor."""
480 self.data=[address&0xff,address>>8,value];
481 self.writecmd(0,0x03,3,self.data);
482 return ord(self.data[0]);
483 def poke16(self,address,value):
484 """Set a word of memory by the monitor."""
485 self.pokebyte(address,value&0xFF);
486 self.pokebyte(address,(value>>8)&0xFF);
488 def setsecret(self,value):
489 """Set a secret word for later retreival. Used by glitcher."""
490 #self.eeprompoke(0,value);
491 #self.eeprompoke(1,value);
492 print "Secret setting is not yet suppored for this target.";
496 """Get a secret word. Used by glitcher."""
498 print "Secret getting is not yet suppored for this target.";
502 def dumpmem(self,begin,end):
505 print "%04x %04x" % (i, self.MONpeek16(i));
507 def monitor_ram_pattern(self):
508 """Overwrite all of RAM with 0xBEEF."""
509 self.writecmd(0,0x90,0,self.data);
511 def monitor_ram_depth(self):
512 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
513 self.writecmd(0,0x91,0,self.data);
514 return ord(self.data[0])+(ord(self.data[1])<<8);
523 def setBaud(self,baud):
524 """Change the baud rate. TODO fix this."""
525 rates=self.baudrates;
527 print "Changing FET baud."
528 self.serialport.write(chr(0x00));
529 self.serialport.write(chr(0x80));
530 self.serialport.write(chr(1));
531 self.serialport.write(chr(baud));
533 print "Changed host baud."
534 self.serialport.setBaudrate(rates[baud]);
536 self.serialport.flushInput()
537 self.serialport.flushOutput()
539 print "Baud is now %i." % rates[baud];
542 return ord(self.serialport.read(1));
544 for r in self.baudrates:
545 print "\nTrying %i" % r;
546 self.serialport.setBaudrate(r);
548 self.serialport.flushInput()
549 self.serialport.flushOutput()
551 for i in range(1,10):
554 print "Read %02x %02x %02x %02x" % (
555 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
556 def monitortest(self):
557 """Self-test several functions through the monitor."""
558 print "Performing monitor self-test.";
559 self.monitorclocking();
560 for f in range(0,3000):
561 a=self.MONpeek16(0x0c00);
562 b=self.MONpeek16(0x0c02);
563 if a!=0x0c04 and a!=0x0c06:
564 print "ERROR Fetched %04x, %04x" % (a,b);
565 self.pokebyte(0x0021,0); #Drop LED
566 if self.MONpeek8(0x0021)!=0:
567 print "ERROR, P1OUT not cleared.";
568 self.pokebyte(0x0021,1); #Light LED
569 if not self.monitorecho():
570 print "Echo test failed.";
571 print "Self-test complete.";
572 self.monitorclocking();
573 def monitorecho(self):
574 data="The quick brown fox jumped over the lazy dog.";
575 self.writecmd(self.MONITORAPP,0x81,len(data),data);
577 print "Comm error recognized by monitorecho(), got:\n%s" % self.data;
581 def monitor_info(self):
582 print "GoodFET with %s MCU" % self.infostring();
583 print "Clocked at %s" % self.monitorclocking();
586 def monitor_list_apps(self, full=False):
588 old_value = self.besilent
589 self.besilent = True # turn off automatic call to readcmd
590 self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
591 self.besilent = old_value
593 # read the build date string
595 print "Build Date: %s" % self.data
596 print "Firmware apps:"
604 def monitorclocking(self):
605 """Return the 16-bit clocking value."""
606 return "0x%04x" % self.monitorgetclock();
608 def monitorsetclock(self,clock):
609 """Set the clocking value."""
610 self.MONpoke16(0x56, clock);
611 def monitorgetclock(self):
612 """Get the clocking value."""
613 if(os.environ.get("platform")=='arduino'):
615 #Check for MSP430 before peeking this.
616 return self.MONpeek16(0x56);
617 # The following functions ought to be implemented in
620 def infostring(self):
621 if(os.environ.get("platform")=='arduino'):
624 a=self.MONpeek8(0xff0);
625 b=self.MONpeek8(0xff1);
626 return "%02x%02x" % (a,b);
628 print "Locking Unsupported.";
630 print "Erasure Unsupported.";
636 print "Unimplemented.";
639 print "Unimplemented.";
642 print "Unimplemented.";
645 print "Unimplemented.";
648 print "Unimplemented.";
650 def flash(self,file):
651 """Flash an intel hex file to code memory."""
652 print "Flash not implemented.";
653 def dump(self,file,start=0,stop=0xffff):
654 """Dump an intel hex file from code memory."""
655 print "Dump not implemented.";
656 def peek32(self,address, memory="vn"):
658 return (self.peek16(address,memory)+
659 (self.peek16(address+2,memory)<<16));
660 def peek16(self,address, memory="vn"):
661 """Peek 16 bits of memory."""
662 return (self.peek8(address,memory)+
663 (self.peek8(address+1,memory)<<8));
664 def peek8(self,address, memory="vn"):
665 """Peek a byte of memory."""
666 return self.MONpeek8(address); #monitor
667 def peekblock(self,address,length,memory="vn"):
668 """Return a block of data."""
669 data=range(0,length);
670 for foo in range(0,length):
671 data[foo]=self.peek8(address+foo,memory);
673 def pokeblock(self,address,bytes,memory="vn"):
674 """Poke a block of a data into memory at an address."""
676 self.pokebyte(address,foo,memory);
679 def loadsymbols(self):
680 """Load symbols from a file."""