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