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