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