myriad of arm/adi additions. working on moving past arm7 into adiv5
[goodfet] / client / 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 os.name=='nt':
94             from scanwin32 import winScan;
95             scan=winScan();
96             for order,comport,desc,hwid in sorted(scan.comports()):
97                 try:
98                     if hwid.index('FTDI')==0:
99                         port=comport;
100                         #print "Using FTDI port %s" % port
101                 except:
102                     #Do nothing.
103                     a=1;
104         
105         self.serialport = serial.Serial(
106             port,
107             #9600,
108             115200,
109             parity = serial.PARITY_NONE,
110             timeout=timeout
111             )
112         
113         self.verb=0;
114         attempts=0;
115         connected=0;
116         while connected==0:
117             while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
118                 #print "Resyncing.";
119                 self.serialport.flushInput()
120                 self.serialport.flushOutput()
121                 #Explicitly set RTS and DTR to halt board.
122                 self.serialport.setRTS(1);
123                 self.serialport.setDTR(1);
124                 #Drop DTR, which is !RST, low to begin the app.
125                 self.serialport.setDTR(0);
126                 
127                 #TelosB reset, prefer software to I2C SPST Switch.
128                 if(os.environ.get("platform")=='telosb'):
129                     self.telosBReset();
130                 #self.serialport.write(chr(0x80));
131                 #self.serialport.write(chr(0x80));
132                 #self.serialport.write(chr(0x80));
133                 #self.serialport.write(chr(0x80));
134                 
135                 
136                 self.serialport.flushInput()
137                 self.serialport.flushOutput()
138                 #time.sleep(60);
139                 attempts=attempts+1;
140                 self.readcmd(); #Read the first command.
141             #Here we have a connection, but maybe not a good one.
142             connected=1;
143             olds=self.infostring();
144             clocking=self.monitorclocking();
145             for foo in range(1,30):
146                 if not self.monitorecho():
147                     if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
148                                                   clocking);
149                     connected=0;
150                     break;
151         if self.verbose: print "Connected after %02i attempts." % attempts;
152         self.mon_connected();
153     def telosSetSCL(self, level):
154         self.serialport.setRTS(not level)
155     def telosSetSDA(self, level):
156         self.serialport.setDTR(not level)
157
158     def telosI2CStart(self):
159         self.telosSetSDA(1)
160         self.telosSetSCL(1)
161         self.telosSetSDA(0)
162
163     def telosI2CStop(self):
164         self.telosSetSDA(0)
165         self.telosSetSCL(1)
166         self.telosSetSDA(1)
167
168     def telosI2CWriteBit(self, bit):
169         self.telosSetSCL(0)
170         self.telosSetSDA(bit)
171         time.sleep(2e-6)
172         self.telosSetSCL(1)
173         time.sleep(1e-6)
174         self.telosSetSCL(0)
175
176     def telosI2CWriteByte(self, byte):
177         self.telosI2CWriteBit( byte & 0x80 );
178         self.telosI2CWriteBit( byte & 0x40 );
179         self.telosI2CWriteBit( byte & 0x20 );
180         self.telosI2CWriteBit( byte & 0x10 );
181         self.telosI2CWriteBit( byte & 0x08 );
182         self.telosI2CWriteBit( byte & 0x04 );
183         self.telosI2CWriteBit( byte & 0x02 );
184         self.telosI2CWriteBit( byte & 0x01 );
185         self.telosI2CWriteBit( 0 );  # "acknowledge"
186
187     def telosI2CWriteCmd(self, addr, cmdbyte):
188         self.telosI2CStart()
189         self.telosI2CWriteByte( 0x90 | (addr << 1) )
190         self.telosI2CWriteByte( cmdbyte )
191         self.telosI2CStop()
192
193     def telosBReset(self,invokeBSL=0):
194         # "BSL entry sequence at dedicated JTAG pins"
195         # rst !s0: 0 0 0 0 1 1
196         # tck !s1: 1 0 1 0 0 1
197         #   s0|s1: 1 3 1 3 2 0
198
199         # "BSL entry sequence at shared JTAG pins"
200         # rst !s0: 0 0 0 0 1 1
201         # tck !s1: 0 1 0 1 1 0
202         #   s0|s1: 3 1 3 1 0 2
203
204         if invokeBSL:
205             self.telosI2CWriteCmd(0,1)
206             self.telosI2CWriteCmd(0,3)
207             self.telosI2CWriteCmd(0,1)
208             self.telosI2CWriteCmd(0,3)
209             self.telosI2CWriteCmd(0,2)
210             self.telosI2CWriteCmd(0,0)
211         else:
212             self.telosI2CWriteCmd(0,3)
213             self.telosI2CWriteCmd(0,2)
214
215         # This line was not defined inside the else: block, not sure where it
216         # should be however
217         self.telosI2CWriteCmd(0,0)
218         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
219         self.serialport.flushInput()  #clear buffers
220
221
222     def getbuffer(self,size=0x1c00):
223         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
224         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
225     def writecmd(self, app, verb, count=0, data=[]):
226         """Write a command and some data to the GoodFET."""
227         self.serialport.write(chr(app));
228         self.serialport.write(chr(verb));
229         
230         #if data!=None:
231         #    count=len(data); #Initial count ignored.
232         
233         #print "TX %02x %02x %04x" % (app,verb,count);
234         
235         #little endian 16-bit length
236         self.serialport.write(chr(count&0xFF));
237         self.serialport.write(chr(count>>8));
238
239         if self.verbose:
240             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
241         
242         #print "count=%02x, len(data)=%04x" % (count,len(data));
243         
244         if count!=0:
245             if(isinstance(data,list)):
246                 for i in range(0,count):
247                 #print "Converting %02x at %i" % (data[i],i)
248                     data[i]=chr(data[i]);
249             #print type(data);
250             outstr=''.join(data);
251             self.serialport.write(outstr);
252         if not self.besilent:
253             return self.readcmd()
254         else:
255             return []
256
257     def readcmd(self):
258         """Read a reply from the GoodFET."""
259         while 1:#self.serialport.inWaiting(): # Loop while input data is available
260             try:
261                 #print "Reading...";
262                 self.app=ord(self.serialport.read(1));
263                 #print "APP=%2x" % self.app;
264                 self.verb=ord(self.serialport.read(1));
265                 #print "VERB=%02x" % self.verb;
266                 self.count=(
267                     ord(self.serialport.read(1))
268                     +(ord(self.serialport.read(1))<<8)
269                     );
270
271                 if self.verbose:
272                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
273             
274                 #Debugging string; print, but wait.
275                 if self.app==0xFF:
276                     if self.verb==0xFF:
277                         print "# DEBUG %s" % self.serialport.read(self.count)
278                     elif self.verb==0xFE:
279                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
280                     elif self.verb==0xFD:
281                         #Do nothing, just wait so there's no timeout.
282                         print "# NOP.";
283                         
284                     sys.stdout.flush();
285                 else:
286                     self.data=self.serialport.read(self.count);
287                     return self.data;
288             except TypeError:
289                 if self.connected:
290                     print "Warning: waiting for serial read timed out (most likely).";
291                     #print "This shouldn't happen after syncing.  Exiting for safety.";                    
292                     #sys.exit(-1)
293                 return self.data;
294     #Glitching stuff.
295     def glitchApp(self,app):
296         """Glitch into a device by its application."""
297         self.data=[app&0xff];
298         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
299         #return ord(self.data[0]);
300     def glitchVerb(self,app,verb,data):
301         """Glitch during a transaction."""
302         if data==None: data=[];
303         self.data=[app&0xff, verb&0xFF]+data;
304         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
305         #return ord(self.data[0]);
306     def glitchstart(self):
307         """Glitch into the AVR application."""
308         self.glitchVerb(self.APP,0x20,None);
309     def glitchstarttime(self):
310         """Measure the timer of the START verb."""
311         return self.glitchTime(self.APP,0x20,None);
312     def glitchTime(self,app,verb,data):
313         """Time the execution of a verb."""
314         if data==None: data=[];
315         self.data=[app&0xff, verb&0xFF]+data;
316         print "Timing app %02x verb %02x." % (app,verb);
317         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
318         time=ord(self.data[0])+(ord(self.data[1])<<8);
319         print "Timed to be %i." % time;
320         return time;
321     def glitchVoltages(self,low=0x0880, high=0x0fff):
322         """Set glitching voltages. (0x0fff is max.)"""
323         self.data=[low&0xff, (low>>8)&0xff,
324                    high&0xff, (high>>8)&0xff];
325         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
326         #return ord(self.data[0]);
327     def glitchRate(self,count=0x0800):
328         """Set glitching count period."""
329         self.data=[count&0xff, (count>>8)&0xff];
330         self.writecmd(self.GLITCHAPP,0x91,2,
331                       self.data);
332         #return ord(self.data[0]);
333     
334     
335     #Monitor stuff
336     def silent(self,s=0):
337         """Transmissions halted when 1."""
338         self.besilent=s;
339         print "besilent is %i" % self.besilent;
340         self.writecmd(0,0xB0,1,[s]);
341     connected=0;
342     def mon_connected(self):
343         """Announce to the monitor that the connection is good."""
344         self.connected=1;
345         self.writecmd(0,0xB1,0,[]);
346     def out(self,byte):
347         """Write a byte to P5OUT."""
348         self.writecmd(0,0xA1,1,[byte]);
349     def dir(self,byte):
350         """Write a byte to P5DIR."""
351         self.writecmd(0,0xA0,1,[byte]);
352     def call(self,adr):
353         """Call to an address."""
354         self.writecmd(0,0x30,2,
355                       [adr&0xFF,(adr>>8)&0xFF]);
356     def execute(self,code):
357         """Execute supplied code."""
358         self.writecmd(0,0x31,2,#len(code),
359                       code);
360     def peekbyte(self,address):
361         """Read a byte of memory from the monitor."""
362         self.data=[address&0xff,address>>8];
363         self.writecmd(0,0x02,2,self.data);
364         #self.readcmd();
365         return ord(self.data[0]);
366     def peekword(self,address):
367         """Read a word of memory from the monitor."""
368         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
369     def peek(self,address):
370         """Read a word of memory from the monitor."""
371         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
372     def eeprompeek(self,address):
373         """Read a word of memory from the monitor."""
374         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
375     
376     def pokebyte(self,address,value):
377         """Set a byte of memory by the monitor."""
378         self.data=[address&0xff,address>>8,value];
379         self.writecmd(0,0x03,3,self.data);
380         return ord(self.data[0]);
381     def poke16(self,address,value):
382         """Set a word of memory by the monitor."""
383         self.pokebyte(address,value&0xFF);
384         self.pokebyte(address,(value>>8)&0xFF);
385         return value;
386     def setsecret(self,value):
387         """Set a secret word for later retreival.  Used by glitcher."""
388         self.eeprompoke(0,value);
389         self.eeprompoke(1,value);
390     def getsecret(self):
391         """Get a secret word.  Used by glitcher."""
392         self.eeprompeek(0);
393     
394     def dumpmem(self,begin,end):
395         i=begin;
396         while i<end:
397             print "%04x %04x" % (i, self.peekword(i));
398             i+=2;
399     def monitor_ram_pattern(self):
400         """Overwrite all of RAM with 0xBEEF."""
401         self.writecmd(0,0x90,0,self.data);
402         return;
403     def monitor_ram_depth(self):
404         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
405         self.writecmd(0,0x91,0,self.data);
406         return ord(self.data[0])+(ord(self.data[1])<<8);
407     
408     #Baud rates.
409     baudrates=[115200, 
410                9600,
411                19200,
412                38400,
413                57600,
414                115200];
415     def setBaud(self,baud):
416         """Change the baud rate.  TODO fix this."""
417         rates=self.baudrates;
418         self.data=[baud];
419         print "Changing FET baud."
420         self.serialport.write(chr(0x00));
421         self.serialport.write(chr(0x80));
422         self.serialport.write(chr(1));
423         self.serialport.write(chr(baud));
424         
425         print "Changed host baud."
426         self.serialport.setBaudrate(rates[baud]);
427         time.sleep(1);
428         self.serialport.flushInput()
429         self.serialport.flushOutput()
430         
431         print "Baud is now %i." % rates[baud];
432         return;
433     def readbyte(self):
434         return ord(self.serialport.read(1));
435     def findbaud(self):
436         for r in self.baudrates:
437             print "\nTrying %i" % r;
438             self.serialport.setBaudrate(r);
439             #time.sleep(1);
440             self.serialport.flushInput()
441             self.serialport.flushOutput()
442             
443             for i in range(1,10):
444                 self.readbyte();
445             
446             print "Read %02x %02x %02x %02x" % (
447                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
448     def monitortest(self):
449         """Self-test several functions through the monitor."""
450         print "Performing monitor self-test.";
451         self.monitorclocking();
452         for f in range(0,3000):
453             a=self.peekword(0x0c00);
454             b=self.peekword(0x0c02);
455             if a!=0x0c04 and a!=0x0c06:
456                 print "ERROR Fetched %04x, %04x" % (a,b);
457             self.pokebyte(0x0021,0); #Drop LED
458             if self.peekbyte(0x0021)!=0:
459                 print "ERROR, P1OUT not cleared.";
460             self.pokebyte(0x0021,1); #Light LED
461             if not self.monitorecho():
462                 print "Echo test failed.";
463         print "Self-test complete.";
464         self.monitorclocking();
465     def monitorecho(self):
466         data="The quick brown fox jumped over the lazy dog.";
467         self.writecmd(self.MONITORAPP,0x81,len(data),data);
468         if self.data!=data:
469             if self.verbose: print "Comm error recognized by monitorecho().";
470             return 0;
471         return 1;
472     def monitorclocking(self):
473         """Return the 16-bit clocking value."""
474         return "0x%04x" % self.monitorgetclock();
475     
476     def monitorsetclock(self,clock):
477         """Set the clocking value."""
478         self.poke16(0x56, clock);
479     def monitorgetclock(self):
480         """Get the clocking value."""
481         return self.peek16(0x56);
482     # The following functions ought to be implemented in
483     # every client.
484     
485     def infostring(self):
486         a=self.peekbyte(0xff0);
487         b=self.peekbyte(0xff1);
488         return "%02x%02x" % (a,b);
489     def lock(self):
490         print "Locking Unsupported.";
491     def erase(self):
492         print "Erasure Unsupported.";
493     def setup(self):
494         return;
495     def start(self):
496         return;
497     def test(self):
498         print "Unimplemented.";
499         return;
500     def status(self):
501         print "Unimplemented.";
502         return;
503     def halt(self):
504         print "Unimplemented.";
505         return;
506     def resume(self):
507         print "Unimplemented.";
508         return;
509     def getpc(self):
510         print "Unimplemented.";
511         return 0xdead;
512     def flash(self,file):
513         """Flash an intel hex file to code memory."""
514         print "Flash not implemented.";
515     def dump(self,file,start=0,stop=0xffff):
516         """Dump an intel hex file from code memory."""
517         print "Dump not implemented.";
518     def peek32(self,address, memory="vn"):
519         """Peek 32 bits."""
520         return (self.peek16(address,memory)+
521                 (self.peek16(address+2,memory)<<16));
522     def peek16(self,address, memory="vn"):
523         """Peek 16 bits of memory."""
524         return (self.peek8(address,memory)+
525                 (self.peek8(address+1,memory)<<8));
526     def peek8(self,address, memory="vn"):
527         """Peek a byte of memory."""
528         return self.peekbyte(address); #monitor
529     def peekword(self,address, memory="vn"):
530         """Peek a natively sized word of memory."""
531         return self.peek16(address); #monitor
532     def peekblock(self,address,length,memory="vn"):
533         """Return a block of data."""
534         data=range(0,length);
535         for foo in range(0,length):
536             data[foo]=self.peek8(address+foo,memory);
537         return data;
538     def loadsymbols(self):
539         """Load symbols from a file."""
540         return;