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