More thorough monitor test.
[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;
15     if(name=="GoodFET" or name=="monitor"): return GoodFET.GoodFET();
16     elif name=="cc" or name=="chipcon": return GoodFETCC.GoodFETCC();
17     elif name=="avr": return GoodFETAVR.GoodFETAVR();
18     elif name=="spi": return GoodFETSPI.GoodFETSPI();
19     elif name=="msp430": return GoodFETMSP430.GoodFETMSP430();
20     
21     print "Unsupported target: %s" % name;
22     sys.exit(0);
23
24 class SymbolTable:
25     """GoodFET Symbol Table"""
26     db=sqlite3.connect(":memory:");
27     
28     def __init__(self, *args, **kargs):
29         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
30     def get(self,name):
31         self.db.commit();
32         c=self.db.cursor();
33         try:
34             c.execute("select adr,memory from symbols where name=?",(name,));
35             for row in c:
36                 #print "Found it.";
37                 sys.stdout.flush();
38                 return row[0];
39             #print "No dice.";
40         except:# sqlite3.OperationalError:
41             #print "SQL error.";
42             return eval(name);
43         return eval(name);
44     def define(self,adr,name,comment="",memory="vn",size=16):
45         self.db.execute("insert into symbols(adr,name,memory,size,comment)"
46                         "values(?,?,?,?,?);", (
47                 adr,name,memory,size,comment));
48         #print "Set %s=%s." % (name,adr);
49
50 class GoodFET:
51     """GoodFET Client Library"""
52
53     besilent=0;
54     app=0;
55     verb=0;
56     count=0;
57     data="";
58     verbose=False
59     
60     GLITCHAPP=0x71;
61     MONITORAPP=0x00;
62     symbols=SymbolTable();
63     
64     def __init__(self, *args, **kargs):
65         self.data=[0];
66     def getConsole(self):
67         from GoodFETConsole import GoodFETConsole;
68         return GoodFETConsole(self);
69     def name2adr(self,name):
70         return self.symbols.get(name);
71     def timeout(self):
72         print "timeout\n";
73     def serInit(self, port=None, timeout=2):
74         """Open the serial port"""
75         # Make timeout None to wait forever, 0 for non-blocking mode.
76         
77         if port is None and os.environ.get("GOODFET")!=None:
78             glob_list = glob.glob(os.environ.get("GOODFET"));
79             if len(glob_list) > 0:
80                 port = glob_list[0];
81             else:
82                 port = os.environ.get("GOODFET");
83         if port is None:
84             glob_list = glob.glob("/dev/tty.usbserial*");
85             if len(glob_list) > 0:
86                 port = glob_list[0];
87         if port is None:
88             glob_list = glob.glob("/dev/ttyUSB*");
89             if len(glob_list) > 0:
90                 port = glob_list[0];
91         
92         
93         self.serialport = serial.Serial(
94             port,
95             #9600,
96             115200,
97             parity = serial.PARITY_NONE,
98             timeout=timeout
99             )
100         
101         self.verb=0;
102         attempts=0;
103         connected=0;
104         while connected==0:
105             while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
106                 self.serialport.flushInput()
107                 self.serialport.flushOutput()
108                 #Explicitly set RTS and DTR to halt board.
109                 self.serialport.setRTS(1);
110                 self.serialport.setDTR(1);
111                 #Drop DTR, which is !RST, low to begin the app.
112                 self.serialport.setDTR(0);
113                 self.serialport.flushInput()
114                 self.serialport.flushOutput()
115                 #time.sleep(.1);
116                 attempts=attempts+1;
117                 self.readcmd(); #Read the first command.
118             #Here we have a connection, but maybe not a good one.
119             connected=1;
120             olds=self.infostring();
121             self.monitorclocking();
122             for foo in range(1,30):
123                 if not self.monitorecho():
124                     print "Comm error, resyncing.";
125                     connected=0;
126                     break;
127         if self.verbose: print "Connected after %02i attempts." % attempts;
128         self.mon_connected();
129         
130     def getbuffer(self,size=0x1c00):
131         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
132         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
133     def writecmd(self, app, verb, count=0, data=[]):
134         """Write a command and some data to the GoodFET."""
135         self.serialport.write(chr(app));
136         self.serialport.write(chr(verb));
137         
138         #if data!=None:
139         #    count=len(data); #Initial count ignored.
140         
141         #print "TX %02x %02x %04x" % (app,verb,count);
142         
143         #little endian 16-bit length
144         self.serialport.write(chr(count&0xFF));
145         self.serialport.write(chr(count>>8));
146
147         if self.verbose:
148             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
149         
150         #print "count=%02x, len(data)=%04x" % (count,len(data));
151         
152         if count!=0:
153             if(isinstance(data,list)):
154                 for i in range(0,count):
155                 #print "Converting %02x at %i" % (data[i],i)
156                     data[i]=chr(data[i]);
157             #print type(data);
158             outstr=''.join(data);
159             self.serialport.write(outstr);
160         if not self.besilent:
161             return self.readcmd()
162         else:
163             return []
164
165     def readcmd(self):
166         """Read a reply from the GoodFET."""
167         while 1:#self.serialport.inWaiting(): # Loop while input data is available
168             try:
169                 #print "Reading...";
170                 self.app=ord(self.serialport.read(1));
171                 #print "APP=%2x" % self.app;
172                 self.verb=ord(self.serialport.read(1));
173                 #print "VERB=%02x" % self.verb;
174                 self.count=(
175                     ord(self.serialport.read(1))
176                     +(ord(self.serialport.read(1))<<8)
177                     );
178
179                 if self.verbose:
180                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
181             
182                 #Debugging string; print, but wait.
183                 if self.app==0xFF:
184                     if self.verb==0xFF:
185                         print "# DEBUG %s" % self.serialport.read(self.count)
186                     elif self.verb==0xFE:
187                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
188                     sys.stdout.flush();
189                 else:
190                     self.data=self.serialport.read(self.count);
191                     return self.data;
192             except TypeError:
193                 if self.connected:
194                     print "Error: waiting for serial read timed out (most likely).";
195                     print "This shouldn't happen after syncing.  Exiting for safety.";
196                     sys.exit(-1)
197                 return self.data;
198     #Glitching stuff.
199     def glitchApp(self,app):
200         """Glitch into a device by its application."""
201         self.data=[app&0xff];
202         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
203         #return ord(self.data[0]);
204     def glitchVerb(self,app,verb,data):
205         """Glitch during a transaction."""
206         if data==None: data=[];
207         self.data=[app&0xff, verb&0xFF]+data;
208         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
209         #return ord(self.data[0]);
210     def glitchstart(self):
211         """Glitch into the AVR application."""
212         self.glitchVerb(self.APP,0x20,None);
213     def glitchstarttime(self):
214         """Measure the timer of the START verb."""
215         return self.glitchTime(self.APP,0x20,None);
216     def glitchTime(self,app,verb,data):
217         """Time the execution of a verb."""
218         if data==None: data=[];
219         self.data=[app&0xff, verb&0xFF]+data;
220         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
221         return ord(self.data[0])+(ord(self.data[1])<<8);
222     def glitchVoltages(self,low=0x0880, high=0x0fff):
223         """Set glitching voltages. (0x0fff is max.)"""
224         self.data=[low&0xff, (low>>8)&0xff,
225                    high&0xff, (high>>8)&0xff];
226         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
227         #return ord(self.data[0]);
228     def glitchRate(self,count=0x0800):
229         """Set glitching count period."""
230         self.data=[count&0xff, (count>>8)&0xff];
231         self.writecmd(self.GLITCHAPP,0x91,2,
232                       self.data);
233         #return ord(self.data[0]);
234     
235     
236     #Monitor stuff
237     def silent(self,s=0):
238         """Transmissions halted when 1."""
239         self.besilent=s;
240         print "besilent is %i" % self.besilent;
241         self.writecmd(0,0xB0,1,[s]);
242     connected=0;
243     def mon_connected(self):
244         """Announce to the monitor that the connection is good."""
245         self.connected=1;
246         self.writecmd(0,0xB1,0,[]);
247     def out(self,byte):
248         """Write a byte to P5OUT."""
249         self.writecmd(0,0xA1,1,[byte]);
250     def dir(self,byte):
251         """Write a byte to P5DIR."""
252         self.writecmd(0,0xA0,1,[byte]);
253     def call(self,adr):
254         """Call to an address."""
255         self.writecmd(0,0x30,2,
256                       [adr&0xFF,(adr>>8)&0xFF]);
257     def execute(self,code):
258         """Execute supplied code."""
259         self.writecmd(0,0x31,2,#len(code),
260                       code);
261     def peekbyte(self,address):
262         """Read a byte of memory from the monitor."""
263         self.data=[address&0xff,address>>8];
264         self.writecmd(0,0x02,2,self.data);
265         #self.readcmd();
266         return ord(self.data[0]);
267     def peekword(self,address):
268         """Read a word of memory from the monitor."""
269         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
270     def pokebyte(self,address,value):
271         """Set a byte of memory by the monitor."""
272         self.data=[address&0xff,address>>8,value];
273         self.writecmd(0,0x03,3,self.data);
274         return ord(self.data[0]);
275     def dumpmem(self,begin,end):
276         i=begin;
277         while i<end:
278             print "%04x %04x" % (i, self.peekword(i));
279             i+=2;
280     def monitor_ram_pattern(self):
281         """Overwrite all of RAM with 0xBEEF."""
282         self.writecmd(0,0x90,0,self.data);
283         return;
284     def monitor_ram_depth(self):
285         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
286         self.writecmd(0,0x91,0,self.data);
287         return ord(self.data[0])+(ord(self.data[1])<<8);
288     
289     #Baud rates.
290     baudrates=[115200, 
291                9600,
292                19200,
293                38400,
294                57600,
295                115200];
296     def setBaud(self,baud):
297         """Change the baud rate.  TODO fix this."""
298         rates=self.baudrates;
299         self.data=[baud];
300         print "Changing FET baud."
301         self.serialport.write(chr(0x00));
302         self.serialport.write(chr(0x80));
303         self.serialport.write(chr(1));
304         self.serialport.write(chr(baud));
305         
306         print "Changed host baud."
307         self.serialport.setBaudrate(rates[baud]);
308         time.sleep(1);
309         self.serialport.flushInput()
310         self.serialport.flushOutput()
311         
312         print "Baud is now %i." % rates[baud];
313         return;
314     def readbyte(self):
315         return ord(self.serialport.read(1));
316     def findbaud(self):
317         for r in self.baudrates:
318             print "\nTrying %i" % r;
319             self.serialport.setBaudrate(r);
320             #time.sleep(1);
321             self.serialport.flushInput()
322             self.serialport.flushOutput()
323             
324             for i in range(1,10):
325                 self.readbyte();
326             
327             print "Read %02x %02x %02x %02x" % (
328                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
329     def monitortest(self):
330         """Self-test several functions through the monitor."""
331         print "Performing monitor self-test.";
332         self.monitorclocking();
333         for f in range(0,3000):
334             a=self.peekword(0x0c00);
335             b=self.peekword(0x0c02);
336             if a!=0x0c04 and a!=0x0c06:
337                 print "ERROR Fetched %04x, %04x" % (a,b);
338             self.pokebyte(0x0021,0); #Drop LED
339             if self.peekbyte(0x0021)!=0:
340                 print "ERROR, P1OUT not cleared.";
341             self.pokebyte(0x0021,1); #Light LED
342             if not self.monitorecho():
343                 print "Echo test failed.";
344         print "Self-test complete.";
345         self.monitorclocking();
346     def monitorecho(self):
347         data="The quick brown fox jumped over the lazy dog.";
348         self.writecmd(self.MONITORAPP,0x81,len(data),data);
349         if self.data!=data:
350             if verbose: print "Comm error recognized.";
351             return 0;
352         return 1;
353     def monitorclocking(self):
354         DCOCTL=self.peekbyte(0x0056);
355         BCSCTL1=self.peekbyte(0x0057);
356         return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
357
358     # The following functions ought to be implemented in
359     # every client.
360
361     def infostring(self):
362         a=self.peekbyte(0xff0);
363         b=self.peekbyte(0xff1);
364         return "%02x%02x" % (a,b);
365     def lock(self):
366         print "Locking Unsupported.";
367     def erase(self):
368         print "Erasure Unsupported.";
369     def setup(self):
370         return;
371     def start(self):
372         return;
373     def test(self):
374         print "Unimplemented.";
375         return;
376     def status(self):
377         print "Unimplemented.";
378         return;
379     def halt(self):
380         print "Unimplemented.";
381         return;
382     def resume(self):
383         print "Unimplemented.";
384         return;
385     def getpc(self):
386         print "Unimplemented.";
387         return 0xdead;
388     def flash(self,file):
389         """Flash an intel hex file to code memory."""
390         print "Flash not implemented.";
391     def dump(self,file,start=0,stop=0xffff):
392         """Dump an intel hex file from code memory."""
393         print "Dump not implemented.";
394
395     def peek32(self,address, memory="vn"):
396         return (self.peek16(address,memory)+
397                 (self.peek16(address+2,memory)<<16));
398     def peek16(self,address, memory="vn"):
399         return (self.peek8(address,memory)+
400                 (self.peek8(address+1,memory)<<8));
401     def peek8(self,address, memory="vn"):
402         return self.peekbyte(address); #monitor
403     def loadsymbols(self):
404         return;