Nearing 16-bit clock control data.
[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         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 setsecret(self,value):
382         """Set a secret word for later retreival.  Used by glitcher."""
383         self.eeprompoke(0,value);
384         self.eeprompoke(1,value);
385     def getsecret(self):
386         """Get a secret word.  Used by glitcher."""
387         self.eeprompeek(0);
388     
389     def dumpmem(self,begin,end):
390         i=begin;
391         while i<end:
392             print "%04x %04x" % (i, self.peekword(i));
393             i+=2;
394     def monitor_ram_pattern(self):
395         """Overwrite all of RAM with 0xBEEF."""
396         self.writecmd(0,0x90,0,self.data);
397         return;
398     def monitor_ram_depth(self):
399         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
400         self.writecmd(0,0x91,0,self.data);
401         return ord(self.data[0])+(ord(self.data[1])<<8);
402     
403     #Baud rates.
404     baudrates=[115200, 
405                9600,
406                19200,
407                38400,
408                57600,
409                115200];
410     def setBaud(self,baud):
411         """Change the baud rate.  TODO fix this."""
412         rates=self.baudrates;
413         self.data=[baud];
414         print "Changing FET baud."
415         self.serialport.write(chr(0x00));
416         self.serialport.write(chr(0x80));
417         self.serialport.write(chr(1));
418         self.serialport.write(chr(baud));
419         
420         print "Changed host baud."
421         self.serialport.setBaudrate(rates[baud]);
422         time.sleep(1);
423         self.serialport.flushInput()
424         self.serialport.flushOutput()
425         
426         print "Baud is now %i." % rates[baud];
427         return;
428     def readbyte(self):
429         return ord(self.serialport.read(1));
430     def findbaud(self):
431         for r in self.baudrates:
432             print "\nTrying %i" % r;
433             self.serialport.setBaudrate(r);
434             #time.sleep(1);
435             self.serialport.flushInput()
436             self.serialport.flushOutput()
437             
438             for i in range(1,10):
439                 self.readbyte();
440             
441             print "Read %02x %02x %02x %02x" % (
442                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
443     def monitortest(self):
444         """Self-test several functions through the monitor."""
445         print "Performing monitor self-test.";
446         self.monitorclocking();
447         for f in range(0,3000):
448             a=self.peekword(0x0c00);
449             b=self.peekword(0x0c02);
450             if a!=0x0c04 and a!=0x0c06:
451                 print "ERROR Fetched %04x, %04x" % (a,b);
452             self.pokebyte(0x0021,0); #Drop LED
453             if self.peekbyte(0x0021)!=0:
454                 print "ERROR, P1OUT not cleared.";
455             self.pokebyte(0x0021,1); #Light LED
456             if not self.monitorecho():
457                 print "Echo test failed.";
458         print "Self-test complete.";
459         self.monitorclocking();
460     def monitorecho(self):
461         data="The quick brown fox jumped over the lazy dog.";
462         self.writecmd(self.MONITORAPP,0x81,len(data),data);
463         if self.data!=data:
464             if self.verbose: print "Comm error recognized by monitorecho().";
465             return 0;
466         return 1;
467     def monitorclocking(self):
468         """Return the 16-bit clocking value."""
469         return "0x%04x" % self.monitorgetclock();
470     
471     def monitorsetclock(self,clock):
472         """Set the clocking value."""
473         self.poke16(0x56, clock);
474     def monitorgetclock(self):
475         """Get the clocking value."""
476         return self.peek16(0x56);
477     # The following functions ought to be implemented in
478     # every client.
479
480     def infostring(self):
481         a=self.peekbyte(0xff0);
482         b=self.peekbyte(0xff1);
483         return "%02x%02x" % (a,b);
484     def lock(self):
485         print "Locking Unsupported.";
486     def erase(self):
487         print "Erasure Unsupported.";
488     def setup(self):
489         return;
490     def start(self):
491         return;
492     def test(self):
493         print "Unimplemented.";
494         return;
495     def status(self):
496         print "Unimplemented.";
497         return;
498     def halt(self):
499         print "Unimplemented.";
500         return;
501     def resume(self):
502         print "Unimplemented.";
503         return;
504     def getpc(self):
505         print "Unimplemented.";
506         return 0xdead;
507     def flash(self,file):
508         """Flash an intel hex file to code memory."""
509         print "Flash not implemented.";
510     def dump(self,file,start=0,stop=0xffff):
511         """Dump an intel hex file from code memory."""
512         print "Dump not implemented.";
513     def peek32(self,address, memory="vn"):
514         return (self.peek16(address,memory)+
515                 (self.peek16(address+2,memory)<<16));
516     def peek16(self,address, memory="vn"):
517         return (self.peek8(address,memory)+
518                 (self.peek8(address+1,memory)<<8));
519     def peek8(self,address, memory="vn"):
520         return self.peekbyte(address); #monitor
521     def peekword(self,address, memory="vn"):
522         return self.peek(address); #monitor
523     
524     def loadsymbols(self):
525         return;