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