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