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