df26c855f6184098f62828730c0a647d882288ab
[goodfet] / GoodFET.py
1 #!/usr/bin/env python
2 # GoodFET Client Library
3
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is being rewritten and refactored.  You've been warned!
7
8 import sys, time, string, cStringIO, struct, glob, serial, os;
9 import sqlite3;
10
11 fmt = ("B", "<H", None, "<L")
12
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=="cc51": return GoodFETCC.GoodFETCC();
17     elif name=="cc2420" or name=="ccspi": return GoodFETCC.GoodFETCC();
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();
22     
23     print "Unsupported target: %s" % name;
24     sys.exit(0);
25
26 class SymbolTable:
27     """GoodFET Symbol Table"""
28     db=sqlite3.connect(":memory:");
29     
30     def __init__(self, *args, **kargs):
31         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
32     def get(self,name):
33         self.db.commit();
34         c=self.db.cursor();
35         try:
36             c.execute("select adr,memory from symbols where name=?",(name,));
37             for row in c:
38                 #print "Found it.";
39                 sys.stdout.flush();
40                 return row[0];
41             #print "No dice.";
42         except:# sqlite3.OperationalError:
43             #print "SQL error.";
44             return eval(name);
45         return eval(name);
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);
51
52 class GoodFET:
53     """GoodFET Client Library"""
54
55     besilent=0;
56     app=0;
57     verb=0;
58     count=0;
59     data="";
60     verbose=False
61     
62     GLITCHAPP=0x71;
63     MONITORAPP=0x00;
64     symbols=SymbolTable();
65     
66     def __init__(self, *args, **kargs):
67         self.data=[0];
68     def getConsole(self):
69         from GoodFETConsole import GoodFETConsole;
70         return GoodFETConsole(self);
71     def name2adr(self,name):
72         return self.symbols.get(name);
73     def timeout(self):
74         print "timeout\n";
75     def serInit(self, port=None, timeout=2):
76         """Open the serial port"""
77         # Make timeout None to wait forever, 0 for non-blocking mode.
78         
79         if port is None and os.environ.get("GOODFET")!=None:
80             glob_list = glob.glob(os.environ.get("GOODFET"));
81             if len(glob_list) > 0:
82                 port = glob_list[0];
83             else:
84                 port = os.environ.get("GOODFET");
85         if port is None:
86             glob_list = glob.glob("/dev/tty.usbserial*");
87             if len(glob_list) > 0:
88                 port = glob_list[0];
89         if port is None:
90             glob_list = glob.glob("/dev/ttyUSB*");
91             if len(glob_list) > 0:
92                 port = glob_list[0];
93         if port is None:
94             glob_list = glob.glob("/dev/ttyU0");
95             if len(glob_list) > 0:
96                 port = glob_list[0];
97         if os.name=='nt':
98             from scanwin32 import winScan;
99             scan=winScan();
100             for order,comport,desc,hwid in sorted(scan.comports()):
101                 try:
102                     if hwid.index('FTDI')==0:
103                         port=comport;
104                         #print "Using FTDI port %s" % port
105                 except:
106                     #Do nothing.
107                     a=1;
108         
109         self.serialport = serial.Serial(
110             port,
111             #9600,
112             115200,
113             parity = serial.PARITY_NONE,
114             timeout=timeout
115             )
116         
117         self.verb=0;
118         attempts=0;
119         connected=0;
120         while connected==0:
121             while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
122                 if attempts>2:
123                     print "Resyncing.";
124                 self.serialport.flushInput()
125                 self.serialport.flushOutput()
126                 #Explicitly set RTS and DTR to halt board.
127                 self.serialport.setRTS(1);
128                 self.serialport.setDTR(1);
129                 #Drop DTR, which is !RST, low to begin the app.
130                 self.serialport.setDTR(0);
131                 
132                 #TelosB reset, prefer software to I2C SPST Switch.
133                 if(os.environ.get("platform")=='telosb'):
134                     #print "TelosB Reset";
135                     self.telosBReset();
136                 #self.serialport.write(chr(0x80));
137                 #self.serialport.write(chr(0x80));
138                 #self.serialport.write(chr(0x80));
139                 #self.serialport.write(chr(0x80));
140                 
141                 
142                 self.serialport.flushInput()
143                 self.serialport.flushOutput()
144                 #time.sleep(60);
145                 attempts=attempts+1;
146                 self.readcmd(); #Read the first command.
147             #Here we have a connection, but maybe not a good one.
148             connected=1;
149             olds=self.infostring();
150             clocking=self.monitorclocking();
151             for foo in range(1,30):
152                 if not self.monitorecho():
153                     if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
154                                                   clocking);
155                     connected=0;
156                     break;
157         if self.verbose: print "Connected after %02i attempts." % attempts;
158         self.mon_connected();
159         self.serialport.setTimeout(12);
160     def telosSetSCL(self, level):
161         self.serialport.setRTS(not level)
162     def telosSetSDA(self, level):
163         self.serialport.setDTR(not level)
164
165     def telosI2CStart(self):
166         self.telosSetSDA(1)
167         self.telosSetSCL(1)
168         self.telosSetSDA(0)
169
170     def telosI2CStop(self):
171         self.telosSetSDA(0)
172         self.telosSetSCL(1)
173         self.telosSetSDA(1)
174
175     def telosI2CWriteBit(self, bit):
176         self.telosSetSCL(0)
177         self.telosSetSDA(bit)
178         time.sleep(2e-6)
179         self.telosSetSCL(1)
180         time.sleep(1e-6)
181         self.telosSetSCL(0)
182
183     def telosI2CWriteByte(self, byte):
184         self.telosI2CWriteBit( byte & 0x80 );
185         self.telosI2CWriteBit( byte & 0x40 );
186         self.telosI2CWriteBit( byte & 0x20 );
187         self.telosI2CWriteBit( byte & 0x10 );
188         self.telosI2CWriteBit( byte & 0x08 );
189         self.telosI2CWriteBit( byte & 0x04 );
190         self.telosI2CWriteBit( byte & 0x02 );
191         self.telosI2CWriteBit( byte & 0x01 );
192         self.telosI2CWriteBit( 0 );  # "acknowledge"
193
194     def telosI2CWriteCmd(self, addr, cmdbyte):
195         self.telosI2CStart()
196         self.telosI2CWriteByte( 0x90 | (addr << 1) )
197         self.telosI2CWriteByte( cmdbyte )
198         self.telosI2CStop()
199
200     def telosBReset(self,invokeBSL=0):
201         # "BSL entry sequence at dedicated JTAG pins"
202         # rst !s0: 0 0 0 0 1 1
203         # tck !s1: 1 0 1 0 0 1
204         #   s0|s1: 1 3 1 3 2 0
205
206         # "BSL entry sequence at shared JTAG pins"
207         # rst !s0: 0 0 0 0 1 1
208         # tck !s1: 0 1 0 1 1 0
209         #   s0|s1: 3 1 3 1 0 2
210
211         if invokeBSL:
212             self.telosI2CWriteCmd(0,1)
213             self.telosI2CWriteCmd(0,3)
214             self.telosI2CWriteCmd(0,1)
215             self.telosI2CWriteCmd(0,3)
216             self.telosI2CWriteCmd(0,2)
217             self.telosI2CWriteCmd(0,0)
218         else:
219             self.telosI2CWriteCmd(0,3)
220             self.telosI2CWriteCmd(0,2)
221
222         # This line was not defined inside the else: block, not sure where it
223         # should be however
224         self.telosI2CWriteCmd(0,0)
225         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
226         self.serialport.flushInput()  #clear buffers
227
228
229     def getbuffer(self,size=0x1c00):
230         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
231         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
232     def writecmd(self, app, verb, count=0, data=[]):
233         """Write a command and some data to the GoodFET."""
234         self.serialport.write(chr(app));
235         self.serialport.write(chr(verb));
236         
237         #if data!=None:
238         #    count=len(data); #Initial count ignored.
239         
240         #print "TX %02x %02x %04x" % (app,verb,count);
241         
242         #little endian 16-bit length
243         self.serialport.write(chr(count&0xFF));
244         self.serialport.write(chr(count>>8));
245
246         if self.verbose:
247             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
248         
249         #print "count=%02x, len(data)=%04x" % (count,len(data));
250         
251         if count!=0:
252             if(isinstance(data,list)):
253                 for i in range(0,count):
254                 #print "Converting %02x at %i" % (data[i],i)
255                     data[i]=chr(data[i]);
256             #print type(data);
257             outstr=''.join(data);
258             self.serialport.write(outstr);
259         if not self.besilent:
260             return self.readcmd()
261         else:
262             return []
263
264     def readcmd(self):
265         """Read a reply from the GoodFET."""
266         while 1:#self.serialport.inWaiting(): # Loop while input data is available
267             try:
268                 #print "Reading...";
269                 self.app=ord(self.serialport.read(1));
270                 #print "APP=%2x" % self.app;
271                 self.verb=ord(self.serialport.read(1));
272                 #print "VERB=%02x" % self.verb;
273                 self.count=(
274                     ord(self.serialport.read(1))
275                     +(ord(self.serialport.read(1))<<8)
276                     );
277
278                 if self.verbose:
279                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
280             
281                 #Debugging string; print, but wait.
282                 if self.app==0xFF:
283                     if self.verb==0xFF:
284                         print "# DEBUG %s" % self.serialport.read(self.count)
285                     elif self.verb==0xFE:
286                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
287                     elif self.verb==0xFD:
288                         #Do nothing, just wait so there's no timeout.
289                         print "# NOP.";
290                         
291                     sys.stdout.flush();
292                 else:
293                     self.data=self.serialport.read(self.count);
294                     return self.data;
295             except TypeError:
296                 if self.connected:
297                     print "Warning: waiting for serial read timed out (most likely).";
298                     #print "This shouldn't happen after syncing.  Exiting for safety.";                    
299                     #sys.exit(-1)
300                 return self.data;
301     #Glitching stuff.
302     def glitchApp(self,app):
303         """Glitch into a device by its application."""
304         self.data=[app&0xff];
305         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
306         #return ord(self.data[0]);
307     def glitchVerb(self,app,verb,data):
308         """Glitch during a transaction."""
309         if data==None: data=[];
310         self.data=[app&0xff, verb&0xFF]+data;
311         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
312         #return ord(self.data[0]);
313     def glitchstart(self):
314         """Glitch into the AVR application."""
315         self.glitchVerb(self.APP,0x20,None);
316     def glitchstarttime(self):
317         """Measure the timer of the START verb."""
318         return self.glitchTime(self.APP,0x20,None);
319     def glitchTime(self,app,verb,data):
320         """Time the execution of a verb."""
321         if data==None: data=[];
322         self.data=[app&0xff, verb&0xFF]+data;
323         print "Timing app %02x verb %02x." % (app,verb);
324         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
325         time=ord(self.data[0])+(ord(self.data[1])<<8);
326         print "Timed to be %i." % time;
327         return time;
328     def glitchVoltages(self,low=0x0880, high=0x0fff):
329         """Set glitching voltages. (0x0fff is max.)"""
330         self.data=[low&0xff, (low>>8)&0xff,
331                    high&0xff, (high>>8)&0xff];
332         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
333         #return ord(self.data[0]);
334     def glitchRate(self,count=0x0800):
335         """Set glitching count period."""
336         self.data=[count&0xff, (count>>8)&0xff];
337         self.writecmd(self.GLITCHAPP,0x91,2,
338                       self.data);
339         #return ord(self.data[0]);
340     
341     
342     #Monitor stuff
343     def silent(self,s=0):
344         """Transmissions halted when 1."""
345         self.besilent=s;
346         print "besilent is %i" % self.besilent;
347         self.writecmd(0,0xB0,1,[s]);
348     connected=0;
349     def mon_connected(self):
350         """Announce to the monitor that the connection is good."""
351         self.connected=1;
352         self.writecmd(0,0xB1,0,[]);
353     def out(self,byte):
354         """Write a byte to P5OUT."""
355         self.writecmd(0,0xA1,1,[byte]);
356     def dir(self,byte):
357         """Write a byte to P5DIR."""
358         self.writecmd(0,0xA0,1,[byte]);
359     def call(self,adr):
360         """Call to an address."""
361         self.writecmd(0,0x30,2,
362                       [adr&0xFF,(adr>>8)&0xFF]);
363     def execute(self,code):
364         """Execute supplied code."""
365         self.writecmd(0,0x31,2,#len(code),
366                       code);
367     def MONpeek8(self,address):
368         """Read a byte of memory from the monitor."""
369         self.data=[address&0xff,address>>8];
370         self.writecmd(0,0x02,2,self.data);
371         #self.readcmd();
372         return ord(self.data[0]);
373     def MONpeek16(self,address):
374         """Read a word of memory from the monitor."""
375         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
376     def peek(self,address):
377         """Read a word of memory from the monitor."""
378         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
379     def eeprompeek(self,address):
380         """Read a word of memory from the monitor."""
381         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
382     def peekbysym(self,name):
383         """Read a value by its symbol name."""
384         #TODO include memory in symbol.
385         reg=self.symbols.get(name);
386         return self.peek8(reg,"data");
387     def pokebysym(self,name,val):
388         """Write a value by its symbol name."""
389         #TODO include memory in symbol.
390         reg=self.symbols.get(name);
391         return self.pokebyte(reg,val);
392     def pokebyte(self,address,value,memory="vn"):
393         """Set a byte of memory by the monitor."""
394         self.data=[address&0xff,address>>8,value];
395         self.writecmd(0,0x03,3,self.data);
396         return ord(self.data[0]);
397     def poke16(self,address,value):
398         """Set a word of memory by the monitor."""
399         self.pokebyte(address,value&0xFF);
400         self.pokebyte(address,(value>>8)&0xFF);
401         return value;
402     def setsecret(self,value):
403         """Set a secret word for later retreival.  Used by glitcher."""
404         self.eeprompoke(0,value);
405         self.eeprompoke(1,value);
406     def getsecret(self):
407         """Get a secret word.  Used by glitcher."""
408         self.eeprompeek(0);
409     
410     def dumpmem(self,begin,end):
411         i=begin;
412         while i<end:
413             print "%04x %04x" % (i, self.MONpeek16(i));
414             i+=2;
415     def monitor_ram_pattern(self):
416         """Overwrite all of RAM with 0xBEEF."""
417         self.writecmd(0,0x90,0,self.data);
418         return;
419     def monitor_ram_depth(self):
420         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
421         self.writecmd(0,0x91,0,self.data);
422         return ord(self.data[0])+(ord(self.data[1])<<8);
423     
424     #Baud rates.
425     baudrates=[115200, 
426                9600,
427                19200,
428                38400,
429                57600,
430                115200];
431     def setBaud(self,baud):
432         """Change the baud rate.  TODO fix this."""
433         rates=self.baudrates;
434         self.data=[baud];
435         print "Changing FET baud."
436         self.serialport.write(chr(0x00));
437         self.serialport.write(chr(0x80));
438         self.serialport.write(chr(1));
439         self.serialport.write(chr(baud));
440         
441         print "Changed host baud."
442         self.serialport.setBaudrate(rates[baud]);
443         time.sleep(1);
444         self.serialport.flushInput()
445         self.serialport.flushOutput()
446         
447         print "Baud is now %i." % rates[baud];
448         return;
449     def readbyte(self):
450         return ord(self.serialport.read(1));
451     def findbaud(self):
452         for r in self.baudrates:
453             print "\nTrying %i" % r;
454             self.serialport.setBaudrate(r);
455             #time.sleep(1);
456             self.serialport.flushInput()
457             self.serialport.flushOutput()
458             
459             for i in range(1,10):
460                 self.readbyte();
461             
462             print "Read %02x %02x %02x %02x" % (
463                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
464     def monitortest(self):
465         """Self-test several functions through the monitor."""
466         print "Performing monitor self-test.";
467         self.monitorclocking();
468         for f in range(0,3000):
469             a=self.MONpeek16(0x0c00);
470             b=self.MONpeek16(0x0c02);
471             if a!=0x0c04 and a!=0x0c06:
472                 print "ERROR Fetched %04x, %04x" % (a,b);
473             self.pokebyte(0x0021,0); #Drop LED
474             if self.MONpeek8(0x0021)!=0:
475                 print "ERROR, P1OUT not cleared.";
476             self.pokebyte(0x0021,1); #Light LED
477             if not self.monitorecho():
478                 print "Echo test failed.";
479         print "Self-test complete.";
480         self.monitorclocking();
481     def monitorecho(self):
482         data="The quick brown fox jumped over the lazy dog.";
483         self.writecmd(self.MONITORAPP,0x81,len(data),data);
484         if self.data!=data:
485             if self.verbose: print "Comm error recognized by monitorecho().";
486             return 0;
487         return 1;
488
489     def monitor_info(self):
490         print "GoodFET with %s MCU" % self.infostring();
491         print "Clocked at %s" % self.monitorclocking();
492         return 1;
493
494     def monitor_list_apps(self, full=False): 
495         self.monitor_info()
496         old_value = self.besilent
497         self.besilent = True    # turn off automatic call to readcmd
498         self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
499         self.besilent = old_value
500         
501         # read the build date string 
502         self.readcmd()
503         print "Build Date: %s" % self.data
504         print "Firmware apps:"
505         while True:
506             self.readcmd()
507             if self.count == 0:
508                 break
509             print self.data
510         return 1;
511
512     def monitorclocking(self):
513         """Return the 16-bit clocking value."""
514         return "0x%04x" % self.monitorgetclock();
515     
516     def monitorsetclock(self,clock):
517         """Set the clocking value."""
518         self.MONpoke16(0x56, clock);
519     def monitorgetclock(self):
520         """Get the clocking value."""
521         return self.MONpeek16(0x56);
522     # The following functions ought to be implemented in
523     # every client.
524     
525     def infostring(self):
526         a=self.MONpeek8(0xff0);
527         b=self.MONpeek8(0xff1);
528         return "%02x%02x" % (a,b);
529     def lock(self):
530         print "Locking Unsupported.";
531     def erase(self):
532         print "Erasure Unsupported.";
533     def setup(self):
534         return;
535     def start(self):
536         return;
537     def test(self):
538         print "Unimplemented.";
539         return;
540     def status(self):
541         print "Unimplemented.";
542         return;
543     def halt(self):
544         print "Unimplemented.";
545         return;
546     def resume(self):
547         print "Unimplemented.";
548         return;
549     def getpc(self):
550         print "Unimplemented.";
551         return 0xdead;
552     def flash(self,file):
553         """Flash an intel hex file to code memory."""
554         print "Flash not implemented.";
555     def dump(self,file,start=0,stop=0xffff):
556         """Dump an intel hex file from code memory."""
557         print "Dump not implemented.";
558     def peek32(self,address, memory="vn"):
559         """Peek 32 bits."""
560         return (self.peek16(address,memory)+
561                 (self.peek16(address+2,memory)<<16));
562     def peek16(self,address, memory="vn"):
563         """Peek 16 bits of memory."""
564         return (self.peek8(address,memory)+
565                 (self.peek8(address+1,memory)<<8));
566     def peek8(self,address, memory="vn"):
567         """Peek a byte of memory."""
568         return self.MONpeek8(address); #monitor
569     def peekblock(self,address,length,memory="vn"):
570         """Return a block of data."""
571         data=range(0,length);
572         for foo in range(0,length):
573             data[foo]=self.peek8(address+foo,memory);
574         return data;
575     def pokeblock(self,address,bytes,memory="vn"):
576         """Poke a block of a data into memory at an address."""
577         for foo in bytes:
578             self.pokebyte(address,foo,memory);
579             address=address+1;
580         return;
581     def loadsymbols(self):
582         """Load symbols from a file."""
583         return;