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