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