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