Beginning CCSPI mode. Not nearly complete.
[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 "Error: 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         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
317         return ord(self.data[0])+(ord(self.data[1])<<8);
318     def glitchVoltages(self,low=0x0880, high=0x0fff):
319         """Set glitching voltages. (0x0fff is max.)"""
320         self.data=[low&0xff, (low>>8)&0xff,
321                    high&0xff, (high>>8)&0xff];
322         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
323         #return ord(self.data[0]);
324     def glitchRate(self,count=0x0800):
325         """Set glitching count period."""
326         self.data=[count&0xff, (count>>8)&0xff];
327         self.writecmd(self.GLITCHAPP,0x91,2,
328                       self.data);
329         #return ord(self.data[0]);
330     
331     
332     #Monitor stuff
333     def silent(self,s=0):
334         """Transmissions halted when 1."""
335         self.besilent=s;
336         print "besilent is %i" % self.besilent;
337         self.writecmd(0,0xB0,1,[s]);
338     connected=0;
339     def mon_connected(self):
340         """Announce to the monitor that the connection is good."""
341         self.connected=1;
342         self.writecmd(0,0xB1,0,[]);
343     def out(self,byte):
344         """Write a byte to P5OUT."""
345         self.writecmd(0,0xA1,1,[byte]);
346     def dir(self,byte):
347         """Write a byte to P5DIR."""
348         self.writecmd(0,0xA0,1,[byte]);
349     def call(self,adr):
350         """Call to an address."""
351         self.writecmd(0,0x30,2,
352                       [adr&0xFF,(adr>>8)&0xFF]);
353     def execute(self,code):
354         """Execute supplied code."""
355         self.writecmd(0,0x31,2,#len(code),
356                       code);
357     def peekbyte(self,address):
358         """Read a byte of memory from the monitor."""
359         self.data=[address&0xff,address>>8];
360         self.writecmd(0,0x02,2,self.data);
361         #self.readcmd();
362         return ord(self.data[0]);
363     def peekword(self,address):
364         """Read a word of memory from the monitor."""
365         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
366     def peek(self,address):
367         """Read a word of memory from the monitor."""
368         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
369     def pokebyte(self,address,value):
370         """Set a byte of memory by the monitor."""
371         self.data=[address&0xff,address>>8,value];
372         self.writecmd(0,0x03,3,self.data);
373         return ord(self.data[0]);
374     def dumpmem(self,begin,end):
375         i=begin;
376         while i<end:
377             print "%04x %04x" % (i, self.peekword(i));
378             i+=2;
379     def monitor_ram_pattern(self):
380         """Overwrite all of RAM with 0xBEEF."""
381         self.writecmd(0,0x90,0,self.data);
382         return;
383     def monitor_ram_depth(self):
384         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
385         self.writecmd(0,0x91,0,self.data);
386         return ord(self.data[0])+(ord(self.data[1])<<8);
387     
388     #Baud rates.
389     baudrates=[115200, 
390                9600,
391                19200,
392                38400,
393                57600,
394                115200];
395     def setBaud(self,baud):
396         """Change the baud rate.  TODO fix this."""
397         rates=self.baudrates;
398         self.data=[baud];
399         print "Changing FET baud."
400         self.serialport.write(chr(0x00));
401         self.serialport.write(chr(0x80));
402         self.serialport.write(chr(1));
403         self.serialport.write(chr(baud));
404         
405         print "Changed host baud."
406         self.serialport.setBaudrate(rates[baud]);
407         time.sleep(1);
408         self.serialport.flushInput()
409         self.serialport.flushOutput()
410         
411         print "Baud is now %i." % rates[baud];
412         return;
413     def readbyte(self):
414         return ord(self.serialport.read(1));
415     def findbaud(self):
416         for r in self.baudrates:
417             print "\nTrying %i" % r;
418             self.serialport.setBaudrate(r);
419             #time.sleep(1);
420             self.serialport.flushInput()
421             self.serialport.flushOutput()
422             
423             for i in range(1,10):
424                 self.readbyte();
425             
426             print "Read %02x %02x %02x %02x" % (
427                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
428     def monitortest(self):
429         """Self-test several functions through the monitor."""
430         print "Performing monitor self-test.";
431         self.monitorclocking();
432         for f in range(0,3000):
433             a=self.peekword(0x0c00);
434             b=self.peekword(0x0c02);
435             if a!=0x0c04 and a!=0x0c06:
436                 print "ERROR Fetched %04x, %04x" % (a,b);
437             self.pokebyte(0x0021,0); #Drop LED
438             if self.peekbyte(0x0021)!=0:
439                 print "ERROR, P1OUT not cleared.";
440             self.pokebyte(0x0021,1); #Light LED
441             if not self.monitorecho():
442                 print "Echo test failed.";
443         print "Self-test complete.";
444         self.monitorclocking();
445     def monitorecho(self):
446         data="The quick brown fox jumped over the lazy dog.";
447         self.writecmd(self.MONITORAPP,0x81,len(data),data);
448         if self.data!=data:
449             if self.verbose: print "Comm error recognized by monitorecho().";
450             return 0;
451         return 1;
452     def monitorclocking(self):
453         DCOCTL=self.peekbyte(0x0056);
454         BCSCTL1=self.peekbyte(0x0057);
455         return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
456
457     # The following functions ought to be implemented in
458     # every client.
459
460     def infostring(self):
461         a=self.peekbyte(0xff0);
462         b=self.peekbyte(0xff1);
463         return "%02x%02x" % (a,b);
464     def lock(self):
465         print "Locking Unsupported.";
466     def erase(self):
467         print "Erasure Unsupported.";
468     def setup(self):
469         return;
470     def start(self):
471         return;
472     def test(self):
473         print "Unimplemented.";
474         return;
475     def status(self):
476         print "Unimplemented.";
477         return;
478     def halt(self):
479         print "Unimplemented.";
480         return;
481     def resume(self):
482         print "Unimplemented.";
483         return;
484     def getpc(self):
485         print "Unimplemented.";
486         return 0xdead;
487     def flash(self,file):
488         """Flash an intel hex file to code memory."""
489         print "Flash not implemented.";
490     def dump(self,file,start=0,stop=0xffff):
491         """Dump an intel hex file from code memory."""
492         print "Dump not implemented.";
493     def peek32(self,address, memory="vn"):
494         return (self.peek16(address,memory)+
495                 (self.peek16(address+2,memory)<<16));
496     def peek16(self,address, memory="vn"):
497         return (self.peek8(address,memory)+
498                 (self.peek8(address+1,memory)<<8));
499     def peek8(self,address, memory="vn"):
500         return self.peekbyte(address); #monitor
501     def peekword(self,address, memory="vn"):
502         return self.peek(address); #monitor
503     
504     def loadsymbols(self):
505         return;