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