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 while 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 "Identified GoodFET at %s" % btaddr;
65 # BlueFET doesn't run the Service Discovery Protocol.
66 # Instead we manually use the portnumber.
69 print "Connecting to %s on port %i." % (btaddr, port);
70 sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
72 sock.connect((btaddr,port));
73 sock.settimeout(10); #IMPORTANT Must be patient.
75 #Once connected, we need to get synced.
76 #This might require a firmware patch.
78 while str!="http://goodfet.sf.net/":
83 return self.sock.send(msg);
86 return self.sock.recv(len);
88 """GoodFET Client Library"""
99 symbols=SymbolTable();
101 def __init__(self, *args, **kargs):
103 def getConsole(self):
104 from GoodFETConsole import GoodFETConsole;
105 return GoodFETConsole(self);
106 def name2adr(self,name):
107 return self.symbols.get(name);
110 def serInit(self, port=None, timeout=2, attemptlimit=None):
111 """Open a serial port of some kind."""
113 if port=="bluetooth" or os.environ.get("GOODFET")=="bluetooth":
114 self.btInit(port,timeout,attemptlimit);
116 self.pyserInit(port,timeout,attemptlimit);
117 def btInit(self, port, timeout, attemptlimit):
118 """Open a bluetooth port.""";
120 self.serialport=GoodFETbtser(port);
122 def pyserInit(self, port, timeout, attemptlimit):
123 """Open the serial port"""
124 # Make timeout None to wait forever, 0 for non-blocking mode.
127 if os.name=='nt' and sys.version.find('64 bit')!=-1:
128 print "WARNING: PySerial requires a 32-bit Python build in Windows.";
130 if port is None and os.environ.get("GOODFET")!=None:
131 glob_list = glob.glob(os.environ.get("GOODFET"));
132 if len(glob_list) > 0:
135 port = os.environ.get("GOODFET");
137 glob_list = glob.glob("/dev/tty.usbserial*");
138 if len(glob_list) > 0:
141 glob_list = glob.glob("/dev/ttyUSB*");
142 if len(glob_list) > 0:
145 glob_list = glob.glob("/dev/ttyU0");
146 if len(glob_list) > 0:
148 if port is None and os.name=='nt':
149 from scanwin32 import winScan;
151 for order,comport,desc,hwid in sorted(scan.comports()):
153 if hwid.index('FTDI')==0:
155 #print "Using FTDI port %s" % port
161 if(os.environ.get("platform")=='arduino'):
162 baud=19200; #Slower, for now.
163 self.serialport = serial.Serial(
167 parity = serial.PARITY_NONE,
175 while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
176 #while self.data!="http://goodfet.sf.net/":
177 #print "'%s'!=\n'%s'" % (self.data,"http://goodfet.sf.net/");
178 if attemptlimit is not None and attempts >= attemptlimit:
182 self.serialport.flushInput()
183 self.serialport.flushOutput()
185 #TelosB reset, prefer software to I2C SPST Switch.
186 if(os.environ.get("platform")=='telosb'):
187 #print "TelosB Reset";
190 #Explicitly set RTS and DTR to halt board.
191 self.serialport.setRTS(1);
192 self.serialport.setDTR(1);
193 #Drop DTR, which is !RST, low to begin the app.
194 self.serialport.setDTR(0);
196 #self.serialport.write(chr(0x80));
197 #self.serialport.write(chr(0x80));
198 #self.serialport.write(chr(0x80));
199 #self.serialport.write(chr(0x80));
202 #self.serialport.flushInput()
203 #self.serialport.flushOutput()
206 self.readcmd(); #Read the first command.
207 #print "Got %02x,%02x:'%s'" % (self.app,self.verb,self.data);
208 #Here we have a connection, but maybe not a good one.
209 #print "We have a connection."
211 olds=self.infostring();
212 clocking=self.monitorclocking();
213 #if(os.environ.get("platform")!='arduino'):
214 for foo in range(1,30):
215 if not self.monitorecho():
217 print "Comm error on %i try, resyncing out of %s." % (foo,
221 if self.verbose: print "Connected after %02i attempts." % attempts;
222 self.mon_connected();
223 self.serialport.setTimeout(12);
225 self.serialport.close();
226 def telosSetSCL(self, level):
227 self.serialport.setRTS(not level)
228 def telosSetSDA(self, level):
229 self.serialport.setDTR(not level)
231 def telosI2CStart(self):
236 def telosI2CStop(self):
241 def telosI2CWriteBit(self, bit):
243 self.telosSetSDA(bit)
249 def telosI2CWriteByte(self, byte):
250 self.telosI2CWriteBit( byte & 0x80 );
251 self.telosI2CWriteBit( byte & 0x40 );
252 self.telosI2CWriteBit( byte & 0x20 );
253 self.telosI2CWriteBit( byte & 0x10 );
254 self.telosI2CWriteBit( byte & 0x08 );
255 self.telosI2CWriteBit( byte & 0x04 );
256 self.telosI2CWriteBit( byte & 0x02 );
257 self.telosI2CWriteBit( byte & 0x01 );
258 self.telosI2CWriteBit( 0 ); # "acknowledge"
260 def telosI2CWriteCmd(self, addr, cmdbyte):
262 self.telosI2CWriteByte( 0x90 | (addr << 1) )
263 self.telosI2CWriteByte( cmdbyte )
266 def telosBReset(self,invokeBSL=0):
267 # "BSL entry sequence at dedicated JTAG pins"
268 # rst !s0: 0 0 0 0 1 1
269 # tck !s1: 1 0 1 0 0 1
272 # "BSL entry sequence at shared JTAG pins"
273 # rst !s0: 0 0 0 0 1 1
274 # tck !s1: 0 1 0 1 1 0
278 self.telosI2CWriteCmd(0,1)
279 self.telosI2CWriteCmd(0,3)
280 self.telosI2CWriteCmd(0,1)
281 self.telosI2CWriteCmd(0,3)
282 self.telosI2CWriteCmd(0,2)
283 self.telosI2CWriteCmd(0,0)
285 self.telosI2CWriteCmd(0,3)
286 self.telosI2CWriteCmd(0,2)
288 # This line was not defined inside the else: block, not sure where it
290 self.telosI2CWriteCmd(0,0)
291 time.sleep(0.250) #give MSP430's oscillator time to stabilize
292 self.serialport.flushInput() #clear buffers
295 def getbuffer(self,size=0x1c00):
296 writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
297 print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
298 def writecmd(self, app, verb, count=0, data=[]):
299 """Write a command and some data to the GoodFET."""
300 self.serialport.write(chr(app));
301 self.serialport.write(chr(verb));
304 # count=len(data); #Initial count ignored.
306 #print "TX %02x %02x %04x" % (app,verb,count);
308 #little endian 16-bit length
309 self.serialport.write(chr(count&0xFF));
310 self.serialport.write(chr(count>>8));
313 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
315 #print "count=%02x, len(data)=%04x" % (count,len(data));
318 if(isinstance(data,list)):
319 for i in range(0,count):
320 #print "Converting %02x at %i" % (data[i],i)
321 data[i]=chr(data[i]);
323 outstr=''.join(data);
324 self.serialport.write(outstr);
325 if not self.besilent:
326 return self.readcmd()
331 """Read a reply from the GoodFET."""
332 while 1:#self.serialport.inWaiting(): # Loop while input data is available
335 self.app=ord(self.serialport.read(1));
336 #print "APP=%02x" % self.app;
337 self.verb=ord(self.serialport.read(1));
339 #Fixes an obscure bug in the TelosB.
341 while self.verb==0x00:
342 self.verb=ord(self.serialport.read(1));
344 #print "VERB=%02x" % self.verb;
346 ord(self.serialport.read(1))
347 +(ord(self.serialport.read(1))<<8)
351 #print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
353 #Debugging string; print, but wait.
356 print "# DEBUG %s" % self.serialport.read(self.count)
357 elif self.verb==0xFE:
358 print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
359 elif self.verb==0xFD:
360 #Do nothing, just wait so there's no timeout.
365 self.data=self.serialport.read(self.count);
369 print "Warning: waiting for serial read timed out (most likely).";
370 #print "This shouldn't happen after syncing. Exiting for safety.";
374 def glitchApp(self,app):
375 """Glitch into a device by its application."""
376 self.data=[app&0xff];
377 self.writecmd(self.GLITCHAPP,0x80,1,self.data);
378 #return ord(self.data[0]);
379 def glitchVerb(self,app,verb,data):
380 """Glitch during a transaction."""
381 if data==None: data=[];
382 self.data=[app&0xff, verb&0xFF]+data;
383 self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
384 #return ord(self.data[0]);
385 def glitchstart(self):
386 """Glitch into the AVR application."""
387 self.glitchVerb(self.APP,0x20,None);
388 def glitchstarttime(self):
389 """Measure the timer of the START verb."""
390 return self.glitchTime(self.APP,0x20,None);
391 def glitchTime(self,app,verb,data):
392 """Time the execution of a verb."""
393 if data==None: data=[];
394 self.data=[app&0xff, verb&0xFF]+data;
395 print "Timing app %02x verb %02x." % (app,verb);
396 self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
397 time=ord(self.data[0])+(ord(self.data[1])<<8);
398 print "Timed to be %i." % time;
400 def glitchVoltages(self,low=0x0880, high=0x0fff):
401 """Set glitching voltages. (0x0fff is max.)"""
402 self.data=[low&0xff, (low>>8)&0xff,
403 high&0xff, (high>>8)&0xff];
404 self.writecmd(self.GLITCHAPP,0x90,4,self.data);
405 #return ord(self.data[0]);
406 def glitchRate(self,count=0x0800):
407 """Set glitching count period."""
408 self.data=[count&0xff, (count>>8)&0xff];
409 self.writecmd(self.GLITCHAPP,0x91,2,
411 #return ord(self.data[0]);
415 def silent(self,s=0):
416 """Transmissions halted when 1."""
418 print "besilent is %i" % self.besilent;
419 self.writecmd(0,0xB0,1,[s]);
421 def mon_connected(self):
422 """Announce to the monitor that the connection is good."""
424 self.writecmd(0,0xB1,0,[]);
426 """Write a byte to P5OUT."""
427 self.writecmd(0,0xA1,1,[byte]);
429 """Write a byte to P5DIR."""
430 self.writecmd(0,0xA0,1,[byte]);
432 """Call to an address."""
433 self.writecmd(0,0x30,2,
434 [adr&0xFF,(adr>>8)&0xFF]);
435 def execute(self,code):
436 """Execute supplied code."""
437 self.writecmd(0,0x31,2,#len(code),
439 def MONpeek8(self,address):
440 """Read a byte of memory from the monitor."""
441 self.data=[address&0xff,address>>8];
442 self.writecmd(0,0x02,2,self.data);
444 return ord(self.data[0]);
445 def MONpeek16(self,address):
446 """Read a word of memory from the monitor."""
447 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
448 def peek(self,address):
449 """Read a word of memory from the monitor."""
450 return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
451 def eeprompeek(self,address):
452 """Read a word of memory from the monitor."""
453 print "EEPROM peeking not supported for the monitor.";
454 #return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
455 def peekbysym(self,name):
456 """Read a value by its symbol name."""
457 #TODO include memory in symbol.
458 reg=self.symbols.get(name);
459 return self.peek8(reg,"data");
460 def pokebysym(self,name,val):
461 """Write a value by its symbol name."""
462 #TODO include memory in symbol.
463 reg=self.symbols.get(name);
464 return self.pokebyte(reg,val);
465 def pokebyte(self,address,value,memory="vn"):
466 """Set a byte of memory by the monitor."""
467 self.data=[address&0xff,address>>8,value];
468 self.writecmd(0,0x03,3,self.data);
469 return ord(self.data[0]);
470 def poke16(self,address,value):
471 """Set a word of memory by the monitor."""
472 self.pokebyte(address,value&0xFF);
473 self.pokebyte(address,(value>>8)&0xFF);
475 def setsecret(self,value):
476 """Set a secret word for later retreival. Used by glitcher."""
477 #self.eeprompoke(0,value);
478 #self.eeprompoke(1,value);
479 print "Secret setting is not yet suppored for this target.";
483 """Get a secret word. Used by glitcher."""
485 print "Secret getting is not yet suppored for this target.";
489 def dumpmem(self,begin,end):
492 print "%04x %04x" % (i, self.MONpeek16(i));
494 def monitor_ram_pattern(self):
495 """Overwrite all of RAM with 0xBEEF."""
496 self.writecmd(0,0x90,0,self.data);
498 def monitor_ram_depth(self):
499 """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
500 self.writecmd(0,0x91,0,self.data);
501 return ord(self.data[0])+(ord(self.data[1])<<8);
510 def setBaud(self,baud):
511 """Change the baud rate. TODO fix this."""
512 rates=self.baudrates;
514 print "Changing FET baud."
515 self.serialport.write(chr(0x00));
516 self.serialport.write(chr(0x80));
517 self.serialport.write(chr(1));
518 self.serialport.write(chr(baud));
520 print "Changed host baud."
521 self.serialport.setBaudrate(rates[baud]);
523 self.serialport.flushInput()
524 self.serialport.flushOutput()
526 print "Baud is now %i." % rates[baud];
529 return ord(self.serialport.read(1));
531 for r in self.baudrates:
532 print "\nTrying %i" % r;
533 self.serialport.setBaudrate(r);
535 self.serialport.flushInput()
536 self.serialport.flushOutput()
538 for i in range(1,10):
541 print "Read %02x %02x %02x %02x" % (
542 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
543 def monitortest(self):
544 """Self-test several functions through the monitor."""
545 print "Performing monitor self-test.";
546 self.monitorclocking();
547 for f in range(0,3000):
548 a=self.MONpeek16(0x0c00);
549 b=self.MONpeek16(0x0c02);
550 if a!=0x0c04 and a!=0x0c06:
551 print "ERROR Fetched %04x, %04x" % (a,b);
552 self.pokebyte(0x0021,0); #Drop LED
553 if self.MONpeek8(0x0021)!=0:
554 print "ERROR, P1OUT not cleared.";
555 self.pokebyte(0x0021,1); #Light LED
556 if not self.monitorecho():
557 print "Echo test failed.";
558 print "Self-test complete.";
559 self.monitorclocking();
560 def monitorecho(self):
561 data="The quick brown fox jumped over the lazy dog.";
562 self.writecmd(self.MONITORAPP,0x81,len(data),data);
564 print "Comm error recognized by monitorecho(), got:\n%s" % self.data;
568 def monitor_info(self):
569 print "GoodFET with %s MCU" % self.infostring();
570 print "Clocked at %s" % self.monitorclocking();
573 def monitor_list_apps(self, full=False):
575 old_value = self.besilent
576 self.besilent = True # turn off automatic call to readcmd
577 self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
578 self.besilent = old_value
580 # read the build date string
582 print "Build Date: %s" % self.data
583 print "Firmware apps:"
591 def monitorclocking(self):
592 """Return the 16-bit clocking value."""
593 return "0x%04x" % self.monitorgetclock();
595 def monitorsetclock(self,clock):
596 """Set the clocking value."""
597 self.MONpoke16(0x56, clock);
598 def monitorgetclock(self):
599 """Get the clocking value."""
600 if(os.environ.get("platform")=='arduino'):
602 #Check for MSP430 before peeking this.
603 return self.MONpeek16(0x56);
604 # The following functions ought to be implemented in
607 def infostring(self):
608 if(os.environ.get("platform")=='arduino'):
611 a=self.MONpeek8(0xff0);
612 b=self.MONpeek8(0xff1);
613 return "%02x%02x" % (a,b);
615 print "Locking Unsupported.";
617 print "Erasure Unsupported.";
623 print "Unimplemented.";
626 print "Unimplemented.";
629 print "Unimplemented.";
632 print "Unimplemented.";
635 print "Unimplemented.";
637 def flash(self,file):
638 """Flash an intel hex file to code memory."""
639 print "Flash not implemented.";
640 def dump(self,file,start=0,stop=0xffff):
641 """Dump an intel hex file from code memory."""
642 print "Dump not implemented.";
643 def peek32(self,address, memory="vn"):
645 return (self.peek16(address,memory)+
646 (self.peek16(address+2,memory)<<16));
647 def peek16(self,address, memory="vn"):
648 """Peek 16 bits of memory."""
649 return (self.peek8(address,memory)+
650 (self.peek8(address+1,memory)<<8));
651 def peek8(self,address, memory="vn"):
652 """Peek a byte of memory."""
653 return self.MONpeek8(address); #monitor
654 def peekblock(self,address,length,memory="vn"):
655 """Return a block of data."""
656 data=range(0,length);
657 for foo in range(0,length):
658 data[foo]=self.peek8(address+foo,memory);
660 def pokeblock(self,address,bytes,memory="vn"):
661 """Poke a block of a data into memory at an address."""
663 self.pokebyte(address,foo,memory);
666 def loadsymbols(self):
667 """Load symbols from a file."""