297111ef8696c24a16412421febb7c60eb1afc0e
[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 ugly as sin, for bootstrapping the firmware only.
7 # Rewrite cleanly as soon as is convenient.
8
9 import sys, time, string, cStringIO, struct, glob, serial, os;
10
11
12 class GoodFET:
13     def __init__(self, *args, **kargs):
14         self.data=[0];
15     def timeout(self):
16         print "timeout\n";
17     def serInit(self, port=None):
18         """Open the serial port"""
19         
20         if port is None:
21             port=os.environ.get("GOODFET");
22         
23         if port is None:
24             glob_list = glob.glob("/dev/tty.usbserial*");
25             if len(glob_list) > 0:
26                 port = glob_list[0];
27         if port is None:
28             glob_list = glob.glob("/dev/ttyUSB*");
29             if len(glob_list) > 0:
30                 port = glob_list[0];
31         
32         self.serialport = serial.Serial(
33             port,
34             #9600,
35             115200,
36             parity = serial.PARITY_NONE
37             )
38         #Drop DTR, which is !RST, low to begin the app.
39         self.serialport.setDTR(0);
40         self.serialport.flushInput()
41         self.serialport.flushOutput()
42         
43         #Read and handle the initial command.
44         #time.sleep(1);
45         self.readcmd(); #Read the first command.
46         if(self.verb!=0x7F):
47             print "Verb %02x is wrong.  Incorrect firmware?" % self.verb;
48         #print "Connected."
49     def writecmd(self, app, verb, count, data):
50         """Write a command and some data to the GoodFET."""
51         self.serialport.write(chr(app));
52         self.serialport.write(chr(verb));
53         self.serialport.write(chr(count));
54         #print "count=%02x, len(data)=%04x" % (count,len(data));
55         if count!=0:
56             for d in data:
57                 self.serialport.write(chr(d));
58         self.readcmd();  #Uncomment this later, to ensure a response.
59     def readcmd(self):
60         """Read a reply from the GoodFET."""
61         self.app=ord(self.serialport.read(1));
62         self.verb=ord(self.serialport.read(1));
63         self.count=ord(self.serialport.read(1));
64         if self.count>0:
65             self.data=self.serialport.read(self.count);
66         #print "READ %02x %02x %02x " % (self.app, self.verb, self.count);
67         
68     #Monitor stuff
69     def peekbyte(self,address):
70         """Read a byte of memory from the monitor."""
71         self.data=[address&0xff,address>>8];
72         self.writecmd(0,0x02,2,self.data);
73         #self.readcmd();
74         return ord(self.data[0]);
75     def peekword(self,address):
76         """Read a word of memory from the monitor."""
77         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
78     def pokebyte(self,address,value):
79         """Set a byte of memory by the monitor."""
80         self.data=[address&0xff,address>>8,value];
81         self.writecmd(0,0x03,3,self.data);
82         return ord(self.data[0]);
83     def dumpmem(self,begin,end):
84         i=begin;
85         while i<end:
86             print "%04x %04x" % (i, self.peekword(i));
87             i+=2;
88     def monitor_ram_pattern(self):
89         """Overwrite all of RAM with 0xBEEF."""
90         self.writecmd(0,0x90,0,self.data);
91         return;
92     def monitor_ram_depth(self):
93         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
94         self.writecmd(0,0x91,0,self.data);
95         return ord(self.data[0])+(ord(self.data[1])<<8);
96     
97     #Baud rates.
98     baudrates=[115200, 
99                9600,
100                19200,
101                38400,
102                57600,
103                115200];
104     def setBaud(self,baud):
105         """Change the baud rate.  TODO fix this."""
106         rates=self.baudrates;
107         self.data=[baud];
108         print "Changing FET baud."
109         self.serialport.write(chr(0x00));
110         self.serialport.write(chr(0x80));
111         self.serialport.write(chr(1));
112         self.serialport.write(chr(baud));
113         
114         print "Changed host baud."
115         self.serialport.setBaudrate(rates[baud]);
116         time.sleep(1);
117         self.serialport.flushInput()
118         self.serialport.flushOutput()
119         
120         print "Baud is now %i." % rates[baud];
121         return;
122     def readbyte(self):
123         return ord(self.serialport.read(1));
124     def findbaud(self):
125         for r in self.baudrates:
126             print "\nTrying %i" % r;
127             self.serialport.setBaudrate(r);
128             #time.sleep(1);
129             self.serialport.flushInput()
130             self.serialport.flushOutput()
131             
132             for i in range(1,10):
133                 self.readbyte();
134             
135             print "Read %02x %02x %02x %02x" % (
136                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
137     def monitortest(self):
138         """Self-test several functions through the monitor."""
139         print "Performing monitor self-test.";
140         
141         if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
142             print "ERROR Fetched wrong value from 0x0c04.";
143         self.pokebyte(0x0021,0); #Drop LED
144         if self.peekbyte(0x0021)!=0:
145             print "ERROR, P1OUT not cleared.";
146         self.pokebyte(0x0021,1); #Light LED
147         
148         print "Self-test complete.";
149     
150     def SPIsetup(self):
151         """Moved the FET into the SPI application."""
152         self.writecmd(0x01,0x10,0,self.data); #SPI/SETUP
153         
154     def SPItrans8(self,byte):
155         """Read and write 8 bits by SPI."""
156         data=self.SPItrans([byte]);
157         return ord(data[0]);
158     
159     def SPItrans(self,data):
160         """Exchange data by SPI."""
161         self.data=data;
162         self.writecmd(0x01,0x00,len(data),data);
163         return self.data;
164     
165     JEDECmanufacturers={0xFF: "MISSING",
166                         0xEF: "Winbond",
167                         0xC2: "MXIC",
168                         0x20: "Numonyx/ST"
169                         };
170
171     JEDECdevices={0xFFFFFF: "MISSING",
172                   0xEF3014: "W25X80L",
173                   0xEF3013: "W25X40L",
174                   0xEF3012: "W25X20L",
175                   0xEF3011: "W25X10L",
176                   0xC22014: "MX25L8005",
177                   0xC22013: "MX25L4005",
178                   0x204011: "M45PE10"
179                   };
180     def SPIjedec(self):
181         """Grab an SPI Flash ROM's JEDEC bytes."""
182         data=[0x9f, 0, 0, 0];
183         data=self.SPItrans(data);
184         #print "Manufacturer: %02x\nType: %02x\nCapacity: %02x" % (ord(data[1]),ord(data[2]),ord(data[3]));
185         self.JEDECmanufacturer=ord(data[1]);
186         self.JEDECtype=ord(data[2]);
187         self.JEDECcapacity=ord(data[3]);
188         self.JEDECdevice=(ord(data[1])<<16)+(ord(data[2])<<8)+ord(data[3]);
189         return data;
190     def SPIpeek(self,adr):
191         """Grab a byte from an SPI Flash ROM."""
192         data=[0x03,
193               (adr&0xFF0000)>>16,
194               (adr&0xFF00)>>8,
195               adr&0xFF,
196               0];
197         self.SPItrans(data);
198         return ord(self.data[4]);
199     def SPIpeekblock(self,adr):
200         """Grab a byte from an SPI Flash ROM."""
201         data=[(adr&0xFF0000)>>16,
202               (adr&0xFF00)>>8,
203               adr&0xFF];
204         
205         self.writecmd(0x01,0x02,3,data);
206         return self.data;
207     
208     def SPIpokebyte(self,adr,val):
209         self.SPIpokebytes(adr,[val]);
210     def SPIpokebytes(self,adr,data):
211         #self.SPIwriteenable();
212         adranddata=[(adr&0xFF0000)>>16,
213               (adr&0xFF00)>>8,
214               adr&0xFF
215               ]+data;
216         self.writecmd(0x01,0x03,
217                       len(adranddata),adranddata);
218         
219     def SPIchiperase(self):
220         """Mass erase an SPI Flash ROM."""
221         self.writecmd(0x01,0x81,0,[]);
222     def SPIwriteenable(self):
223         """SPI Flash Write Enable"""
224         data=[0x06];
225         self.SPItrans(data);
226         
227     def SPIjedecmanstr(self):
228         """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
229         man=self.JEDECmanufacturers.get(self.JEDECmanufacturer)
230         if man==0:
231             man="UNKNOWN";
232         return man;
233     
234     def SPIjedecstr(self):
235         """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
236         man=self.JEDECmanufacturers.get(self.JEDECmanufacturer);
237         if man==0:
238             man="UNKNOWN";
239         device=self.JEDECdevices.get(self.JEDECdevice);
240         if device==0:
241             device="???"
242         return "%s %s" % (man,device);
243     def MSP430setup(self):
244         """Move the FET into the MSP430 JTAG application."""
245         print "Initializing MSP430.";
246         self.writecmd(0x11,0x10,0,self.data);
247
248     
249     
250     def CCsetup(self):
251         """Move the FET into the CC2430/CC2530 application."""
252         #print "Initializing Chipcon.";
253         self.writecmd(0x30,0x10,0,self.data);
254     def CCrd_config(self):
255         """Read the config register of a Chipcon."""
256         self.writecmd(0x30,0x82,0,self.data);
257         return ord(self.data[0]);
258     def CCwr_config(self,config):
259         """Write the config register of a Chipcon."""
260         self.writecmd(0x30,0x81,1,[config&0xFF]);
261     
262     CCversions={0x0100:"CC1110",
263                 0x8500:"CC2430",
264                 0x8900:"CC2431",
265                 0x8100:"CC2510",
266                 0x9100:"CC2511",
267                 0xFF00:"CCmissing"};
268     def CCidentstr(self):
269         ident=self.CCident();
270         chip=self.CCversions.get(ident&0xFF00);
271         return "%s/r%02x" % (chip, ident&0xFF); 
272     def CCident(self):
273         """Get a chipcon's ID."""
274         self.writecmd(0x30,0x8B,0,None);
275         chip=ord(self.data[0]);
276         rev=ord(self.data[1]);
277         return (chip<<8)+rev;
278     def CCgetPC(self):
279         """Get a chipcon's PC."""
280         self.writecmd(0x30,0x83,0,None);
281         hi=ord(self.data[0]);
282         lo=ord(self.data[1]);
283         return (hi<<8)+lo;
284     def CCdebuginstr(self,instr):
285         self.writecmd(0x30,0x88,len(instr),instr);
286         return ord(self.data[0]);
287     def MSP430peek(self,adr):
288         """Read the contents of memory at an address."""
289         self.data=[adr&0xff, (adr&0xff00)>>8];
290         self.writecmd(0x11,0x02,2,self.data);
291         return ord(self.data[0])+(ord(self.data[1])<<8);
292     def CCpeekcodebyte(self,adr):
293         """Read the contents of code memory at an address."""
294         self.data=[adr&0xff, (adr&0xff00)>>8];
295         self.writecmd(0x30,0x90,2,self.data);
296         return ord(self.data[0]);
297     def CCpeekdatabyte(self,adr):
298         """Read the contents of data memory at an address."""
299         self.data=[adr&0xff, (adr&0xff00)>>8];
300         self.writecmd(0x30,0x91, 2, self.data);
301         return ord(self.data[0]);
302     def CCpokedatabyte(self,adr,val):
303         """Write a byte to data memory."""
304         self.data=[adr&0xff, (adr&0xff00)>>8, val];
305         self.writecmd(0x30, 0x92, 3, self.data);
306         return ord(self.data[0]);
307     def CCchiperase(self):
308         """Erase all of the target's memory."""
309         self.writecmd(0x30,0x80,0,None);
310     def CCstatus(self):
311         """Check the status."""
312         self.writecmd(0x30,0x84,0,None);
313         return ord(self.data[0])
314     CCstatusbits={0x80 : "erased",
315                   0x40 : "pcon_idle",
316                   0x20 : "halted",
317                   0x10 : "pm0",
318                   0x08 : "halted",
319                   0x04 : "locked",
320                   0x02 : "oscstable",
321                   0x01 : "overflow"};
322     def CCstatusstr(self):
323         """Check the status as a string."""
324         status=self.CCstatus();
325         str="";
326         i=1;
327         while i<0x100:
328             if(status&i):
329                 str="%s %s" %(self.CCstatusbits[i],str);
330             i*=2;
331         return str;
332     def MSP430poke(self,adr,val):
333         """Read the contents of memory at an address."""
334         self.data=[adr&0xff, (adr&0xff00)>>8, val&0xff, (val&0xff00)>>8];
335         self.writecmd(0x11,0x03,4,self.data);
336         return;# ord(self.data[0])+(ord(self.data[1])<<8);
337     def MSP430start(self):
338         """Start debugging."""
339         self.writecmd(0x11,0x20,0,self.data);
340         ident=self.MSP430ident();
341         print "Target identifies as %04x." % ident;
342     
343     def CCstart(self):
344         """Start debugging."""
345         self.writecmd(0x30,0x20,0,self.data);
346         ident=self.CCidentstr();
347         print "Target identifies as %s." % ident;
348         #print "Status: %s." % self.CCstatusstr();
349         self.CCreleasecpu();
350         self.CChaltcpu();
351         #print "Status: %s." % self.CCstatusstr();
352         
353     def CCstop(self):
354         """Stop debugging."""
355         self.writecmd(0x30,0x21,0,self.data);
356     def CCstep_instr(self):
357         """Step one instruction."""
358         self.writecmd(0x30,0x89,0,self.data);
359     def MSP430stop(self):
360         """Stop debugging."""
361         self.writecmd(0x11,0x21,0,self.data);
362     def MSP430haltcpu(self):
363         """Halt the CPU."""
364         self.writecmd(0x11,0xA0,0,self.data);
365     def MSP430releasecpu(self):
366         """Resume the CPU."""
367         self.writecmd(0x11,0xA1,0,self.data);
368     def CChaltcpu(self):
369         """Halt the CPU."""
370         self.writecmd(0x30,0x86,0,self.data);
371     def CCreleasecpu(self):
372         """Resume the CPU."""
373         self.writecmd(0x30,0x87,0,self.data);
374     def MSP430shiftir8(self,ins):
375         """Shift the 8-bit Instruction Register."""
376         data=[ins];
377         self.writecmd(0x11,0x80,1,data);
378         return ord(self.data[0]);
379     def MSP430shiftdr16(self,dat):
380         """Shift the 16-bit Data Register."""
381         data=[dat&0xFF,(dat&0xFF00)>>8];
382         self.writecmd(0x11,0x81,2,data);
383         return ord(self.data[0])#+(ord(self.data[1])<<8);
384     def MSP430setinstrfetch(self):
385         """Set the instruction fetch mode."""
386         self.writecmd(0x11,0xC1,0,self.data);
387         return self.data[0];
388     def MSP430ident(self):
389         """Grab self-identification word from 0x0FF0 as big endian."""
390         i=self.MSP430peek(0x0ff0);
391         return ((i&0xFF00)>>8)+((i&0xFF)<<8)
392     def MSP430test(self):
393         """Test MSP430 JTAG.  Requires that a chip be attached."""
394         if self.MSP430ident()==0xffff:
395             print "Is anything connected?";
396         print "Testing RAM.";
397         temp=self.MSP430peek(0x0200);
398         self.MSP430poke(0x0200,0xdead);
399         if(self.MSP430peek(0x0200)!=0xdead):
400             print "Poke of 0x0200 did not set to 0xDEAD properly.";
401             return;
402         self.MSP430poke(0x0200,temp); #restore old value.
403     def MSP430flashtest(self):
404         self.MSP430masserase();
405         i=0x2500;
406         while(i<0xFFFF):
407             if(self.MSP430peek(i)!=0xFFFF):
408                 print "ERROR: Unerased flash at %04x."%i;
409             self.MSP430writeflash(i,0xDEAD);
410             i+=2;
411     def MSP430masserase(self):
412         """Erase MSP430 flash memory."""
413         self.writecmd(0x11,0xE3,0,None);
414     def MSP430writeflash(self,adr,val):
415         """Write a word of flash memory."""
416         if(self.MSP430peek(adr)!=0xFFFF):
417             print "FLASH ERROR: %04x not clear." % adr;
418         data=[adr&0xFF,(adr&0xFF00)>>8,val&0xFF,(val&0xFF00)>>8];
419         self.writecmd(0x11,0xE1,4,data);
420         rval=ord(self.data[0])+(ord(self.data[1])<<8);
421         if(val!=rval):
422             print "FLASH WRITE ERROR AT %04x.  Found %04x, wrote %04x." % (adr,rval,val);
423             
424     def MSP430dumpbsl(self):
425         self.MSP430dumpmem(0xC00,0xfff);
426     def MSP430dumpallmem(self):
427         self.MSP430dumpmem(0x200,0xffff);
428     def MSP430dumpmem(self,begin,end):
429         i=begin;
430         while i<end:
431             print "%04x %04x" % (i, self.MSP430peek(i));
432             i+=2;
433     def CCtest(self):
434         self.CCreleasecpu();
435         self.CChaltcpu();
436         #print "Status: %s" % self.CCstatusstr();
437         
438         #Grab ident three times, should be equal.
439         ident1=self.CCident();
440         ident2=self.CCident();
441         ident3=self.CCident();
442         if(ident1!=ident2 or ident2!=ident3):
443             print "Error, repeated ident attempts unequal."
444             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
445         
446         #Single step, printing PC.
447         print "Tracing execution at startup."
448         for i in range(1,15):
449             pc=self.CCgetPC();
450             byte=self.CCpeekcodebyte(i);
451             #print "PC=%04x, %02x" % (pc, byte);
452             self.CCstep_instr();
453         
454         print "Verifying that debugging a NOP doesn't affect the PC."
455         for i in range(1,15):
456             pc=self.CCgetPC();
457             self.CCdebuginstr([0x00]);
458             if(pc!=self.CCgetPC()):
459                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
460         
461         
462         #print "Status: %s." % self.CCstatusstr();
463         #Exit debugger
464         self.CCstop();
465         print "Done.";