MSP430X2 support is sufficient to read memory!
[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     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 and os.environ.get("GOODFET")!=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=0, data=[], blocks=1):
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         
60         self.readcmd(blocks);  #Uncomment this later, to ensure a response.
61     def readcmd(self,blocks=1):
62         """Read a reply from the GoodFET."""
63         self.app=ord(self.serialport.read(1));
64         self.verb=ord(self.serialport.read(1));
65         self.count=ord(self.serialport.read(1));
66         self.data=self.serialport.read(self.count*blocks);
67         #print "READ %02x %02x %02x " % (self.app, self.verb, self.count);
68         return self.data;
69         
70     #Monitor stuff
71     def peekbyte(self,address):
72         """Read a byte of memory from the monitor."""
73         self.data=[address&0xff,address>>8];
74         self.writecmd(0,0x02,2,self.data);
75         #self.readcmd();
76         return ord(self.data[0]);
77     def peekword(self,address):
78         """Read a word of memory from the monitor."""
79         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
80     def pokebyte(self,address,value):
81         """Set a byte of memory by the monitor."""
82         self.data=[address&0xff,address>>8,value];
83         self.writecmd(0,0x03,3,self.data);
84         return ord(self.data[0]);
85     def dumpmem(self,begin,end):
86         i=begin;
87         while i<end:
88             print "%04x %04x" % (i, self.peekword(i));
89             i+=2;
90     def monitor_ram_pattern(self):
91         """Overwrite all of RAM with 0xBEEF."""
92         self.writecmd(0,0x90,0,self.data);
93         return;
94     def monitor_ram_depth(self):
95         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
96         self.writecmd(0,0x91,0,self.data);
97         return ord(self.data[0])+(ord(self.data[1])<<8);
98     
99     #Baud rates.
100     baudrates=[115200, 
101                9600,
102                19200,
103                38400,
104                57600,
105                115200];
106     def setBaud(self,baud):
107         """Change the baud rate.  TODO fix this."""
108         rates=self.baudrates;
109         self.data=[baud];
110         print "Changing FET baud."
111         self.serialport.write(chr(0x00));
112         self.serialport.write(chr(0x80));
113         self.serialport.write(chr(1));
114         self.serialport.write(chr(baud));
115         
116         print "Changed host baud."
117         self.serialport.setBaudrate(rates[baud]);
118         time.sleep(1);
119         self.serialport.flushInput()
120         self.serialport.flushOutput()
121         
122         print "Baud is now %i." % rates[baud];
123         return;
124     def readbyte(self):
125         return ord(self.serialport.read(1));
126     def findbaud(self):
127         for r in self.baudrates:
128             print "\nTrying %i" % r;
129             self.serialport.setBaudrate(r);
130             #time.sleep(1);
131             self.serialport.flushInput()
132             self.serialport.flushOutput()
133             
134             for i in range(1,10):
135                 self.readbyte();
136             
137             print "Read %02x %02x %02x %02x" % (
138                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
139     def monitortest(self):
140         """Self-test several functions through the monitor."""
141         print "Performing monitor self-test.";
142         
143         if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
144             print "ERROR Fetched wrong value from 0x0c04.";
145         self.pokebyte(0x0021,0); #Drop LED
146         if self.peekbyte(0x0021)!=0:
147             print "ERROR, P1OUT not cleared.";
148         self.pokebyte(0x0021,1); #Light LED
149         
150         print "Self-test complete.";
151     
152     
153
154     def I2Csetup(self):
155         """Move the FET into the I2C application."""
156         self.writecmd(0x02,0x10,0,self.data); #SPI/SETUP
157     def I2Cstart(self):
158         """Start an I2C transaction."""
159         self.writecmd(0x02,0x20,0,self.data); #SPI/SETUP
160     def I2Cstop(self):
161         """Stop an I2C transaction."""
162         self.writecmd(0x02,0x21,0,self.data); #SPI/SETUP
163     def I2Cread(self,len=1):
164         """Read len bytes by I2C."""
165         self.writecmd(0x02,0x00,1,[len]); #SPI/SETUP
166         return self.data;
167     def I2Cwrite(self,bytes):
168         """Write bytes by I2C."""
169         self.writecmd(0x02,0x01,len(bytes),bytes); #SPI/SETUP
170         return ord(self.data[0]);
171 class GoodFETSPI(GoodFET):
172     def SPIsetup(self):
173         """Move the FET into the SPI application."""
174         self.writecmd(0x01,0x10,0,self.data); #SPI/SETUP
175         
176     def SPItrans8(self,byte):
177         """Read and write 8 bits by SPI."""
178         data=self.SPItrans([byte]);
179         return ord(data[0]);
180     
181     def SPItrans(self,data):
182         """Exchange data by SPI."""
183         self.data=data;
184         self.writecmd(0x01,0x00,len(data),data);
185         return self.data;
186
187 class GoodFETSPIFlash(GoodFETSPI):
188     JEDECmanufacturers={0xFF: "MISSING",
189                         0xEF: "Winbond",
190                         0xC2: "MXIC",
191                         0x20: "Numonyx/ST"
192                         };
193
194     JEDECdevices={0xFFFFFF: "MISSING",
195                   0xEF3014: "W25X80L",
196                   0xEF3013: "W25X40L",
197                   0xEF3012: "W25X20L",
198                   0xEF3011: "W25X10L",
199                   0xC22014: "MX25L8005",
200                   0xC22013: "MX25L4005",
201                   0x204011: "M45PE10"
202                   };
203     JEDECsizes={0x14: 0x100000,
204                 0x13: 0x080000,
205                 0x12: 0x040000,
206                 0x11: 0x020000}
207     JEDECsize=0;
208
209     def SPIjedec(self):
210         """Grab an SPI Flash ROM's JEDEC bytes."""
211         data=[0x9f, 0, 0, 0];
212         data=self.SPItrans(data);
213         #print "Manufacturer: %02x\nType: %02x\nCapacity: %02x" % (ord(data[1]),ord(data[2]),ord(data[3]));
214         self.JEDECmanufacturer=ord(data[1]);
215         self.JEDECtype=ord(data[2]);
216         self.JEDECcapacity=ord(data[3]);
217         self.JEDECsize=self.JEDECsizes.get(self.JEDECcapacity);
218         if self.JEDECsize==None:
219             self.JEDECsize=0;
220         self.JEDECdevice=(ord(data[1])<<16)+(ord(data[2])<<8)+ord(data[3]);
221         return data;
222     def SPIpeek(self,adr):
223         """Grab a byte from an SPI Flash ROM."""
224         data=[0x03,
225               (adr&0xFF0000)>>16,
226               (adr&0xFF00)>>8,
227               adr&0xFF,
228               0];
229         self.SPItrans(data);
230         return ord(self.data[4]);
231     def SPIpeekblock(self,adr,blocks=1):
232         """Grab a few block from an SPI Flash ROM.  Block size is unknown"""
233         data=[(adr&0xFF0000)>>16,
234               (adr&0xFF00)>>8,
235               adr&0xFF,
236               blocks];
237         
238         self.writecmd(0x01,0x02,4,data,blocks);
239         return self.data;
240     
241     def SPIpokebyte(self,adr,val):
242         self.SPIpokebytes(adr,[val]);
243     def SPIpokebytes(self,adr,data):
244         #self.SPIwriteenable();
245         adranddata=[(adr&0xFF0000)>>16,
246               (adr&0xFF00)>>8,
247               adr&0xFF
248               ]+data;
249         self.writecmd(0x01,0x03,
250                       len(adranddata),adranddata);
251         
252     def SPIchiperase(self):
253         """Mass erase an SPI Flash ROM."""
254         self.writecmd(0x01,0x81,0,[]);
255     def SPIwriteenable(self):
256         """SPI Flash Write Enable"""
257         data=[0x06];
258         self.SPItrans(data);
259         
260     def SPIjedecmanstr(self):
261         """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
262         man=self.JEDECmanufacturers.get(self.JEDECmanufacturer)
263         if man==0:
264             man="UNKNOWN";
265         return man;
266     
267     def SPIjedecstr(self):
268         """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
269         man=self.JEDECmanufacturers.get(self.JEDECmanufacturer);
270         if man==0:
271             man="UNKNOWN";
272         device=self.JEDECdevices.get(self.JEDECdevice);
273         if device==0:
274             device="???"
275         return "%s %s" % (man,device);
276
277 class GoodFETCC(GoodFET):
278     """A GoodFET variant for use with Chipcon 8051 Zigbe SoC."""
279     def CChaltcpu(self):
280         """Halt the CPU."""
281         self.writecmd(0x30,0x86,0,self.data);
282     def CCreleasecpu(self):
283         """Resume the CPU."""
284         self.writecmd(0x30,0x87,0,self.data);
285     def CCtest(self):
286         self.CCreleasecpu();
287         self.CChaltcpu();
288         #print "Status: %s" % self.CCstatusstr();
289         
290         #Grab ident three times, should be equal.
291         ident1=self.CCident();
292         ident2=self.CCident();
293         ident3=self.CCident();
294         if(ident1!=ident2 or ident2!=ident3):
295             print "Error, repeated ident attempts unequal."
296             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
297         
298         #Single step, printing PC.
299         print "Tracing execution at startup."
300         for i in range(1,15):
301             pc=self.CCgetPC();
302             byte=self.CCpeekcodebyte(i);
303             #print "PC=%04x, %02x" % (pc, byte);
304             self.CCstep_instr();
305         
306         print "Verifying that debugging a NOP doesn't affect the PC."
307         for i in range(1,15):
308             pc=self.CCgetPC();
309             self.CCdebuginstr([0x00]);
310             if(pc!=self.CCgetPC()):
311                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
312         
313         
314         #print "Status: %s." % self.CCstatusstr();
315         #Exit debugger
316         self.CCstop();
317         print "Done.";
318
319     def CCsetup(self):
320         """Move the FET into the CC2430/CC2530 application."""
321         #print "Initializing Chipcon.";
322         self.writecmd(0x30,0x10,0,self.data);
323     def CCrd_config(self):
324         """Read the config register of a Chipcon."""
325         self.writecmd(0x30,0x82,0,self.data);
326         return ord(self.data[0]);
327     def CCwr_config(self,config):
328         """Write the config register of a Chipcon."""
329         self.writecmd(0x30,0x81,1,[config&0xFF]);
330     
331     CCversions={0x0100:"CC1110",
332                 0x8500:"CC2430",
333                 0x8900:"CC2431",
334                 0x8100:"CC2510",
335                 0x9100:"CC2511",
336                 0xFF00:"CCmissing"};
337     def CCidentstr(self):
338         ident=self.CCident();
339         chip=self.CCversions.get(ident&0xFF00);
340         return "%s/r%02x" % (chip, ident&0xFF); 
341     def CCident(self):
342         """Get a chipcon's ID."""
343         self.writecmd(0x30,0x8B,0,None);
344         chip=ord(self.data[0]);
345         rev=ord(self.data[1]);
346         return (chip<<8)+rev;
347     def CCgetPC(self):
348         """Get a chipcon's PC."""
349         self.writecmd(0x30,0x83,0,None);
350         hi=ord(self.data[0]);
351         lo=ord(self.data[1]);
352         return (hi<<8)+lo;
353     def CCdebuginstr(self,instr):
354         self.writecmd(0x30,0x88,len(instr),instr);
355         return ord(self.data[0]);
356     def CCpeekcodebyte(self,adr):
357         """Read the contents of code memory at an address."""
358         self.data=[adr&0xff, (adr&0xff00)>>8];
359         self.writecmd(0x30,0x90,2,self.data);
360         return ord(self.data[0]);
361     def CCpeekdatabyte(self,adr):
362         """Read the contents of data memory at an address."""
363         self.data=[adr&0xff, (adr&0xff00)>>8];
364         self.writecmd(0x30,0x91, 2, self.data);
365         return ord(self.data[0]);
366     def CCpokedatabyte(self,adr,val):
367         """Write a byte to data memory."""
368         self.data=[adr&0xff, (adr&0xff00)>>8, val];
369         self.writecmd(0x30, 0x92, 3, self.data);
370         return ord(self.data[0]);
371     def CCchiperase(self):
372         """Erase all of the target's memory."""
373         self.writecmd(0x30,0x80,0,None);
374     def CCstatus(self):
375         """Check the status."""
376         self.writecmd(0x30,0x84,0,None);
377         return ord(self.data[0])
378     CCstatusbits={0x80 : "erased",
379                   0x40 : "pcon_idle",
380                   0x20 : "halted",
381                   0x10 : "pm0",
382                   0x08 : "halted",
383                   0x04 : "locked",
384                   0x02 : "oscstable",
385                   0x01 : "overflow"};
386     def CCstatusstr(self):
387         """Check the status as a string."""
388         status=self.CCstatus();
389         str="";
390         i=1;
391         while i<0x100:
392             if(status&i):
393                 str="%s %s" %(self.CCstatusbits[i],str);
394             i*=2;
395         return str;
396     def CCstart(self):
397         """Start debugging."""
398         self.writecmd(0x30,0x20,0,self.data);
399         ident=self.CCidentstr();
400         print "Target identifies as %s." % ident;
401         #print "Status: %s." % self.CCstatusstr();
402         self.CCreleasecpu();
403         self.CChaltcpu();
404         #print "Status: %s." % self.CCstatusstr();
405         
406     def CCstop(self):
407         """Stop debugging."""
408         self.writecmd(0x30,0x21,0,self.data);
409     def CCstep_instr(self):
410         """Step one instruction."""
411         self.writecmd(0x30,0x89,0,self.data);
412