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