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